diff --git a/ASSETS.md b/ASSETS.md index a483174dc1..a21d7a9692 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -154,6 +154,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | +| `assets/icons/dc-corner-tool.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | | @@ -194,6 +195,15 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-grad-stroke-along.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-stroke-within.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-gradient.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-bar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-column.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-line.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-pie.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-radar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-scatter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-stacked-bar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-stacked-column.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-group-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -203,6 +213,9 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-join-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-knife.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-lasso-enclosing.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-lasso-polygonal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-lasso.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-line-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-line.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-list-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -230,6 +243,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-path-eraser.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pathfinder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-perspective-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-perspective.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pf-crop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pf-divide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -248,6 +262,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | | | `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-recolor-arrow.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a right arrow, a Recolor Artwork row that is recolored) | MIT OR Apache-2.0 | | +| `assets/icons/dc-recolor-arrow-off.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dashed line without a head, a Recolor Artwork row that is excluded) | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-reference-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -262,7 +278,11 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-screen-mode.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-selection.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shape-builder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-shared-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-slice-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-slice.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-slide-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -273,7 +293,14 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-swatch-kinds.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-swatch-process.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a square, a process color) | MIT OR Apache-2.0 | | | `assets/icons/dc-swatch-spot.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dot in a ring, a spot color) | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-screener.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-scruncher.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-shifter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-sizer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-spinner.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-stainer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-styler.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..12f4bb334f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -148,6 +148,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers 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. @@ -158,6 +159,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/assets/icons/dc-corner-tool.svg b/assets/icons/dc-corner-tool.svg new file mode 100644 index 0000000000..7b467ce306 --- /dev/null +++ b/assets/icons/dc-corner-tool.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-area.svg b/assets/icons/dc-graph-area.svg new file mode 100644 index 0000000000..4aae0a6663 --- /dev/null +++ b/assets/icons/dc-graph-area.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-bar.svg b/assets/icons/dc-graph-bar.svg new file mode 100644 index 0000000000..ee08f9eba3 --- /dev/null +++ b/assets/icons/dc-graph-bar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-column.svg b/assets/icons/dc-graph-column.svg new file mode 100644 index 0000000000..bf896fe563 --- /dev/null +++ b/assets/icons/dc-graph-column.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-line.svg b/assets/icons/dc-graph-line.svg new file mode 100644 index 0000000000..46a2ef7ecd --- /dev/null +++ b/assets/icons/dc-graph-line.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-pie.svg b/assets/icons/dc-graph-pie.svg new file mode 100644 index 0000000000..a406bf7b7a --- /dev/null +++ b/assets/icons/dc-graph-pie.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-radar.svg b/assets/icons/dc-graph-radar.svg new file mode 100644 index 0000000000..82fe72d29e --- /dev/null +++ b/assets/icons/dc-graph-radar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-scatter.svg b/assets/icons/dc-graph-scatter.svg new file mode 100644 index 0000000000..c674fc8cd1 --- /dev/null +++ b/assets/icons/dc-graph-scatter.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-stacked-bar.svg b/assets/icons/dc-graph-stacked-bar.svg new file mode 100644 index 0000000000..989dfaaf58 --- /dev/null +++ b/assets/icons/dc-graph-stacked-bar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-stacked-column.svg b/assets/icons/dc-graph-stacked-column.svg new file mode 100644 index 0000000000..f7f234f280 --- /dev/null +++ b/assets/icons/dc-graph-stacked-column.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso-enclosing.svg b/assets/icons/dc-lasso-enclosing.svg new file mode 100644 index 0000000000..c15d730f97 --- /dev/null +++ b/assets/icons/dc-lasso-enclosing.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso-polygonal.svg b/assets/icons/dc-lasso-polygonal.svg new file mode 100644 index 0000000000..4f69572878 --- /dev/null +++ b/assets/icons/dc-lasso-polygonal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso.svg b/assets/icons/dc-lasso.svg new file mode 100644 index 0000000000..5143e0d447 --- /dev/null +++ b/assets/icons/dc-lasso.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-perspective-select.svg b/assets/icons/dc-perspective-select.svg new file mode 100644 index 0000000000..e31fa0b254 --- /dev/null +++ b/assets/icons/dc-perspective-select.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-recolor-arrow-off.svg b/assets/icons/dc-recolor-arrow-off.svg new file mode 100644 index 0000000000..9a972d3804 --- /dev/null +++ b/assets/icons/dc-recolor-arrow-off.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-recolor-arrow.svg b/assets/icons/dc-recolor-arrow.svg new file mode 100644 index 0000000000..41dd50e3be --- /dev/null +++ b/assets/icons/dc-recolor-arrow.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-shared-edge.svg b/assets/icons/dc-shared-edge.svg new file mode 100644 index 0000000000..7301265544 --- /dev/null +++ b/assets/icons/dc-shared-edge.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slice-select.svg b/assets/icons/dc-slice-select.svg new file mode 100644 index 0000000000..9cdce42a1e --- /dev/null +++ b/assets/icons/dc-slice-select.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slice.svg b/assets/icons/dc-slice.svg new file mode 100644 index 0000000000..5a1791b428 --- /dev/null +++ b/assets/icons/dc-slice.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slide-anchor.svg b/assets/icons/dc-slide-anchor.svg new file mode 100644 index 0000000000..0107876985 --- /dev/null +++ b/assets/icons/dc-slide-anchor.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-screener.svg b/assets/icons/dc-symbol-screener.svg new file mode 100644 index 0000000000..cbb9aa899f --- /dev/null +++ b/assets/icons/dc-symbol-screener.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-scruncher.svg b/assets/icons/dc-symbol-scruncher.svg new file mode 100644 index 0000000000..4b4203acba --- /dev/null +++ b/assets/icons/dc-symbol-scruncher.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-shifter.svg b/assets/icons/dc-symbol-shifter.svg new file mode 100644 index 0000000000..bd3c2b67d2 --- /dev/null +++ b/assets/icons/dc-symbol-shifter.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-sizer.svg b/assets/icons/dc-symbol-sizer.svg new file mode 100644 index 0000000000..771627cf72 --- /dev/null +++ b/assets/icons/dc-symbol-sizer.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-spinner.svg b/assets/icons/dc-symbol-spinner.svg new file mode 100644 index 0000000000..c5a3ab7423 --- /dev/null +++ b/assets/icons/dc-symbol-spinner.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-stainer.svg b/assets/icons/dc-symbol-stainer.svg new file mode 100644 index 0000000000..79f2541d28 --- /dev/null +++ b/assets/icons/dc-symbol-stainer.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-styler.svg b/assets/icons/dc-symbol-styler.svg new file mode 100644 index 0000000000..b81ffaa5e7 --- /dev/null +++ b/assets/icons/dc-symbol-styler.svg @@ -0,0 +1 @@ + diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fdd18c4693..6d5cb0f1a5 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -219,7 +219,7 @@ pub fn set_live_art(f: LiveArt, inputs: LiveInputs) { } /// The registered [`LiveInputs`] now, 0 while nothing is registered. -fn live_inputs() -> u64 { +pub fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 38a62e0341..7c13b8f755 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -293,8 +293,15 @@ pub fn is_white(p: &Paint) -> bool { } } +/// Whether `p` is paper white: white ([`is_white`]) and not a tint above 0% of one of the spot +/// inks `spots` ([`Document::spot_ink_names`]). The white of a spot swatch (an opaque white ink, +/// for example) is an ink of its own; a 0% tint puts no ink down. +pub fn is_paper_white(p: &Paint, spots: &BTreeSet) -> bool { + is_white(p) && !matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && spots.contains(name)) +} + /// Discard White Overprint (Document Setup) as output applies it: whether it is on, and the spot -/// inks a white tint of which still overprints ([`Document::spot_ink`]). +/// inks a white tint of which still overprints ([`Document::spot_ink_names`]). #[derive(Clone, Debug, Default, PartialEq)] pub struct DiscardWhite { on: bool, @@ -304,8 +311,13 @@ pub struct DiscardWhite { impl DiscardWhite { /// The document's setting and spot inks. pub fn of(doc: &Document) -> Self { - let spot_inks = doc.swatches_iter().map(|s| &s.name).filter(|n| doc.swatch(n).is_some_and(|s| s.spot && s.paint.color().is_some())); - Self { on: doc.setup.discard_white_overprint, spot_inks: spot_inks.cloned().collect() } + Self::printing(doc, |_| true) + } + + /// The document's setting when only the spot inks for which `spot` is true print as spot + /// inks: a white of another one (converted to process inks) is paper white. + pub fn printing(doc: &Document, spot: impl Fn(&str) -> bool) -> Self { + Self { on: doc.setup.discard_white_overprint, spot_inks: doc.spot_ink_names().into_iter().filter(|n| spot(n)).collect() } } /// The setting `on`, with no spot inks. @@ -314,32 +326,31 @@ impl DiscardWhite { } /// Whether `p` loses its overprint: the setting is on and `p` is paper white - /// ([`is_white`]), not a tint above 0% of a spot ink, which prints as that ink. + /// ([`Self::paper_white`]), not a tint above 0% of a spot ink, which prints as that ink. pub fn discards(&self, p: &Paint) -> bool { - let spot = matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.spot_inks.contains(name)); - self.on && is_white(p) && !spot + self.on && self.paper_white(p) + } + + /// Whether `p` is paper white with these spot inks ([`is_paper_white`]), whether the setting + /// is on or off: an overprinting paper white puts no ink down. + pub fn paper_white(&self, p: &Paint) -> bool { + is_paper_white(p, &self.spot_inks) } } impl Document { + /// The names of the spot swatches that a color linked by name prints as: a name whose first + /// swatch ([`Document::swatch`]) is not a solid spot color is left out. + pub fn spot_ink_names(&self) -> BTreeSet { + let mut seen = BTreeSet::new(); + self.swatches_iter().filter(|s| seen.insert(s.name.as_str()) && s.spot && s.paint.color().is_some()).map(|s| s.name.clone()).collect() + } + /// The names of the spot swatches. pub fn spot_names(&self) -> Vec { self.swatches_iter().filter(|s| s.spot).map(|s| s.name.clone()).collect() } - /// Whether `p` is a tint above 0% of a spot swatch with a solid color, which prints as an ink - /// of its own even when its color is white ([`is_white`]); a link is judged by the first - /// swatch of its name. - pub fn spot_ink(&self, p: &Paint) -> bool { - matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())) - } - - /// Whether Discard White Overprint (Document Setup) takes the overprint off `p` - /// ([`DiscardWhite::discards`]). - pub fn discards_white_overprint(&self, p: &Paint) -> bool { - self.setup.discard_white_overprint && is_white(p) && !self.spot_ink(p) - } - /// Files from before per-fill/stroke overprint listed the objects marked Overprint Black /// under [`LEGACY_OVERPRINT_KEY`]: their 100% black fills and strokes overprint now. pub fn migrate_overprint_black(&mut self) { @@ -488,6 +499,58 @@ mod tests { assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it"); } + #[test] + fn a_white_spot_ink_overprints_under_discard_white() { + let mut d = Document::new(100.0, 100.0); + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + d.swatches.push(vectorcraft_color::Swatch { name: "Process White".into(), paint: Paint::solid(white), global: true, spot: false }); + let spot = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }; + let process = Paint::Solid { color: white, swatch: Some("Process White".into()), tint: 1.0 }; + let paper = Paint::solid(white); + assert!(d.setup.discard_white_overprint, "on by default"); + d.swatches.push(vectorcraft_color::Swatch { + name: "Red Ink".into(), + paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), + global: true, + spot: true, + }); + // A 0% tint of a spot ink resolves to white and puts no ink down. + let no_red = Paint::Solid { color: white, swatch: Some("Red Ink".into()), tint: 0.0 }; + let no_white = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 0.0 }; + let half_white = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 0.5 }; + let discard = DiscardWhite::of(&d); + assert!(discard.discards(&paper), "paper white knocks out"); + assert!(discard.discards(&process), "so does a global process white"); + assert!(!discard.discards(&spot) && !discard.discards(&half_white), "a white spot ink is an ink"); + assert!(discard.discards(&no_red) && discard.discards(&no_white), "a 0% tint of a spot ink is paper white"); + assert!(!is_paper_white(&spot, &d.spot_ink_names()) && is_paper_white(&paper, &d.spot_ink_names())); + let converted = DiscardWhite::printing(&d, |n| n != "Opaque White"); + assert!(converted.discards(&spot), "a white spot ink printed as process inks is paper white"); + // A spot swatch after a process one of the same name: a link finds the process one. + d.swatches.push(vectorcraft_color::Swatch { name: "Process White".into(), paint: Paint::solid(white), global: true, spot: true }); + assert!(DiscardWhite::of(&d).discards(&process), "the first swatch of the name decides"); + // A spot swatch without a solid color prints a linked solid as its own process color. + d.swatches.push(vectorcraft_color::Swatch { name: "Empty".into(), paint: Paint::None, global: true, spot: true }); + let empty = Paint::Solid { color: white, swatch: Some("Empty".into()), tint: 1.0 }; + assert!(DiscardWhite::of(&d).discards(&empty), "so it is paper white"); + d.setup.discard_white_overprint = false; + assert!(!DiscardWhite::of(&d).discards(&paper), "off: white overprints too"); + + // The previews and plates darken the spot ink and leave paper white knocking out. + let blend = |fill: Paint| { + let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(fill, Paint::None, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + let mut a = Arc::new(n); + darken_overprints(&mut a, &discard, &BTreeMap::new()); + a.appearance.fill().map(|f| f.blend) + }; + assert_eq!(blend(spot), Some(BlendMode::Darken)); + assert_eq!(blend(paper), Some(BlendMode::Normal)); + } + #[test] fn apply_deep_copies_only_the_nodes_that_change() { let k = cmyk(0.0, 0.0, 0.0, 1.0); @@ -560,7 +623,7 @@ mod tests { }; let spot = linked("White Ink", 0.5); assert_eq!(blend(spot.clone(), spot.clone()), (BlendMode::Darken, Some(BlendMode::Darken))); - assert!(doc.spot_ink(&spot) && !discard.discards(&spot)); + assert!(!discard.paper_white(&spot) && !discard.discards(&spot)); for knocks_out in [linked("White Ink", 0.0), linked("Paper", 1.0), Paint::solid(white)] { assert!(discard.discards(&knocks_out), "{knocks_out:?}"); assert_eq!(blend(knocks_out.clone(), knocks_out.clone()).0, BlendMode::Normal, "{knocks_out:?}"); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 305ae19e3b..56f955106b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -846,8 +846,9 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. pub use addons::{fold_source, print_hidden}; -/// Document Info's category titles and the Objects category's count labels. -pub use docinfo::{CATEGORIES, OBJECT_LABELS}; +/// Document Info's category titles, the Objects category's count labels, and how its image rows +/// write a resolution and a number of bytes. +pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index f17f93ff9b..8bf1e00d16 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Print Ink Fixes", ["Object", "Plug-ins", "Color Effects"], None, - "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting; a white linked to a spot swatch at a tint above 0% is an ink and keeps it), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", has_doc, print_fixes::run ), diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs index 8440e597f0..12c4f3a7c2 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -1,14 +1,15 @@ //! Print Ink Fixes (`addon.color.printFixes`, Object › Plug-ins › Color Effects › Print Ink //! Fixes…): a CMYK document's inks made ready for print in one undo step. Colours with more total -//! ink than the limit are scaled down to it, white fills and strokes stop overprinting, and black +//! ink than the limit are scaled down to it, paper white fills and strokes stop overprinting, and black //! ones start to, as Edit › Edit Colors › Overprint Black sets it. +use std::collections::BTreeSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Color; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_doc::overprint::{OverprintBlack, is_white}; +use vectorcraft_doc::overprint::{OverprintBlack, is_paper_white}; use vectorcraft_doc::{ColorMode, Node, NodeKind}; use super::super::super::colorcmds::{Recolor, Scope, keeping_series_paint}; @@ -78,8 +79,9 @@ impl Fixes { } /// Remove white overprint from `n`'s own fills and strokes and its characters': true when - /// that changed anything. - fn unset_white(&self, n: &mut Node) -> bool { + /// that changed anything. A white linked to one of the spot inks `inks` is an ink and keeps + /// overprinting ([`is_paper_white`]). + fn unset_white(&self, n: &mut Node, inks: &BTreeSet) -> bool { let mut changed = false; let mut off = |aimed: bool, white: bool, flag: &mut bool| { if aimed && white && *flag { @@ -89,31 +91,32 @@ impl Fixes { }; for it in &mut n.appearance.items { let aimed = if it.is_fill() { self.fill } else { self.stroke }; - let white = is_white(it.paint()); + let white = is_paper_white(it.paint(), inks); off(aimed, white, it.overprint_mut()); } if let NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { - off(self.fill, is_white(&r.style.fill), &mut r.style.overprint_fill); - off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke); + off(self.fill, is_paper_white(&r.style.fill, inks), &mut r.style.overprint_fill); + off(self.stroke, is_paper_white(&r.style.stroke, inks), &mut r.style.overprint_stroke); } } // A colorized image's color is its fill. if n.colorize_overprints() { - let white = n.extras().colorize.as_deref().is_some_and(is_white); + let white = n.extras().colorize.as_deref().is_some_and(|p| is_paper_white(p, inks)); off(self.fill, white, &mut n.extras_mut().colorize_overprint); } changed } /// The overprint fixes on `n` and everything inside it: (objects whose white overprint was - /// removed, objects set to overprint black). - fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String]) -> (usize, usize) { - let white = usize::from(self.remove_white_overprint && self.unset_white(n)); + /// removed, objects set to overprint black). `spots`: the document's spot swatch names; `inks`: + /// those that linked colors print as ([`vectorcraft_doc::Document::spot_ink_names`]). + fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String], inks: &BTreeSet) -> (usize, usize) { + let white = usize::from(self.remove_white_overprint && self.unset_white(n, inks)); 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().filter(|c| !c.is_ruler_guide()) { - let (w, b) = self.overprint(Arc::make_mut(c), black, spots); + let (w, b) = self.overprint(Arc::make_mut(c), black, spots, inks); counts = (counts.0 + w, counts.1 + b); } counts @@ -159,10 +162,10 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 { return Ok(ink); } - let spots = d.spot_names(); + let (spots, inks) = (d.spot_names(), d.spot_ink_names()); for id in &ids { if let Some(n) = d.node_mut(*id) { - let (w, b) = fixes.overprint(n, &black, &spots); + let (w, b) = fixes.overprint(n, &black, &spots, &inks); (white, blacks) = (white + w, blacks + b); } } diff --git a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs index e4c1915879..8e28701572 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs @@ -101,6 +101,20 @@ fn white_overprint_goes_and_black_overprint_comes_at_the_threshold() { assert_eq!(s.execute(C, &json!({"overprintBlack": 90, "fill": false})).unwrap()["changed"], 0); } +#[test] +fn a_white_spot_ink_keeps_its_overprint() { + let white = cmyk(0.0, 0.0, 0.0, 0.0); + let (mut s, ids) = doc(&[(white.clone(), true), (white.clone(), true)]); + s.execute("swatch.new", &json!({"name": "Opaque White", "color": white, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(fill(&s, ids[1]).1, "the swatch keeps the overprint"); + let v = s.execute(C, &json!({"removeWhiteOverprint": true})).unwrap(); + assert_eq!(v["whiteOverprintRemoved"], 1, "{v}"); + assert_eq!([fill(&s, ids[0]).1, fill(&s, ids[1]).1], [false, true], "paper white stops; the spot white is an ink"); +} + #[test] fn bad_requests_and_rgb_documents_are_refused() { let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), true)]); diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 586dc9947e..2c14c3deba 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -4,8 +4,8 @@ //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes //! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents -//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add -//! Bounding Circle ([`bounding`]). +//! ([`tangents`]), Tangent Circle ([`tangent_circle`]), Add Bounding Rectangle and Add +//! Bounding Circle ([`bounding`]) and Add Inscribed Circle ([`inscribed`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -14,6 +14,7 @@ mod bridge; mod corners; #[cfg(test)] mod effect_tests; +mod inscribed; mod shape; mod shared_edge; mod tangent_circle; @@ -190,6 +191,7 @@ pub fn specs() -> Vec { v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v.extend(bounding::specs()); + v.extend(inscribed::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs index 954a4f829a..b82b67832e 100644 --- a/crates/engine/src/cmd/addons/pathtools/bounding.rs +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec { /// Enabled with a selection that is not an object of a symbol instance's art, which /// [`selected_roots_to_transform`] refuses. -fn whole_objects(s: &Session) -> std::result::Result<(), String> { +pub(super) fn whole_objects(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; no_symbol_part(s) } diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed.rs b/crates/engine/src/cmd/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..e240fdf43d --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed.rs @@ -0,0 +1,97 @@ +//! Add Inscribed Circle: the largest live circle inside each selected closed path or compound +//! path. The circle is the pathops crate's +//! ([`inscribed_circle`](vectorcraft_pathops::addons::pathtools::inscribed_circle)). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, PathData}; +use vectorcraft_pathops::addons::pathtools::{self as pt, InscribedError}; + +use super::super::super::edit::selected_roots_to_transform; +use super::super::super::{CommandSpec, bad, cmd}; +use super::bounding::whole_objects; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command. +pub(crate) const COMMAND: &str = "addon.pathtools.inscribedCircle"; +/// The undo step's name. +const LABEL: &str = "Add Inscribed Circle"; +/// How far a live circle's four curves reach past a true circle, as a share of its radius: at +/// most 0.0273%, about 20° from each axis. +const CIRCLE_BULGE: f64 = 3e-4; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.inscribedCircle", + "Add Inscribed Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and before it is drawn its radius is within 0.02 pt of the largest (when the filled area's box is at least 10 pt across on its narrower side; for a smaller one, within a five-hundredth of that side; a curve whose control polygon is longer than 4096² times the flattening tolerance, half the search's precision (83,886 pt at 0.005 pt), is flattened more coarsely, and the circle can be smaller by as much; a curved hole narrower than the flattening tolerance can also make it smaller; a shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 of the tolerance). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn 0.03% smaller and stays inside where it touches. Holes and gaps narrower than 1e-6 pt close up, and edges can move by as much, as in the other path operations. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; inside an isolated compound path they join it and take its appearance; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces once flattened, or the searches of the selected objects together measure more than 134,217,728 distances from a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length that it flattens to no area even at the finest tolerance (\"object N is too complex to measure\") → {id: the first circle, ids}", + whole_objects, + inscribed_circle + )] +} + +/// The outline of path or compound path `id` and its fill rule; `None` for anything else, an open +/// path, or a compound path with an open member. +fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> { + let n = d.node(id)?; + let (paths, rule): (Vec<&PathData>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, .. } => (vec![path], *rule), + NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule), + _ => return None, + }; + let subpaths: Vec<_> = paths.iter().flat_map(|p| p.subpaths.iter()).filter(|sp| !sp.anchors.is_empty()).collect(); + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed) { + return None; + } + Some((PathData::new(subpaths.into_iter().cloned().collect()), rule)) +} + +fn inscribed_circle(s: &mut Session, _p: &Value) -> Result { + // The roots leave out selected layers, which are not paths either. + let st = s.doc()?; + if let Some(layer) = st.selection.objects.iter().find(|id| st.doc.node(**id).is_some_and(Node::is_layer)) { + return Err(bad(COMMAND, format!("object {} is not a closed path or compound path", layer.0))); + } + let roots = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let mut circles = vec![]; + // The searches share one work limit, so the command stays bounded however many objects are + // selected. + let mut work = pt::MAX_INSCRIBED_WORK; + for id in roots { + let value = id.0; + let Some((path, rule)) = outline(d, id) else { + return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path"))); + }; + let c = pt::inscribed_circle_within(&path, rule, &mut work).map_err(|e| match e { + InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")), + InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")), + })?; + circles.push(c); + } + // Path art: inside an isolated compound path, the circles join it, as Tangent Circle's do. + let parent = s.doc()?.target_parent_for_path()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ids = s.edit(LABEL, |d, sel| { + let mut ids = vec![]; + for c in &circles { + // Smaller by the curves' bulge, so the drawn circle stays inside where it touches. + let (r, at) = (c.radius / (1.0 + CIRCLE_BULGE), c.center); + let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) }; + let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(n.id); + d.insert(parent, usize::MAX, n)?; + } + sel.set(ids.iter().copied()); + Ok(ids) + })?; + let first = ids.first().map_or(0, |id| id.0); + Ok(json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::>() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..86f0342ff7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs @@ -0,0 +1,221 @@ +//! Add Inscribed Circle: the largest circle in a square, a concave shape and a ring compound path +//! under its fill rule, one circle per object as one undo step, the drawn circle inside where its +//! curves bulge, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::Point; + +use super::COMMAND; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +/// The center and radius of the live circle `id`. +fn circle(s: &Session, id: NodeId) -> (Point, f64) { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(live), .. } => match live.as_ref() { + LiveShape::Ellipse { w, h, xf, .. } => { + assert!((w - h).abs() < 1e-9, "a circle, not an ellipse"); + (*xf * Point::new(w / 2.0, h / 2.0), w / 2.0) + } + other => panic!("not a live ellipse: {other:?}"), + }, + other => panic!("not a live shape: {other:?}"), + } +} + +/// The smallest drawn radius for a largest circle of radius `largest`: smaller by the curves' +/// bulge, and by the search's 0.02 pt. +fn least(largest: f64) -> f64 { + largest / (1.0 + super::CIRCLE_BULGE) - 0.02 +} + +/// The command on the selection fails with a message holding `want`, and the document is as it was. +fn refused(s: &mut Session, want: &str) { + let (undo, objects) = (undo_len(s), object_count(s)); + let e = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + assert_eq!((undo_len(s), object_count(s)), (undo, objects)); +} + +/// The circle in a square sits at its center and touches its sides, gets the current paint, goes +/// on top of the layer and is selected; one undo removes it. +#[test] +fn a_square_gets_the_circle_that_touches_its_sides() { + let mut s = session(); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()); + let (undo, objects) = (undo_len(&s), object_count(&s)); + let out = s.execute(COMMAND, &json!({})).unwrap(); + let id = id_of(&out); + let (center, r) = circle(&s, id); + assert!((center - Point::new(150.0, 150.0)).hypot() < 0.02 && r <= 50.0 + 1e-6 && r > least(50.0), "{center:?} {r}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + let d = &s.doc().unwrap().doc; + let parent = d.parent_of(sq).unwrap(); + assert_eq!(d.parent_of(id), Some(parent)); + assert_eq!(d.node(parent).unwrap().children().unwrap().last().map(|n| n.id), Some(id), "on top of the layer"); + // The current paint, as the rectangle drawn before got it. + let (n, r) = (d.node(id).unwrap(), d.node(sq).unwrap()); + assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint())); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), objects); +} + +/// The circle in an L sits in its corner, inside the shape, where the box's center is outside. +#[test] +fn a_concave_shape_gets_the_circle_in_its_corner() { + let mut s = session(); + let anchors = [(0, 0), (100, 0), (100, 30), (30, 30), (30, 100), (0, 100)].map(|(x, y)| json!({"x": x, "y": y})); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let (center, r) = circle(&s, id); + let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(r <= largest + 1e-6 && r > least(largest), "{r}"); + assert!(center.x < 30.0 && center.y < 30.0, "{center:?}"); +} + +/// A compound path of two concentric circles: under even-odd the inner one is a hole, and the +/// circle lies in the ring beside it. Under nonzero it is a hole while the two circles turn +/// opposite ways, and with both turning the same way the circle fills the outer one. +#[test] +fn a_ring_compound_path_gets_a_circle_by_its_fill_rule() { + let mut s = session(); + let outer = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap()); + let inner = id_of(&s.execute("shape.ellipse", &json!({"x": 160, "y": 160, "width": 80, "height": 80})).unwrap()); + select(&mut s, &[outer, inner]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let ring = Point::new(200.0, 200.0); + let cases = [("evenOdd", false, 70.0, 30.0), ("nonZero", false, 70.0, 30.0), ("nonZero", true, 0.0, 100.0), ("evenOdd", true, 70.0, 30.0)]; + for (rule, same_way, around, largest) in cases { + select(&mut s, &[compound]); + let both = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + s.execute("path.reverse", &json!({"ids": both, "reversed": true})).unwrap(); + if !same_way { + s.execute("path.reverse", &json!({"ids": [both[1]], "reversed": false})).unwrap(); + } + s.execute("path.setFillRule", &json!({"rule": rule, "ids": [compound.0]})).unwrap(); + select(&mut s, &[compound]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let (center, r) = circle(&s, id); + assert!(r > least(largest) && r < largest + 0.0003 * 140.0, "{rule} {same_way}: {r}"); + assert!(((center - ring).hypot() - around).abs() < 0.1, "{rule} {same_way}: {center:?}"); + } +} + +/// Each selected path gets its own circle, all as one undo step; a path of a compound path +/// selected on its own gets a circle of its own outline. +#[test] +fn each_selected_path_gets_a_circle_in_one_step() { + let mut s = session(); + let a = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap()); + let b = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 40, "height": 80})).unwrap()); + select(&mut s, &[a, b]); + let undo = undo_len(&s); + let ids = ids_of(&s.execute(COMMAND, &json!({})).unwrap()); + assert_eq!(ids.len(), 2); + assert_eq!(undo_len(&s), undo + 1); + let centers: Vec = ids.iter().map(|id| circle(&s, *id).0).collect(); + assert!(centers.iter().any(|c| c.x < 40.0) && centers.iter().any(|c| c.x > 100.0), "{centers:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[a, b]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let member = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id; + select(&mut s, &[member]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let r = circle(&s, id).1; + assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}"); + // Inside the isolated compound path, the circle joins it. + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + select(&mut s, &[member]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(compound)); +} + +/// The drawn circle stays inside a large square turned so that it touches the square's sides +/// where its curves bulge most past a true circle, about 20° from each axis. +#[test] +fn the_drawn_circle_stays_inside_where_its_curves_bulge() { + let mut s = session(); + let (center, half) = (Point::new(1200.0, 1200.0), 1000.0); + for degrees in [15.0_f64, 19.4, 25.0] { + let (sin, cos) = degrees.to_radians().sin_cos(); + let corner = |u: f64, v: f64| json!({"x": center.x + u * cos - v * sin, "y": center.y + u * sin + v * cos}); + let anchors = [(-half, -half), (half, -half), (half, half), (-half, half)].map(|(u, v)| corner(u, v)); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { + panic!("not a path"); + }; + for seg in path.to_bezpath().segments() { + for i in 0..=200 { + let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 200.0) - center; + let (u, v) = (p.x * cos + p.y * sin, -p.x * sin + p.y * cos); + assert!(u.abs().max(v.abs()) <= half, "{degrees}°: ({u}, {v}) is outside the square"); + } + } + } +} + +/// An open path, an object that is not a path or compound path, a path that fills no area and an +/// empty selection are errors, and nothing is drawn. +#[test] +fn open_paths_other_objects_and_no_selection_are_refused() { + let mut s = session(); + assert!(s.execute(COMMAND, &json!({})).is_err(), "nothing selected"); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap()); + select(&mut s, &[open]); + refused(&mut s, "is not a closed path or compound path"); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()); + select(&mut s, &[sq]); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + select(&mut s, &[group]); + refused(&mut s, "is not a closed path or compound path"); + // One refused object leaves the other selected objects without a circle too. + select(&mut s, &[group, open]); + refused(&mut s, "is not a closed path or compound path"); + let flat = [(0, 300), (100, 300), (50, 300)].map(|(x, y)| json!({"x": x, "y": y})); + let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap()); + select(&mut s, &[flat]); + refused(&mut s, "fills no area"); + // A selected layer is refused too, alone or with a path. + let mut layer = None; + s.doc().unwrap().doc.walk(|n| { + if n.is_layer() { + layer.get_or_insert(n.id); + } + }); + let layer = layer.unwrap(); + let path = id_of(&s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap()); + for ids in [vec![layer], vec![layer, path]] { + select(&mut s, &ids); + refused(&mut s, "is not a closed path or compound path"); + } +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 99ccd2d828..ac993f7ab5 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -1198,6 +1198,24 @@ pub(crate) fn capture_series_paint_writes( super::graph::capture_series_top_paints(d, &rows) } +/// Store on the graph the opacity and blend mode of each row an edit wrote (`written`: an object with the index of the +/// row) on the series marks among them, when that row is the topmost visible one of its kind, also when the mark +/// already showed that opacity: it replaces the opacity another mark of the series left on the graph. When the edit +/// reaches several marks of one series, the frontmost one sets what the graph stores. Returns whether the stored +/// opacity or blend mode changed. +pub(crate) fn capture_series_opacity_writes(d: &mut vectorcraft_doc::Document, written: &[(NodeId, usize)]) -> bool { + let ids: Vec = written.iter().map(|(id, _)| *id).collect(); + // A later mark's capture replaces an earlier one's: take them in paint order. + let rows: Vec<(NodeId, bool)> = series_children_in_paint_order(d, &ids) + .into_iter() + .flat_map(|id| { + let shown = written.iter().filter(move |(w, _)| *w == id).filter_map(|(_, at)| Some((id, top_row_kind(&d.node(id)?.appearance, *at)?))); + shown.collect::>() + }) + .collect(); + super::graph::capture_series_opacity(d, &rows) +} + /// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`. fn top_row_kind(ap: &Appearance, at: usize) -> Option { let fill = ap.items.get(at)?.is_fill(); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 79dbd6e488..aa3cf36cba 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -14,13 +14,14 @@ //! the document's Spot Colors option says. Pasting back into the document the objects came from //! uses its resources as they are now. -use std::cell::OnceCell; +use std::cell::{Cell, OnceCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::pattern::pattern_paint; use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX}; use vectorcraft_doc::{ Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, @@ -610,6 +611,9 @@ pub(crate) enum SwatchChoice { pub(crate) struct SwatchChoices { all: SwatchChoice, by_name: BTreeMap, + /// Names a swatch or pattern that comes in under a numbered name skips, each with the swatch + /// it is reserved for, which still comes in under it when the document does not use it. + reserved: Arc>, } impl SwatchChoices { @@ -621,16 +625,22 @@ impl SwatchChoices { }; match p.get("swatchConflict") { None | Some(Value::Null) => Ok(Self::default()), - Some(Value::Object(m)) => { - Ok(Self { all: SwatchChoice::Merge, by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::>()? }) - } - Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), + Some(Value::Object(m)) => Ok(Self { + all: SwatchChoice::Merge, + by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::>()?, + reserved: Arc::default(), + }), + Some(v) => Ok(Self { all: one(v)?, ..Self::default() }), } } /// Add for every conflict: each pasted swatch whose name the document gives another color /// comes in renamed. pub(crate) fn add_all() -> Self { - Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + Self { all: SwatchChoice::Add, ..Self::default() } + } + /// These choices, with numbered names skipping the names of `names` ([`SwatchChoices::reserved`]). + pub(crate) fn reserving(self, names: &Arc>) -> Self { + Self { reserved: Arc::clone(names), ..self } } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) @@ -1154,6 +1164,9 @@ pub(crate) struct Imported { pub added_designs: BTreeSet, /// The global and spot colors that took the document's color (merged). merged_swatches: BTreeSet, + /// Whether a name [`SwatchChoices::reserving`] reserves changed the name a swatch or pattern + /// came in under. + pub reserved_named: bool, } impl Imported { @@ -1425,9 +1438,39 @@ impl Clipboard { let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art)); let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| { - // Its swatch comes along under the same name. - let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n)); + // Its swatch comes along under the same name, which skips the reserved swatch + // names too, except its own name when that is reserved for a swatch of it. + let skipped = Cell::new(false); + let ours = |w: &Swatch| matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == def.name); + let name = unique_name(&def.name, |n| { + let used = d.pattern(n).is_some() || d.swatch_name_taken(n); + let held = !used && choices.reserved.get(n).is_some_and(|w| n != def.name || !ours(w)); + skipped.set(skipped.get() || held); + used || held + }); + out.reserved_named |= skipped.get(); add_pattern(d, PatternDef { name: name.clone(), ..def.clone() }); + // The name is left to a swatch it is reserved for that places the pattern + // otherwise; the swatch the pattern comes with gets another. + let placed = choices.reserved.get(&name).is_some_and(|w| ours(w) && w.paint != pattern_paint(&def.name)); + if placed && d.swatches.last().is_some_and(|w| w.name == name) { + let other = unique_name(&name, |n| n == name || d.swatch_name_taken(n) || choices.reserved.contains_key(n)); + if let Some(w) = d.swatches.last_mut() { + w.name = other; + } + } + // A pattern that comes in under another name than the one reserved for its + // swatch, because a pattern has that name, keeps that name for its swatch + // when no swatch or color group uses it. + let own = name != def.name + && !d.swatch_name_taken(&def.name) + && choices.reserved.get(&def.name).is_some_and(|w| w.paint == pattern_paint(&def.name)); + if own && d.swatches.last().is_some_and(|w| w.name == name) { + if let Some(w) = d.swatches.last_mut() { + w.name = def.name.clone(); + } + out.reserved_named = true; + } Placed::added(&def.name, name) }); added_patterns.extend(p.new_name(&def.name)); @@ -1660,7 +1703,9 @@ impl Clipboard { out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { - add_swatch(d, w, same_doc) + let (p, reserved_named) = add_swatch(d, w, w, same_doc, &choices.reserved, &out.relink); + out.reserved_named |= reserved_named; + p }; out.placed(Res::Swatch, &w.name, &p); } @@ -1675,7 +1720,8 @@ impl Clipboard { for def in self.swatches.iter().filter(|w| !is_base(w) && used.carries(w)) { let mut w = def.clone(); out.relink.paint(&mut w.paint); - let p = add_swatch(d, &w, same_doc); + let (p, reserved_named) = add_swatch(d, &w, def, same_doc, &choices.reserved, &out.relink); + out.reserved_named |= reserved_named; out.placed(Res::Swatch, &def.name, &p); } } @@ -1877,13 +1923,62 @@ pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[St clip.import_used(d, &used, &SwatchChoices::default(), false) } +/// Whether `name` ends in a space and a number, as a numbered copy's name ("Ink 2") does. +pub(crate) fn numbered_name(name: &str) -> bool { + name.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())) +} + /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups -/// share one namespace). -fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed { +/// share one namespace) → where it went, and whether `reserved` changed its name. `source` is the +/// pasted swatch `w` stands for, before its links were relinked. A numbered name skips the names +/// in `reserved`. A numbered name in `reserved` ("Ink 2") that `d` does not use is kept for the +/// swatch it is reserved for: that swatch comes in under it, not as a numbered copy of it that `d` +/// has, and another swatch of that name gets a number. A numbered copy in `d` whose name is +/// reserved for another swatch, and that is that swatch with its links as `relink` gives them, is +/// left to it, whether or not the import brings that swatch. +fn add_swatch(d: &mut Document, w: &Swatch, source: &Swatch, same_doc: bool, reserved: &BTreeMap, relink: &Relink) -> (Placed, bool) { let same = |n: &str| d.swatch(n).is_some_and(|t| *t == Swatch { name: n.to_string(), ..w.clone() }); - existing(&w.name, d.swatches_iter().map(|t| t.name.as_str()), same_doc, same).unwrap_or_else(|| { - let name = d.free_swatch_name(&w.name); - d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); - Placed::added(&w.name, name) - }) + let kept = (!same_doc && numbered_name(&w.name) && !d.swatch_name_taken(&w.name)).then(|| reserved.get(&w.name)).flatten(); + let (owns, held) = (kept.is_some_and(|o| o == source), kept.is_some_and(|o| o != source)); + let is_owner = |t: &Swatch, o: &Swatch| { + let mut o = o.clone(); + relink.paint(&mut o.paint); + *t == o + }; + let theirs = + |n: &str| n != w.name && copy_of(&w.name, n) && reserved.get(n).is_some_and(|o| o != source && d.swatch(n).is_some_and(|t| is_owner(t, o))); + let names = || d.swatches_iter().map(|t| t.name.as_str()); + let excluded = Cell::new(false); + let found = existing( + &w.name, + names().filter(|n| { + let t = theirs(n); + excluded.set(excluded.get() || t); + !t + }), + same_doc, + same, + ); + let reused = |p: &Option| match p { + Some(Placed::Reused(n)) => Some(n.clone()), + _ => None, + }; + let passed_over = excluded.get() && reused(&found) != reused(&existing(&w.name, names(), same_doc, same)); + let over_copy = match found { + Some(p) if !owns => return (p, passed_over), + found => found.is_some(), + }; + let mut skipped = held; + let name = if d.swatch_name_taken(&w.name) || held { + let mut free = |n: &String| { + let taken = d.swatch_name_taken(n); + skipped |= !taken && reserved.contains_key(n); + !taken && !reserved.contains_key(n) + }; + (2..).map(|i| format!("{} {i}", w.name)).find(&mut free).unwrap_or_else(|| d.free_swatch_name(&w.name)) + } else { + w.name.clone() + }; + d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); + (Placed::added(&w.name, name), over_copy || skipped || passed_over) } diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index bb22ae5c16..f20a413473 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "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: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), 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), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), 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, fills and strokes at an opacity of 0, 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, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; 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. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{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: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), 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), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), 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, fills and strokes at an opacity of 0, 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, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; 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. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -183,8 +183,126 @@ fn count_fonts(fonts: &mut BTreeMap, t: &vectorcr } } -/// An image object as Document Info lists it: (name, width, height, linked file). -type ImageRow = (String, u32, u32, Option); +/// An image object as Linked Images or Embedded Images lists it. +struct ImageRow { + name: String, + width: u32, + height: u32, + /// What a linked image's row names: its file's path, or the file's name alone when the request + /// may not read it. `None` for an embedded image. + file: Option, + /// The image's format ([`image_format`]); `None` when it is not known. + format: Option<&'static str>, + /// The pixels per inch across and down at the size the image is placed at; `None` when its + /// transform flattens it. + ppi: Option<[f64; 2]>, + /// For an embedded image, the bytes its pixels take when drawn (8-bit RGBA: width × height × 4). + memory: Option, + /// For an embedded image, the bytes of the encoded image the document holds. + stored: Option, +} + +impl ImageRow { + /// Image object `n` (image `im`) of `d`, `file` the row value of its link. + fn of(d: &Document, n: &Node, im: &vectorcraft_doc::ImageObject, file: Option) -> Self { + let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string()); + // A distorted image is measured at its middle, as `image.info` measures it. + let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf); + let ppi = super::place::effective_ppi(xf); + // An image with no pixels across or down has no area, and so does one whose transform lays + // both pixel axes on one line. The determinant is compared with the product of the two + // axes' lengths, at any scale. + let [xx, xy, yx, yy, ..] = xf.as_coeffs(); + let has_area = im.width > 0 && im.height > 0 && xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy); + let embedded = im.link.is_none(); + let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4); + Self { + name, + width: im.width, + height: im.height, + file, + format: image_format(d, im), + ppi: (has_area && ppi.iter().all(|v| *v > 0.0 && v.is_finite())).then_some(ppi), + memory: if embedded { memory() } else { None }, + stored: if embedded { d.images.get(&im.key).map(|b| b.bytes.len() as u64) } else { None }, + } + } + + /// The row's value: the format, the size in pixels, and for a linked image its resolution and + /// file, for an embedded one the memory its pixels take. + fn value(&self) -> String { + let format = self.format.unwrap_or("Unknown format"); + let size = format!("{} × {} px", self.width, self.height); + match &self.file { + Some(file) => { + let ppi = match self.ppi { + Some([x, y]) if ppi_number(x) == ppi_number(y) => format!("{} ppi", ppi_number(x)), + Some([x, y]) => format!("{} × {} ppi", ppi_number(x), ppi_number(y)), + None => "resolution unavailable".into(), + }; + format!("{format}; {size}; {ppi} — {file}") + } + None => { + let memory = self.memory.map_or_else(|| "memory unavailable".to_string(), |b| format!("estimated memory {}", byte_size(b))); + format!("{format}; {size}; {memory}") + } + } + } + + /// The row's `imageObjects` entry. + fn entry(&self) -> Value { + json!({ + "name": self.name, + "width": self.width, + "height": self.height, + "linked": self.file.is_some(), + "file": self.file, + "format": self.format, + "effectivePpi": self.ppi, + "memoryBytes": self.memory, + "storedBytes": self.stored, + }) + } +} + +/// The format of image `im` of `d`, as the Links panel names it: for a linked image its file's, by +/// its extension (DCS for a separated one), else the type of the pixels the document holds for it; +/// `None` when neither names a known format. +fn image_format(d: &Document, im: &vectorcraft_doc::ImageObject) -> Option<&'static str> { + use super::fileio; + if im.link.is_some() && d.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) { + return Some("DCS"); + } + im.link + .as_ref() + .and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name()))) + .or_else(|| d.images.get(&im.key).and_then(|b| fileio::FORMATS.iter().find(|f| f.raster && f.mime == b.mime))) + .map(|f| f.label) +} + +/// A resolution as Document Info shows it: rounded to a tenth (below 1, to a hundredth), without a +/// trailing `.0`. +pub fn ppi_number(ppi: f64) -> String { + let k = if ppi.abs() < 1.0 { 100.0 } else { 10.0 }; + format!("{}", (ppi * k).round() / k) +} + +/// A number of bytes as Document Info shows it: in B below 1 KiB, else in KiB, MiB or GiB rounded +/// to a tenth. +pub fn byte_size(bytes: u64) -> String { + const UNITS: [&str; 3] = ["KiB", "MiB", "GiB"]; + if bytes < 1024 { + return format!("{bytes} B"); + } + let mut v = bytes as f64 / 1024.0; + let mut unit = 0; + // 1023.96 KiB is shown as 1 MiB rather than as 1024 KiB. + while v >= 1023.95 && unit + 1 < UNITS.len() { + v /= 1024.0; + unit += 1; + } + format!("{} {}", (v * 10.0).round() / 10.0, UNITS[unit]) +} /// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives /// its name and then its kind with the number of instances it draws (for a grid, its rows and @@ -337,11 +455,9 @@ fn sections( "symbols" => names("symbols"), "fonts" => fonts.to_vec(), "fontDetails" => font_details.to_vec(), - "linkedImages" => { - images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect() - } + "linkedImages" => images.iter().filter(|i| i.file.is_some()).map(|i| (i.name.clone(), i.value())).collect(), "repeats" => repeats.to_vec(), - _ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(), + _ => images.iter().filter(|i| i.file.is_none()).map(|i| (i.name.clone(), i.value())).collect(), }; Section { id, title, rows } }) @@ -753,8 +869,8 @@ fn info(s: &mut Session, p: &Value) -> Result { im.key.clone(), 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, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() }))); + let file = link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() }); + image_rows.push(ImageRow::of(d, n, im, file)); Some("images") } NodeKind::SymbolInstance { symbol, .. } => { @@ -835,13 +951,8 @@ fn info(s: &mut Session, p: &Value) -> Result { let font_names: Vec = fonts.keys().map(super::fonts::font_label).collect(); let (font_uses, font_use_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip(); let (font_entries, font_rows): (Vec, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip(); - // The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a - // linked image's row value (its path, or its file name alone when the request may not read it), - // and null for an embedded one. - let image_objects: Vec = image_rows - .iter() - .map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file })) - .collect(); + // The image objects in walk order, as Linked Images and Embedded Images list them. + let image_objects: Vec = image_rows.iter().map(ImageRow::entry).collect(); // Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two // brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type // as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them. @@ -2246,11 +2357,156 @@ mod tests { assert_eq!(objects.len(), 2, "{objects:?}"); for (o, r) in objects.iter().zip(&embedded) { assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}"); - assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"])); + let memory = byte_size(o["memoryBytes"].as_u64().unwrap()); + assert_eq!(r[1], format!("{}; {} × {} px; estimated memory {memory}", o["format"].as_str().unwrap(), o["width"], o["height"])); } assert!(section("linkedImages").is_empty()); } + /// An image object to place: (key, MIME type, linked path, width, height, transform). + type Placed<'a> = (&'a str, &'a str, Option<&'a str>, u32, u32, Affine); + + /// Image objects `images` placed in a new document, with a blob of `100 + n` bytes of type + /// `mime` for each new key; their ids in order. + fn images_in(s: &mut Session, images: &[Placed]) -> Vec { + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.edit("Place", |d, _| { + let mut ids = vec![]; + for (n, (key, mime, link, width, height, xf)) in images.iter().enumerate() { + if !d.images.contains_key(*key) { + d.images.insert((*key).into(), vectorcraft_doc::ImageBlob::new(*mime, vec![0; 100 + n])); + } + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: (*key).into(), + width: *width, + height: *height, + xf: *xf, + link: link.map(vectorcraft_doc::LinkInfo::new), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), usize::MAX, Node::new(id, NodeKind::Image(Box::new(im))))?; + ids.push(id); + } + Ok(ids) + }) + .unwrap() + } + + /// Linked Images gives each linked image's format, size in pixels, resolution at the size it is + /// placed at and file, and Embedded Images each embedded image's format, size and the memory + /// its pixels take; `imageObjects` gives the same facts with the bytes the document holds for an + /// embedded image, the text report writes the same rows, and Selection Only lists the selected + /// images alone. + #[test] + fn image_rows_give_format_resolution_and_memory() { + let mut s = Session::new(); + let half = Affine::scale(0.5); + let ids = images_in( + &mut s, + &[ + ("a", "image/png", None, 1200, 800, half), + ("b", "image/jpeg", None, 10, 10, half), + ("c", "image/x-unheard-of", None, 3, 2, half), + ("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.48)), + ("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.24)), + ("a", "image/png", Some("/art/wide.png"), 1200, 800, Affine::scale_non_uniform(0.5, 1.0)), + ("a", "image/png", Some("/art/scan.tif"), 1200, 800, half), + ("a", "image/png", Some("/art/flat.png"), 1200, 800, Affine::scale_non_uniform(0.5, 0.0)), + // Both pixel axes on one line: neither has length 0, but the image has no area. + ("a", "image/png", Some("/art/line.png"), 1200, 800, Affine::new([0.5, 0.5, 1.0, 1.0, 0.0, 0.0])), + ("c", "image/x-unheard-of", Some("/art/odd.qqq"), 3, 2, half), + ], + ); + let i = s.execute("document.info", &json!({})).unwrap(); + let rows = |i: &Value, id: &str| -> Vec<(String, String)> { + let section = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap().clone(); + section["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().into(), r[1].as_str().unwrap().into())).collect() + }; + let embedded = rows(&i, "embeddedImages"); + let values: Vec<&str> = embedded.iter().map(|(_, v)| v.as_str()).collect(); + assert_eq!( + values, + [ + "PNG; 1200 × 800 px; estimated memory 3.7 MiB", + "JPEG; 10 × 10 px; estimated memory 400 B", + "Unknown format; 3 × 2 px; estimated memory 24 B" + ] + ); + let linked = rows(&i, "linkedImages"); + assert_eq!( + linked, + [ + ("photo.png", "PNG; 1200 × 800 px; 150 ppi — /art/photo.png"), + ("photo.png", "PNG; 1200 × 800 px; 300 ppi — /art/photo.png"), + ("wide.png", "PNG; 1200 × 800 px; 144 × 72 ppi — /art/wide.png"), + ("scan.tif", "TIFF; 1200 × 800 px; 144 ppi — /art/scan.tif"), + ("flat.png", "PNG; 1200 × 800 px; resolution unavailable — /art/flat.png"), + ("line.png", "PNG; 1200 × 800 px; resolution unavailable — /art/line.png"), + ("odd.qqq", "Unknown format; 3 × 2 px; 144 ppi — /art/odd.qqq"), + ] + .map(|(a, b)| (a.to_string(), b.to_string())) + ); + let objects = i["imageObjects"].as_array().unwrap(); + assert_eq!(objects.len(), 10); + assert_eq!( + (objects[0]["format"].clone(), objects[0]["effectivePpi"].clone(), objects[0]["memoryBytes"].clone(), objects[0]["storedBytes"].clone()), + (json!("PNG"), json!([144.0, 144.0]), json!(1200 * 800 * 4), json!(100)) + ); + assert_eq!((objects[1]["format"].clone(), objects[1]["storedBytes"].clone()), (json!("JPEG"), json!(101))); + assert_eq!(objects[2]["format"], Value::Null); + // A linked image gives no memory and no stored bytes: the document holds only its preview. + assert_eq!((objects[3]["memoryBytes"].clone(), objects[3]["storedBytes"].clone()), (Value::Null, Value::Null)); + let ppi = |o: &Value| -> Vec { o["effectivePpi"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect() }; + assert!(ppi(&objects[3]).iter().all(|v| (v - 150.0).abs() < 1e-9), "{}", objects[3]); + assert_eq!(ppi(&objects[5]), [144.0, 72.0]); + assert_eq!((objects[7]["effectivePpi"].clone(), objects[8]["effectivePpi"].clone()), (Value::Null, Value::Null)); + let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nphoto.png: PNG; 1200 × 800 px; 150 ppi — /art/photo.png\n"), "{text}"); + assert!(text.contains(": JPEG; 10 × 10 px; estimated memory 400 B\n"), "{text}"); + // Selection Only lists the selected images alone, with the same rows. + s.execute("select.set", &json!({"ids": [ids[1].0, ids[5].0]})).unwrap(); + let selected = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + assert_eq!(rows(&selected, "embeddedImages").iter().map(|(_, v)| v.as_str()).collect::>(), [values[1]]); + assert_eq!(rows(&selected, "linkedImages"), [linked[2].clone()]); + } + + /// An image placed at a very small size still has an area, so its row gives a resolution. + #[test] + fn a_tiny_placement_still_gives_a_resolution() { + let mut s = Session::new(); + images_in(&mut s, &[("a", "image/png", Some("/art/huge.png"), 100_000, 100_000, Affine::scale(1e-7))]); + let i = s.execute("document.info", &json!({})).unwrap(); + let ppi = i["imageObjects"][0]["effectivePpi"].as_array().map(|v| v.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect::>()); + let ppi = ppi.unwrap_or_default(); + assert!(ppi.len() == 2 && ppi.iter().all(|v| (v / 7.2e8 - 1.0).abs() < 1e-9), "{}", i["imageObjects"][0]); + } + + /// An image with no pixels across or down has no area, so its row gives no resolution whatever + /// its transform. + #[test] + fn a_zero_pixel_image_has_no_resolution() { + let mut s = Session::new(); + let half = Affine::scale(0.5); + images_in(&mut s, &[("a", "image/png", Some("/art/none.png"), 0, 800, half), ("a", "image/png", Some("/art/flat.png"), 1200, 0, half)]); + let i = s.execute("document.info", &json!({})).unwrap(); + let objects = i["imageObjects"].as_array().cloned().unwrap_or_default(); + assert_eq!(objects.iter().map(|o| o["effectivePpi"].clone()).collect::>(), [Value::Null, Value::Null], "{objects:?}"); + let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap_or_default().to_string(); + assert!(text.contains("none.png: PNG; 0 × 800 px; resolution unavailable — /art/none.png\n"), "{text}"); + assert!(text.contains("flat.png: PNG; 1200 × 0 px; resolution unavailable — /art/flat.png\n"), "{text}"); + } + + /// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a + /// resolution to a tenth without a trailing `.0`. + #[test] + fn byte_sizes_and_resolutions_read_to_a_tenth() { + let shown = [0, 1023, 1024, 1536, 1024 * 1024 - 1, 3_840_000, 5 << 30, u64::MAX].map(byte_size); + assert_eq!(shown, ["0 B", "1023 B", "1 KiB", "1.5 KiB", "1 MiB", "3.7 MiB", "5 GiB", "17179869184 GiB"]); + assert_eq!([150.0, 72.0 / 0.48, 205.714, 0.04, 0.001].map(ppi_number), ["150", "150", "205.7", "0.04", "0"]); + } + /// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind /// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and /// one an object's gradient of that kind shares; a type object's characters count as its own. diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 885fd35988..1054ca3ddc 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,6 +31,7 @@ mod freehand; mod quickpen; mod smooth; +pub(super) use anchors::{following_anchors, remove_anchors_of}; pub use commands::specs; pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; pub(super) use cut::{components, erase_outline}; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 5b80fcc80f..8068418edd 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -166,7 +166,7 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { /// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors. /// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads /// only its own pairs. -fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { +pub(in crate::cmd) fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { let mut next = BTreeSet::new(); let mut kept = 0; let mut rest = removed; @@ -202,7 +202,7 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr /// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed, /// and a path left with no subpath is removed through `emptied`; the caller then takes it out of /// the selection. True when the path went. -fn remove_anchors_of( +pub(in crate::cmd) fn remove_anchors_of( d: &mut Document, sel: &mut Selection, emptied: &mut Beside, diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index c761656b7f..bce1e24d98 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -1,7 +1,7 @@ use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment}; use super::cut::{erase_region, erase_segments, knife, split}; use super::freehand::{blob, freehand}; -use super::quickpen::quick_pen; +use super::quickpen::{quick_pen, quick_pen_length}; use super::smooth::{join_scrub, smooth_region}; use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection}; @@ -43,6 +43,15 @@ pub fn specs() -> Vec { has_doc, quick_pen ), + cmd!( + "path.quickPenLength", + "Quick Pen", + [], + None, + "{id, subpath?: index (0), end?: \"end\" (default)|\"start\", length: pt} make the line or arc at that end of the open subpath `length` long, as dragging the Quick Pen tool's length handle does: a line keeps its other point and its direction; an arc (the segments before the end that lie on one circle and turn the same way) keeps its other point, its circle and the way it turns, with a sweep of at most 359°. length runs from 0.001 to 1000000 pt for a line, and to 359° of the circle for an arc. A length the piece already has changes nothing; otherwise the path is selected, as one undo step → {id, kind: \"line\"|\"arc\", length}. An end that is neither straight nor a circular arc, a closed subpath, a locked or hidden path, a length outside the range and a result that would reach past the canvas are errors", + has_doc, + quick_pen_length + ), cmd!( "path.removeAnchor", "Delete Anchor Point", diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs index 84640bc876..c6549075df 100644 --- a/crates/engine/src/cmd/draw2/quickpen.rs +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -1,9 +1,12 @@ -//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs. +//! The Quick Pen tool's commands: `path.quickPen` draws a path of straight lines and circular arcs, +//! and `path.quickPenLength` makes the line or arc at an end of a path longer or shorter. +use vectorcraft_tools::quickpen::length as qpl; use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke}; use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound}; use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or}; +use crate::cmd::f64_req; const C: &str = "path.quickPen"; /// The most pieces one request takes. @@ -94,3 +97,58 @@ pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "id": id.0 })) } + +const L: &str = "path.quickPenLength"; + +/// `path.quickPenLength`: the line or arc at an end of an open subpath made `length` long. +pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result { + let Some(id) = object_param(p, "id", L)? else { return Err(bad(L, "missing `id`")) }; + let si = usize_opt(p, "subpath", L)?.unwrap_or(0); + let at_start = match p.get("end") { + None | Some(Value::Null) => false, + Some(v) => match v.as_str() { + Some("end") => false, + Some("start") => true, + _ => { + let key = "end"; + return Err(bad(L, format!("`{key}` must be one of {}", ["start", "end"].join(", ")))); + } + }, + }; + let length = f64_req(p, "length", L)?; + let d = &s.doc()?.doc; + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(L, "`id` is not a path"))?; + if !d.is_editable(id) { + return Err(bad(L, "the path is locked or hidden")); + } + let sp = path.subpaths.get(si).ok_or_else(|| bad(L, "no such subpath"))?; + if sp.closed { + return Err(bad(L, "the subpath is closed")); + } + let piece = qpl::end_piece(sp, at_start).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; + let (key, lo, hi) = ("length", qpl::MIN_LENGTH, piece.max_length()); + if !(lo..=hi).contains(&length) { + // An arc's limit, 359° of its circle, is given to the thousandth of a point, rounded down. + let hi = (hi * 1000.0).floor() / 1000.0; + return Err(bad(L, format!("`{key}` must be from {lo} to {hi}"))); + } + let out = qpl::with_length(sp, at_start, length).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; + if !qp::on_canvas(&out) { + return Err(bad(L, "result would exceed the canvas (coordinates out of range)")); + } + let kind = match piece.shape { + qpl::EndShape::Line => "line", + qpl::EndShape::Arc { .. } => "arc", + }; + if (length - piece.length).abs() <= 1e-9 * length.max(1.0) { + return Ok(json!({ "id": id.0, "kind": kind, "length": piece.length })); + } + let top = super::super::path::compound_or_self(d, id); + s.edit("Quick Pen", |d, sel| { + let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?; + *slot = out; + sel.set([top]); + Ok(()) + })?; + Ok(json!({ "id": id.0, "kind": kind, "length": length })) +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e784ab920a..d8cc5c8910 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1222,6 +1222,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; + switch_or(p, "keepJoined", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // An object of a symbol instance's art can't be removed from the instance alone. if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() { @@ -1229,7 +1230,8 @@ fn clear(s: &mut Session, p: &Value) -> Result { } // Direct-selected anchors or segments: remove those, and any objects selected whole with them. if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) { - return super::path::delete_anchors(s, p); + let keep_joined = keeps_paths_joined(s, p)?; + return super::path::delete_anchors_joined(s, p, keep_joined); } // Selected ruler guides (selected on their own). if explicit.is_none() && s.doc()?.selection.is_empty() { @@ -1279,6 +1281,17 @@ fn clear(s: &mut Session, p: &Value) -> Result { ok() } +/// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else +/// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a +/// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined` +/// was recorded before the preference existed, so it opens the paths as it did then. +fn keeps_paths_joined(s: &mut Session, p: &Value) -> Result { + let default = s.prefs.delete_keeps_paths_joined && !s.replaying(); + let on = switch_or(p, "keepJoined", default, "edit.clear")?; + s.note_journal("keepJoined", json!(on)); + Ok(on) +} + /// Document ids scope node ids: two tabs may contain objects with the same node id. fn drop_selection(s: &mut Session, p: &Value) -> Result { const CMD: &str = "edit.dropSelection"; diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 819895414c..8e080e8d80 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "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), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), 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, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; 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; in pdfA2b files, and with longPagesInPoints: false, 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?: 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; false: the UserUnit as above, with a warning that names this option), 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, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). 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, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; 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; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (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, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), 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. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{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), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), 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, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; 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; in pdfA2b files, and with longPagesInPoints: false, 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?: 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; false: the UserUnit as above, with a warning that names this option), 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, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). 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, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; 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; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (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, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), 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 not linked to a spot swatch at a tint above 0% 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. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index d0ed27ca8a..45242affa3 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -333,6 +333,66 @@ fn an_item_opacity_on_a_series_mark_survives_regeneration() { assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), None)); } +/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` on one series mark are kept by the graph as the transparency +/// commands' item opacity is: every path of that series has them after the graph is drawn again. +#[test] +fn a_paint_opacity_on_a_series_mark_survives_regeneration() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.execute("paint.setFill", &json!({"ids": [bar.0], "opacity": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bar.0], "color": "#ff0000", "opacity": 60})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6))); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let marks = series(&n, 0).children().unwrap().to_vec(); + let opacities: Vec<(f32, f32)> = marks.iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect(); + assert!(opacities.iter().all(|o| *o == (0.4, 0.6)), "{opacities:?}"); +} + +/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` with the opacity a mark already shows replace the opacity +/// another mark of the series left on the graph, as an explicit 100% does. +#[test] +fn a_paint_opacity_a_series_mark_already_shows_replaces_the_kept_opacity() { + let (mut s, id, _, marks) = column_marks(); + s.execute("paint.setFill", &json!({"ids": [marks[0].0], "opacity": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [marks[0].0], "opacity": 60})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6))); + // The second mark is opaque already: its row comes out as it was. + s.execute("paint.setFill", &json!({"ids": [marks[1].0], "color": "#ff0000", "opacity": 100})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, Some(0.6))); + s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "opacity": 100})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, None)); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let opacities: Vec<(f32, f32)> = + series(&n, 0).children().unwrap().iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect(); + assert!(opacities.iter().all(|o| *o == (1.0, 1.0)), "{opacities:?}"); +} + +/// The same for a graph's axis lines: a stroke opacity set on an opaque line replaces the one its kind keeps from another +/// line. +#[test] +fn a_stroke_opacity_an_axis_line_already_shows_replaces_the_kept_opacity() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap(); + let kept = |s: &Session| spec(s, id).label_styles.axis_rows.and_then(|r| r.paint.stroke_opacity); + assert_eq!(kept(&s), Some(0.4)); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "opacity": 100})).unwrap(); + assert_eq!(kept(&s), None); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let opacities: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.stroke().map_or(1.0, |st| st.opacity)).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{opacities:?}"); +} + /// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the /// graph keeps none, so the series stays opaque when it is drawn again. #[test] @@ -1424,6 +1484,27 @@ fn paint_targets_leave_a_graph_designs_copy_out() { assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]); } +/// The fill opacity the proxies show leaves out the art of a column or marker design in a series, which +/// `paint.setFill {opacity}` leaves out too: with only that art selected there is none, also with a row of the art +/// active, and with a mark selected after it the mark's. +#[test] +fn proxy_opacity_leaves_a_graph_designs_art_out() { + let (mut s, _, _, art, mark) = design_art(); + let (mut m, _, marker_art) = marker_design_art(); + for (s, art) in [(&mut s, art), (&mut m, marker_art)] { + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + assert_eq!(s.proxy_opacity(false), None); + assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err()); + let fill = top_row(s, art, true); + s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap(); + assert_eq!(s.proxy_opacity(false), None, "with the art's fill row active"); + assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err()); + } + s.execute("paint.setFill", &json!({"ids": [mark.0], "opacity": 40})).unwrap(); + s.execute("select.set", &json!({"ids": [art.0, mark.0]})).unwrap(); + assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the mark's fill opacity"); +} + /// The art of a marker design in series 1 of a line graph: the design's copy and a path inside it. fn marker_design_art() -> (Session, NodeId, NodeId) { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index be203e9991..80c4cbefb9 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1360,7 +1360,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Resul // or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings // a library pattern's colors. let current = s.doc()?.doc.clone(); - let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?; + let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip, &Default::default())?; drop(current); let target = super::patternlib::imported_name(&imported, &name); let paint = vectorcraft_doc::pattern::pattern_paint(&target); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index aa330e11ea..96365e6553 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -187,7 +187,7 @@ pub fn specs() -> Vec { "Rearrange All Artboards…", ["Object", "Artboards"], None, - "{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn)} lay the artboards out in their order, the grid's top-left at the first artboard's; a locked artboard stays where it is → {artboards, rows, columns}", + "{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn), indices?: [n] (lay out only these artboards, in document order; the others and their art and guides stay where they are), at?: [x, y] (the grid's top-left)} lay the artboards out in their order, the grid's top-left at `at`, else at the first artboard's laid out; a locked artboard stays where it is and keeps its place in the grid → {artboards, rows, columns; with indices also indices and moved, the count of artboards that moved}", has_doc, rearrange_artboards ), @@ -1718,32 +1718,48 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(CMD, "order must be leftToRight or rightToLeft")), }; let count = s.doc()?.doc.artboards.len(); - let n_ab = count.max(1); - // Columns of a grid by row, rows of a grid by column. - let lines = whole_or(p, "columns", 2, CMD)?.clamp(1, n_ab as u64) as usize; - let (rows, cols) = match layout { - L::GridByRow => (n_ab.div_ceil(lines), lines), - L::GridByColumn => (lines, n_ab.div_ceil(lines)), - L::Row => (1, n_ab), - L::Column => (n_ab, 1), + // `indices` lays out only those artboards, in document order; left out, every artboard. + let picked: Option> = match p.get("indices") { + Some(v) => Some(super::panelcmds::listed_artboards(&s.doc()?.doc, v, "indices", CMD)?), + None => None, }; + let at = match p.get("at") { + Some(v) => Some(super::finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(CMD, "`at` must be [x, y]"))?), + None => None, + }; + // Columns of a grid by row, rows of a grid by column. + let lines = whole_or(p, "columns", 2, CMD)?; check_numbers(p, &["spacing"], CMD)?; let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5); let move_art = switch_or(p, "moveArtwork", true, CMD)?; check_switches(p, &["patterns"], CMD)?; let locked_and_hidden = super::panelcmds::locked_and_hidden(s, p, move_art, CMD)?; let d = &s.doc()?.doc; - let rects: Vec = d.artboards.iter().map(|a| a.rect).collect(); + let laid: Vec = picked.clone().unwrap_or_else(|| (0..count).collect()); + let rects: Vec = laid.iter().filter_map(|i| d.artboards.get(*i)).map(|a| a.rect).collect(); let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect(); - let first = rects.first().map_or(Point::ZERO, |r| r.origin()); - let origins = super::newdoc::grid_origins_rc(&sizes, first, (rows, cols), spacing, layout == L::GridByColumn, rtl); - // A locked artboard stays where it is, and keeps its place in the grid. - let deltas: Vec = - rects.iter().zip(origins).zip(&d.artboards).map(|((r, o), a)| if a.locked { Vec2::ZERO } else { o - r.origin() }).collect(); + // The grid's top-left: `at`, else the first artboard laid out's. + let origin = at.unwrap_or_else(|| rects.first().map_or(Point::ZERO, |r| r.origin())); + let (origins, rows, cols) = super::newdoc::rearrange_grid(&sizes, origin, layout, lines, spacing, rtl); + // A locked artboard stays where it is, and keeps its place in the grid; an artboard not laid + // out stays where it is. + let mut deltas = vec![Vec2::ZERO; count]; + for ((i, r), o) in laid.iter().zip(&rects).zip(origins) { + if let Some(dl) = deltas.get_mut(*i) + && !d.artboards.get(*i).is_some_and(|a| a.locked) + { + *dl = o - r.origin(); + } + } + let moved = deltas.iter().filter(|dl| dl.x.abs() > 1e-9 || dl.y.abs() > 1e-9).count(); + let result = match &picked { + Some(indices) => json!({ "artboards": count, "indices": indices, "moved": moved, "rows": rows, "columns": cols }), + None => json!({ "artboards": count, "rows": rows, "columns": cols }), + }; // When no artboard moves more than 1e-9 pt on either axis, or there is none, the document and // its undo history stay as they are. - if deltas.iter().all(|dl| dl.x.abs() <= 1e-9 && dl.y.abs() <= 1e-9) { - return Ok(json!({ "artboards": count, "rows": rows, "columns": cols })); + if moved == 0 { + return Ok(result); } // With moveArtwork, each top-level object (a child of a layer or sublayer) moves with the // artboard its center is on, with symbol instances measured by their art as @@ -1791,5 +1807,5 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - Ok(json!({ "artboards": count, "rows": rows, "columns": cols })) + Ok(result) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index ff6fb9a6a1..8272f7d8cb 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -634,6 +634,30 @@ pub(crate) fn grid_origins_rc( .collect() } +/// Rearrange Artboards' grid for artboards of `sizes`, in their order, its top-left at `origin`: +/// `lines` is the column count of a grid by row and the row count of a grid by column (kept to 1 +/// to the artboard count), and `rtl` puts the first column at the right. Returns each artboard's +/// top-left corner and the grid's rows and columns. +pub fn rearrange_grid( + sizes: &[(f64, f64)], + origin: Point, + layout: ArtboardLayout, + lines: u64, + spacing: f64, + rtl: bool, +) -> (Vec, usize, usize) { + let n = sizes.len().max(1); + let lines = usize::try_from(lines).unwrap_or(usize::MAX).clamp(1, n); + let (rows, cols) = match layout { + ArtboardLayout::GridByRow => (n.div_ceil(lines), lines), + ArtboardLayout::GridByColumn => (lines, n.div_ceil(lines)), + ArtboardLayout::Row => (1, n), + ArtboardLayout::Column => (n, 1), + }; + let origins = grid_origins_rc(sizes, origin, (rows, cols), spacing, layout == ArtboardLayout::GridByColumn, rtl); + (origins, rows, cols) +} + /// The built-in presets: (category, presets as (name, width, height, units)), with the category's /// colour mode and raster effects resolution. Sizes in `units` (converted to points on use). type Category = (&'static str, ColorMode, f64, &'static [(&'static str, f64, f64, Unit)]); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 43f219d661..b09bc04d4b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "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|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|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), 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), 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, defaultsOnly?: bool, 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 color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces 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; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is 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). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {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|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), 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), 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, 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 color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces 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; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is 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). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {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) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -161,7 +161,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", always, proxies ), @@ -239,6 +239,80 @@ impl Session { None } + /// The opacity (0..1) of the fill that `paint.setFill {opacity}` sets (or of the stroke that + /// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the + /// first picked point's. The rows the command would edit are read in order (a group without an + /// active Appearance row stands for its contents), and the first that exists answers. `None` + /// with nothing selected, for an object selected in a symbol instance, while the Live Paint + /// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while + /// the Type tool has characters selected, and when only type + /// characters, objects without that item or the art of graph designs in a graph series are + /// selected. + pub fn proxy_opacity(&self, stroke: bool) -> Option { + let st = self.active()?; + // The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the + // selection keeps its own (for_bucket). + if st.selection.symbol_part.is_some() || self.bucket_paints() { + return None; + } + // The command would give the opacity to the characters, which have none of their own. + if super::textedit::selected_range(self).is_some_and(|(_, a, b)| a != b) { + return None; + } + let item = self.appearance_item(); + let of = |n: &Node, item: Option| -> Option { + if item.is_none() && matches!(n.kind, NodeKind::Text(_)) { + return None; + } + if !stroke + && item.is_none() + && let NodeKind::Mesh(m) = &n.kind + && let Some((_, points)) = picked_mesh_points(self, &[n.id]).first() + { + return points.first().and_then(|i| m.points.get(*i)).map(|q| q.opacity); + } + if stroke { n.appearance.stroke_at(item).map(|s| s.opacity) } else { n.appearance.fill_at(item).map(|f| f.opacity) } + }; + let subjects = st.selection.subjects(); + // The command leaves out the art of a graph design in a series, which the graph draws again + // from the design, and a series group stands for the paths directly in it + // (graph::paint_targets). + let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id); + // As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of + // this kind in the first selected object's stack, read in the stacks the command edits; + // else the topmost one of the painted leaves of the selected objects (a group's + // contents; for a targeted layer, its editable art, ItemTarget::targets). A row of a + // graph design's art selected first stands for nothing (item_target_at). + let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id)); + let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke)); + if let Some(index) = active { + // The objects whose own stacks the command edits (appearance_targets: a selected + // compound-path member stands for its compound, and an object inside another selected + // one is left out), with the one whose stack the row belongs to first. + // Each target reads the row the command edits there (ItemTarget::per_target and + // ItemTarget::resolve): the row equal to the active one, else its topmost of the kind. + let row = ItemTarget::Item { index, explicit: false, aligned: true }; + let mut roots = super::appearance::appearance_targets(self, &Value::Null).ok()?; + let anchor = row.anchor(self, &roots); + if let Some(head) = roots.get_mut(..=anchor) { + head.rotate_right(1); + } + let targets: Vec = super::graph::series_group_marks_where(&st.doc, &roots, |n| n.extras().series_index.is_some()) + .into_iter() + .filter(|id| editable(&id)) + .collect(); + return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| { + let n = st.doc.node(*id)?; + of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?) + }); + } + // A Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit + // (ItemTarget::targets_for). + let leaves = super::leaf_targets(self, &st.selection.objects).ok()?; + let skipped = live_paint_parts_skipped(&st.doc, &st.selection.objects, !stroke); + leaves.iter().filter(editable).filter(|id| !skipped.contains(*id)).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) + } + pub(crate) fn remember_paint_now(&mut self, p: &Paint) { match p { Paint::Solid { color, .. } => { @@ -483,7 +557,12 @@ impl Session { fn proxies(s: &mut Session, _: &Value) -> Result { let (fill, stroke) = s.proxy_paints(); let (fill_mixed, stroke_mixed) = s.proxy_mixed(); - Ok(json!({"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed})) + // As transparency.info answers an opacity: a percentage to two places. + let percent = |o: Option| o.map(|o| (f64::from(o) * 10_000.0).round() / 100.0); + Ok(json!({ + "fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed, + "fillOpacity": percent(s.proxy_opacity(false)), "strokeOpacity": percent(s.proxy_opacity(true)), + })) } /// `stroke` param, defaulting to the proxy that is in front. @@ -602,13 +681,36 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { return Err(bad(cmd, "`tint` goes with a global or spot `swatch`")); } check_keep_model(p, cmd)?; - let paint = paint_from(s, p)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?; + let opacity = opacity_param(p, cmd)?; + let paint = paint_from(s, p)?; + // A `swatch` that is no name gives no paint, and does not turn the request into an opacity alone. + let swatch_not_a_name = p.get("swatch").is_some_and(|v| !v.is_null() && !v.is_string()); + if paint.is_none() && (opacity.is_none() || swatch_not_a_name) { + return Err(bad(cmd, "give color, none, swatch, gradient or opacity")); + } // As `paint.editGradient`: a `dither` given applies to gradient fills only. A gradient swatch // (named) keeps its own dither; `"swatch": null` names none. - if !fill && matches!(&paint, Paint::Gradient(g) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() { + if !fill && matches!(&paint, Some(Paint::Gradient(g)) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() { return Err(bad(cmd, "`dither` applies to gradient fills (paint.setFill)")); } - apply_paint(s, p, paint, fill) + apply_paint_opacity(s, p, paint, opacity, fill) +} + +/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None` +/// when it is left out or null. +fn opacity_param(p: &Value, cmd: &str) -> Result> { + match p.get("opacity") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(o) if (0.0..=100.0).contains(&o) => Ok(Some((o / 100.0) as f32)), + _ => Err(bad(cmd, "`opacity` must be a number from 0 to 100")), + }, + } +} + +/// The error for an `opacity` that would go to type characters, which have no opacity of their own. +fn characters_have_no_opacity(cmd: &str) -> EngineError { + bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke") } /// [`apply_paint`] on the proxy named by `stroke` (default: the active one), focusing it. @@ -621,17 +723,31 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result /// `paint.setFill`) and of the defaults for new art, focus its proxy unless `focus` is false, and /// remember the paint. Replies `{objects}`: how many objects took the paint. pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result { + apply_paint_opacity(s, p, Some(paint), None, fill) +} + +/// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or +/// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' +/// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. +/// The opacity alone changes neither the defaults for new art nor the remembered colors; with New +/// Art Has Basic Appearance off, new art copies the first selected object's appearance after any +/// command, its opacity included. An opacity that would go only to type +/// characters, to an object selected in a symbol instance, or to no target at all is an error. +fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity: Option, fill: bool) -> Result { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let bucket = bucket_color_params(s, p, cmd)?; let p = bucket.as_ref().unwrap_or(p); let focus = switch_or(p, "focus", true, cmd)?; - let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?; - // Characters selected with the Type tool take the paint, not the whole type object (#1063). - if p.get("ids").is_none() + // An opacity alone places no gradient, so `span` may only be "object" with it. + let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; + // Characters selected with the Type tool take the paint, not the whole type object (#1063). A + // null `ids` or `id` names no object, as `given_nodes` reads it. + if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b { + let (Some(paint), None) = (paint, opacity) else { return Err(characters_have_no_opacity(cmd)) }; // After Select All in threaded text, every frame's text takes it. let story = super::textedit::editing_story(s); let ranges: Vec<(NodeId, usize, usize)> = @@ -684,6 +800,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) // An object of a dynamic symbol instance's art selected with Direct Selection: that object's // fill or stroke changes for this instance only (solid, none, gradient or pattern). if let Some((id, path)) = selected_part_target(s, p, cmd)? { + let Some(paint) = paint.filter(|_| opacity.is_none()) else { + return Err(bad(cmd, "an object selected in a symbol instance has no fill or stroke opacity of its own")); + }; super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| { if fill { o.fill = Some(paint.clone()); @@ -702,36 +821,146 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let item = item_target(s, p, cmd)?.of_kind(s, fill); let selected = item.targets_for(s, p, fill)?; let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); + // An opacity has nothing to go to without targets; with a paint, the defaults then stay too. + if opacity.is_some() && ids.is_empty() { + return Err(bad(cmd, "select objects or give ids")); + } let of = super::appearance::reference_of(s, p, item, cmd)?; - let paint = if span { - // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each - // object's box is that of the row it edits. - let d = &s.doc()?.doc; - let mut spanned = Vec::with_capacity(ids.len()); - for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) { - let (Some(it), Some(n)) = (it, d.node(*id)) else { continue }; - spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?)); + let paint = match paint { + Some(paint) if span => { + // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each + // object's box is that of the row it edits. + let d = &s.doc()?.doc; + let mut spanned = Vec::with_capacity(ids.len()); + for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) { + let (Some(it), Some(n)) = (it, d.node(*id)) else { continue }; + spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?)); + } + Some(placed_across(d, &spanned, paint, p, fill)) } - placed_across(d, &spanned, paint, p, fill) - } else { - paint + paint => paint, }; // The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid - // fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`). - let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] }; + // fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`), + // and a fill opacity fades just them. + let mesh_points = if fill && matches!(paint, Some(Paint::Solid { .. }) | None) { picked_mesh_points(s, &ids) } else { vec![] }; // Without `item`, unless the Appearance panel's active fill item takes the paint. - let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top { - colorized_images(&s.doc()?.doc, &ids, &paint).map_err(|e| bad(cmd, e))? - } else { - vec![] + let colorized = match &paint { + Some(paint) if fill && p.get("item").is_none() && item == ItemTarget::Top => { + colorized_images(&s.doc()?.doc, &ids, paint).map_err(|e| bad(cmd, e))? + } + _ => vec![], + }; + let label = match paint { + None => "Opacity", + Some(_) if fill => "Fill Color", + Some(_) => "Stroke Color", }; - let label = if fill { "Fill Color" } else { "Stroke Color" }; // Each object whose appearance took the paint, with the row it went to, for the paint a graph stores for its series // (a series mark is a path, so it always has a row here). let written = std::cell::RefCell::new(Vec::new()); // The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep // for their characters; a row edit is kept with the label's rows. let characters = std::cell::RefCell::new(Vec::new()); + // The targets that took the opacity, and whether one would have given it to its characters. + let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false)); + // The row each target took the opacity on, for what a graph keeps. + let opacity_written = std::cell::RefCell::new(Vec::new()); + let paint_one = |n: &mut Node, index: Option, paint: &Paint| -> Result<()> { + if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { + characters.borrow_mut().push(n.id); + } + if index.is_none() && colorized.contains(&n.id) { + let colorize = paint.color().map(|_| Box::new(paint.clone())); + // Without a color the image has nothing to overprint, and a later color starts + // knocking out. + if colorize.is_none() { + n.extras_mut().colorize_overprint = false; + } + n.extras_mut().colorize = colorize; + return Ok(()); + } + if index.is_none() + && let Paint::Solid { color, .. } = paint + && let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id) + && let NodeKind::Mesh(m) = &mut n.kind + { + for i in points { + if let Some(q) = m.points.get_mut(*i) { + q.color = *color; + } + } + return Ok(()); + } + if index.is_none() + && let NodeKind::Text(t) = &mut n.kind + { + let (xf, lb) = (t.xf, t.local_bounds()); + for r in &mut t.runs { + if !fill && !paint.is_none() { + run_stroke_weight(&mut r.style); + } + let (cur, b) = run_paint_mut(r, !fill, lb); + *cur = place_run_paint(paint, p, xf, b); + } + return Ok(()); + } + // A missing top fill or stroke is created first: a new stroke's weight sizes the box its + // gradient fits. + if n.appearance.paint_at(index, fill).is_none() { + n.appearance.set_paint_at(index, fill, Paint::None); + } + if !fill { + restore_unpainted_stroke(&mut n.appearance, index, paint); + } + let new_paint = keep_pattern_xf(paint, p, n.appearance.paint_at(index, fill)); + let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill)); + n.appearance.set_paint_at(index, fill, placed); + if !fill + && paint.is_none() + && let Some(stroke) = n.appearance.stroke_at_mut(index) + { + // A stroke without paint has no weight; painting it again restores the 1 pt default. + stroke.width = 0.0; + } + if !fill { + super::object::snap_if_aligned(n); + } + let at = match index { + Some(_) => n.appearance.item_of_kind(index, fill), + None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill), + }; + written.borrow_mut().extend(at.map(|at| (n.id, at))); + Ok(()) + }; + // The opacity goes to what the paint went to: the picked mesh points, else the fill or stroke + // item. Characters, and targets without that item, are left as they are. + let opacity_one = |n: &mut Node, index: Option, o: f32| { + if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { + characters_skipped.set(true); + return; + } + if index.is_none() + && let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id) + && let NodeKind::Mesh(m) = &mut n.kind + { + for i in points { + if let Some(q) = m.points.get_mut(*i) { + q.opacity = o; + took_opacity.borrow_mut().insert(n.id); + } + } + return; + } + let item = + if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) }; + if let Some(item) = item { + *item = o; + took_opacity.borrow_mut().insert(n.id); + let at = index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)); + opacity_written.borrow_mut().extend(at.map(|at| (n.id, at))); + } + }; // The objects counted: with a design's art, those with a row equal to the art's. let ids = edit_items_then( s, @@ -742,96 +971,60 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) label, fill, |n, index| { - if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { - characters.borrow_mut().push(n.id); + if let Some(paint) = &paint { + paint_one(n, index, paint)?; } - if index.is_none() && colorized.contains(&n.id) { - let colorize = paint.color().map(|_| Box::new(paint.clone())); - // Without a color the image has nothing to overprint, and a later color starts - // knocking out. - if colorize.is_none() { - n.extras_mut().colorize_overprint = false; - } - n.extras_mut().colorize = colorize; - return Ok(()); + if let Some(o) = opacity { + opacity_one(n, index, o); } - if index.is_none() - && let Paint::Solid { color, .. } = &paint - && let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id) - && let NodeKind::Mesh(m) = &mut n.kind - { - for i in points { - if let Some(q) = m.points.get_mut(*i) { - q.color = *color; - } - } - return Ok(()); - } - if index.is_none() - && let NodeKind::Text(t) = &mut n.kind - { - let (xf, lb) = (t.xf, t.local_bounds()); - for r in &mut t.runs { - if !fill && !paint.is_none() { - run_stroke_weight(&mut r.style); - } - let (cur, b) = run_paint_mut(r, !fill, lb); - *cur = place_run_paint(&paint, p, xf, b); - } - return Ok(()); - } - // A missing top fill or stroke is created first: a new stroke's weight sizes the box its - // gradient fits. - if n.appearance.paint_at(index, fill).is_none() { - n.appearance.set_paint_at(index, fill, Paint::None); - } - if !fill { - restore_unpainted_stroke(&mut n.appearance, index, &paint); - } - let new_paint = keep_pattern_xf(&paint, p, n.appearance.paint_at(index, fill)); - let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill)); - n.appearance.set_paint_at(index, fill, placed); - if !fill - && paint.is_none() - && let Some(stroke) = n.appearance.stroke_at_mut(index) - { - // A stroke without paint has no weight; painting it again restores the 1 pt default. - stroke.width = 0.0; - } - if !fill { - super::object::snap_if_aligned(n); - } - let at = match index { - Some(_) => n.appearance.item_of_kind(index, fill), - None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill), - }; - written.borrow_mut().extend(at.map(|at| (n.id, at))); Ok(()) }, |before, d, changed| { + // An opacity that no target took is an error, which also takes back the paint given with it. + if opacity.is_some() && took_opacity.borrow().is_empty() { + if characters_skipped.get() { + return Err(characters_have_no_opacity(cmd)); + } + return Err(bad(cmd, "no target has that fill or stroke to take the opacity")); + } + // A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series, and of a + // graph line's, also when the object already showed it. + let kept = opacity.is_some() && { + let rows = opacity_written.borrow(); + let on = super::graph::RowWrites { opacity: true, ..super::graph::RowWrites::NONE }; + let (on_fill, on_stroke) = if fill { (on, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, on) }; + let marks = super::appearance::capture_series_changes(before, d, changed); + let written = super::appearance::capture_series_opacity_writes(d, &rows); + marks | written | super::graph::capture_line_row_writes(d, &rows, on_fill, on_stroke) + }; + let Some(paint) = &paint else { return Ok(kept) }; let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow()); // A graph line keeps the paint written to it, also when it already showed it. let lines = super::graph::capture_line_paint_writes(d, &written.borrow()); let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| { if fill { - st.fill = unplaced(&paint); + st.fill = unplaced(paint); } else { if !paint.is_none() { run_stroke_weight(st); } - st.stroke = unplaced(&paint); + st.stroke = unplaced(paint); } }); - Ok(series || lines || labels) + Ok(series || lines || labels || kept) }, )?; - // Rejected edits leave the next shape's appearance and active proxy untouched. - paint_new_art(s, &paint, fill); if focus { s.fill_active = fill; } - s.remember_paint(&paint); - Ok(json!({"objects": ids.iter().collect::>().len()})) + // Rejected edits leave the next shape's appearance and active proxy untouched. + if let Some(paint) = &paint { + paint_new_art(s, paint, fill); + s.remember_paint(paint); + } + // An opacity alone counts only the targets that took it. + let objects = if paint.is_none() { took_opacity.borrow().len() } else { ids.iter().collect::>().len() }; + Ok(json!({"objects": objects})) } /// Does `p` name no `ids`, `id` or `item`? diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 9c41b7c78d..5ebc84a981 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Delete Anchor Points", [], None, - "{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)", + "{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)", has_anchors, delete_anchors ), @@ -1652,6 +1652,17 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { /// Layers are retained, and an object removed with a selected ancestor is not removed twice. /// Returns JSON `null` on success; selection is replaced by the surviving object IDs. pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { + delete_anchors_joined(s, p, false) +} + +/// [`delete_anchors`], and with `keep_joined` (General › Delete Removes Anchor Points and Keeps +/// Paths Joined) a path with direct-selected anchors and no selected segment loses those anchors +/// as Remove Anchor Points takes them, without opening it, and stays selected with the next +/// anchor along (the one before at an open subpath's end), so the next Delete goes on along the +/// path. When no subpath it changed keeps two anchors, the path stays selected whole, as Remove +/// Anchor Points leaves it. Paths with a selected segment are cut there, as without `keep_joined` +/// (their selected anchors stay in the path), and objects selected whole are deleted, in the same undo step. +pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result { // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?; let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?; @@ -1686,6 +1697,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { d.remove_many(&whole_ids)?; } let mut survivors = vec![]; + let mut following = vec![]; let remaining: Vec = sel.keys().copied().filter(|id| d.node(*id).is_some()).collect(); let mut emptied = Beside::replacing(d, &remaining); for (id, set) in &sel { @@ -1693,6 +1705,23 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { if d.node(*id).is_none() { continue; } + if keep_joined + && !set.is_empty() + && !segments.contains_key(id) + && let Some(path) = d.node(*id).and_then(|n| match &n.kind { + NodeKind::Path { path, .. } => Some(path), + _ => None, + }) + { + let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(); + let anchors: Vec<(usize, usize)> = set.iter().copied().collect(); + let next = super::draw2::following_anchors(&shape, &anchors); + if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? { + survivors.push(*id); + following.push((*id, next)); + } + continue; + } let original = deletion_source(d, *id)?; let subpaths: Vec = { let path = path_mut(d, *id)?; @@ -1736,6 +1765,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { } } selection.set(survivors); + for (id, next) in following { + if !next.is_empty() { + selection.anchors.insert(id, next); + } + } Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 64342b21dd..53fc83b7c9 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -3,6 +3,7 @@ //! document holding its patterns, drawn here from plain shapes ([`PATTERN_LIBRARIES`]). //! `swatch.library.add` copies a pattern into the document with its swatch. +use std::collections::BTreeMap; use std::sync::{Arc, LazyLock}; use vectorcraft_color::{Color, Paint, Swatch, SwatchLibrary}; @@ -15,6 +16,10 @@ use super::clipboard::Clipboard; use super::clipboard::resources::{Imported, SwatchChoices}; use super::swatchlib::LibraryInfo; +/// Names that swatches and patterns coming in under a numbered name skip, each with the library +/// swatch it is reserved for ([`SwatchChoices::reserving`]). +pub(crate) type Reserved = Arc>; + /// A built-in pattern library: a stable id, its menu name and the function that adds its patterns. pub struct BuiltinPatternLibrary { pub id: &'static str, @@ -96,17 +101,18 @@ pub(crate) type SwatchNames = Vec<(String, String)>; /// A global or spot color whose name `d` gives another color comes in under a free name, as Add /// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors /// merge instead when that reuses a pattern of `d` that keeping them would add again -/// ([`probe_import`]). -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> { +/// ([`probe_import`]). A swatch that comes in under a numbered name skips the names in +/// `reserved`. +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str, reserved: &Reserved) -> Result<(String, SwatchNames, SwatchNames)> { let gathered = gather(lib, name); let had: std::collections::HashSet = d.swatches_iter().map(|w| w.name.clone()).collect(); // Without a color to merge or a pattern to reuse, the document is not copied. let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) { - let (_, probed, imported) = probe_import(d, lib, name, &gathered)?; + let (_, probed, imported) = probe_import(d, lib, name, &gathered, reserved)?; *d = probed; imported } else { - gathered.import_into(d, &SwatchChoices::add_all(), false)? + gathered.import_into(d, &SwatchChoices::add_all().reserving(reserved), false)? }; let from = |to: &str| { let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str()); @@ -138,9 +144,11 @@ pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::Has gather(lib, name).swatches.into_iter().map(|w| w.name).collect() } -/// The names in `lib` of pattern `name` and of the patterns its art brings. -pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet { - gather(lib, name).patterns.into_iter().map(|p| p.name).collect() +/// The names in `lib` of the swatches and patterns that pattern `name` of `lib` brings, itself +/// included. +pub(crate) fn brought_resource_names(lib: &Document, name: &str) -> std::collections::HashSet { + let gathered = gather(lib, name); + gathered.swatches.into_iter().map(|w| w.name).chain(gathered.patterns.into_iter().map(|p| p.name)).collect() } /// The name pattern `name` has in the document `imported` went into. @@ -154,8 +162,8 @@ pub(crate) fn imported_name(imported: &Imported, name: &str) -> String { /// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is /// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it /// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those -/// resources are compared too. -pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> { +/// resources are compared too, with numbered names skipping `reserved`. +pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str, reserved: &Reserved) -> Option<(String, SwatchNames)> { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 && gathered.symbols.is_empty() @@ -173,7 +181,7 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio if !has_candidate(d, lib, name) { return None; } - let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?; + let (_, _, imported) = probe_import(d, lib, name, &gathered, reserved).ok()?; if imported.added != 0 { return None; } @@ -203,19 +211,73 @@ pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool { /// another color comes in under a free name (Add). Those colors merge instead when Add would add /// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to /// the document's own colors of those names, as pasting with Merge, or adding it from a library -/// before, leaves it. -pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> { +/// before, leaves it. A swatch or pattern that comes in under a numbered name skips the names in +/// `reserved` ([`SwatchChoices::reserving`]). When that changed a name and the pattern would come +/// in again, or would be reused only by merging colors, an import that does not skip them is used +/// if it reuses a pattern of `d` (one pasted there), without merging in the second case, and uses +/// none of those names that `d` does not use, other than for the swatch a name is reserved for. +pub(crate) fn probe_import( + d: &Document, + lib: &Document, + name: &str, + gathered: &Clipboard, + reserved: &Reserved, +) -> Result<(SwatchChoices, Document, Imported)> { let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); - let mut with_add = d.clone(); - let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?; - if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { - let mut merged = d.clone(); - let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?; - if reused(&found) { - return Ok((SwatchChoices::default(), merged, found)); + let found = probe_skipping(d, lib, name, gathered, reserved)?; + // A reuse that merges colors gives the pattern the document's colors, so one that keeps the + // library's is tried too. + let merged = |i: &Imported| reused(i) && i.merged != 0; + if found.2.reserved_named && (!reused(&found.2) || merged(&found.2)) && has_candidate(d, lib, name) { + let pasted = probe_skipping(d, lib, name, gathered, &Reserved::default())?; + let better = !reused(&found.2) || !merged(&pasted.2); + if reused(&pasted.2) && better && !takes_reserved(d, &pasted.1, &pasted.2, gathered, reserved) { + return Ok(pasted); } } - Ok((SwatchChoices::add_all(), with_add, added)) + Ok(found) +} + +/// Whether `probed`, the import of `gathered` into a copy of `d` that `imported` describes, gives a +/// name in `reserved` that `d` does not use to a pattern, or to a swatch other than the one the name +/// is reserved for coming in under its own name. +fn takes_reserved(d: &Document, probed: &Document, imported: &Imported, gathered: &Clipboard, reserved: &Reserved) -> bool { + let had: std::collections::HashSet<&str> = + d.swatches_iter().map(|w| w.name.as_str()).chain(d.swatch_groups.iter().map(|g| g.name.as_str())).collect(); + let renamed_to = |n: &str| imported.renamed.iter().any(|r| r["kind"] == "swatch" && r["to"] == n && r["from"] != n); + let owner_only = |n: &str, owner: &Swatch| gathered.swatches.iter().filter(|w| w.name == n).all(|w| w == owner); + let swatch = probed + .swatches_iter() + .map(|w| w.name.as_str()) + .filter(|n| !had.contains(n)) + .any(|n| reserved.get(n).is_some_and(|owner| !owner_only(n, owner) || renamed_to(n))); + let patterns: std::collections::HashSet<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect(); + swatch || probed.patterns.iter().any(|p| !patterns.contains(p.name.as_str()) && reserved.contains_key(&p.name)) +} + +/// [`probe_import`] with numbered names skipping `reserved`. +fn probe_skipping( + d: &Document, + lib: &Document, + name: &str, + gathered: &Clipboard, + reserved: &Reserved, +) -> Result<(SwatchChoices, Document, Imported)> { + let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); + let (add, merge) = (SwatchChoices::add_all().reserving(reserved), SwatchChoices::default().reserving(reserved)); + let mut with_add = d.clone(); + let mut added = gathered.import_into(&mut with_add, &add, false)?; + if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { + let mut merged = d.clone(); + let mut found = gathered.import_into(&mut merged, &merge, false)?; + // Whether a reservation changed a name counts for either import. + found.reserved_named |= added.reserved_named; + if reused(&found) { + return Ok((merge, merged, found)); + } + added.reserved_named |= found.reserved_named; + } + Ok((add, with_add, added)) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 44caf0515d..ab77ba5a02 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -44,6 +44,7 @@ //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). +use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; @@ -113,8 +114,19 @@ pub fn describe(p: &Plugin) -> Value { .iter() .map(|c| { let run = m.for_command(c); - json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(), - "paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())}) + let mut entry = json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(), + "paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())}); + if let Some(place) = &c.place { + let mut menu = json!({"path": place.path}); + if let Some(after) = &place.after { + menu["after"] = json!(permissions::display_text(after, permissions::MAX_SHOWN_NAME)); + } + if placed_menu(p, c).is_none() { + menu["placed"] = json!(false); + } + entry["menu"] = menu; + } + entry }) .collect(); v["commands"] = json!(commands); @@ -497,15 +509,278 @@ pub fn find_spec(id: &str) -> Option<&'static CommandSpec> { command_specs().into_iter().find(|c| c.id == id) } +/// The letters and digits of `label`, lowercased. Two labels with the same key read alike in a menu +/// (`Paste (in Place)` and `Paste in Place`). +fn label_key(label: &str) -> String { + label.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The labels of engine commands whose menu item switches to the label of [`other_state`] (the +/// desktop app's dynamic labels). +pub const SWITCHING_LABELS: &[&str] = &[ + "Preview", + "Outline", + "Show Rulers", + "Change to Global Rulers", + "Show Transparency Grid", + "Lock Guides", + "Hide Slices", + "Show Print Tiling", + "Lock Grid", + "Edit Envelope", + "Edit Contents", + "Start Global Edit", +]; + +/// The label of `label`'s other state, for a menu item that switches between two labels: `Show +/// Edges` for `Hide Edges`, `Unlock Guides` for `Lock Guides`, `Stop Global Edit` for `Start Global +/// Edit`, and the reverse. +pub fn other_state(label: &str) -> Option { + const PAIRS: &[(&str, &str)] = &[ + ("Preview", "Outline"), + ("Change to Global Rulers", "Change to Artboard Rulers"), + ("Edit Envelope", "Edit Contents"), + ("Start Global Edit", "Stop Global Edit"), + ]; + let paired = |&(a, b): &(&'static str, &'static str)| { + if label == a { + Some(b) + } else if label == b { + Some(a) + } else { + None + } + }; + if let Some(other) = PAIRS.iter().find_map(paired) { + return Some(other.to_string()); + } + [("Hide ", "Show "), ("Show ", "Hide "), ("Lock ", "Unlock "), ("Unlock ", "Lock ")] + .iter() + .find_map(|(from, to)| label.strip_prefix(from).map(|rest| format!("{to}{rest}"))) +} + +/// The menu that plug-in `p`'s command `c` is listed in when its manifest's `menu` places it in +/// another menu: that menu's path, or `None` when `c` stays in its plug-in's submenu. It stays +/// there when its menu label ([`Command::menu_label`]) has the same letters and digits, ignoring +/// case, as an engine command listed in that menu (either label of one of [`SWITCHING_LABELS`]), +/// an item of [`DESKTOP_MENU_ITEMS`] there, or a command that a plug-in with a lower id, or an +/// earlier command of `p`, places in that menu. The result is the same with and without the +/// desktop app. Results for installed plug-ins are kept until the registry changes. +pub fn placed_menu(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> { + type Placed = HashMap>; + static PLACED: Mutex> = Mutex::new(None); + c.place.as_ref()?; + let m = p.manifest(); + // Read before the registry, so a result found while the registry changes is kept under the + // revision before the change. + let revision = registry::revision(); + // `plugin.inspect` describes a module that is not installed, or not yet in place of the + // installed one: never kept. + if !registry::get(&m.id).is_some_and(|q| std::ptr::eq(&*q, p)) { + return find_place(p, c); + } + let id = command_id(&m.id, &c.id); + if let Ok(placed) = PLACED.lock() + && let Some((at, known)) = placed.as_ref() + && *at == revision + && let Some(found) = known.get(&id) + { + return *found; + } + let found = find_place(p, c); + if let Ok(mut placed) = PLACED.lock() { + let (at, known) = placed.get_or_insert_with(|| (revision, HashMap::new())); + if *at != revision { + *at = revision; + known.clear(); + } + known.insert(id, found); + } + found +} + +/// [`placed_menu`], found again. +fn find_place(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> { + let place = c.place.as_ref()?; + let m = p.manifest(); + let key = label_key(&c.menu_label(&m.name)); + let reads_like = + |label: &str| label_key(label) == key || SWITCHING_LABELS.contains(&label) && other_state(label).is_some_and(|o| label_key(&o) == key); + if super::command_specs().iter().any(|s| s.menu == place.path && reads_like(s.label)) + || DESKTOP_MENU_ITEMS.iter().any(|(path, label)| *path == place.path && label_key(label) == key) + { + return None; + } + let taken = |name: &str, d: &Command| d.place.as_ref().is_some_and(|e| e.path == place.path) && label_key(&d.menu_label(name)) == key; + // The registry lists plug-ins in id order. `p` itself may not be installed yet (`plugin.inspect`), + // or be replacing the installed module of its id, so its own commands come from `m`. + for q in registry::list() { + let qm = q.manifest(); + if qm.id >= m.id { + break; + } + if qm.commands.iter().any(|d| taken(&qm.name, d)) { + return None; + } + } + for d in &m.commands { + if d.id == c.id { + return Some(place.path); + } + if taken(&m.name, d) { + return None; + } + } + Some(place.path) +} + +/// The labels of the desktop app's own items (not engine commands) in the menus of +/// [`vectorcraft_plugins::manifest::MENU_PLACES`], with both labels of an item that switches +/// between two. [`placed_menu`] reads them, so its result is the same with and without the desktop +/// app. +pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ + (&["Edit"], "Spelling"), + (&["Edit"], "Edit Custom Dictionary…"), + (&["Edit"], "Edit Colors"), + (&["Edit"], "Edit Original"), + (&["Edit"], "Transparency Flattener Presets…"), + (&["Edit"], "Print Presets…"), + (&["Edit"], "PDF Presets…"), + (&["Edit"], "Tracing Presets…"), + (&["Edit"], "Perspective Grid Presets…"), + (&["Edit"], "Refresh Monitor Profile"), + (&["Edit"], "Keyboard Shortcuts…"), + (&["Edit"], "Preferences…"), + (&["Edit", "Edit Colors"], "Recolor with Preset"), + (&["Object"], "Transform"), + (&["Object"], "Arrange"), + (&["Object"], "Align"), + (&["Object"], "Distribute"), + (&["Object"], "Lock"), + (&["Object"], "Hide"), + (&["Object"], "Slice"), + (&["Object"], "Path"), + (&["Object"], "Shape"), + (&["Object"], "Pattern"), + (&["Object"], "Repeat"), + (&["Object"], "Intertwine"), + (&["Object"], "Objects on Path"), + (&["Object"], "Blend"), + (&["Object"], "Envelope Distort"), + (&["Object"], "Perspective"), + (&["Object"], "Live Paint"), + (&["Object"], "Image Trace"), + (&["Object"], "Text Wrap"), + (&["Object"], "Clipping Mask"), + (&["Object"], "Compound Path"), + (&["Object"], "Artboards"), + (&["Object"], "Graph"), + (&["Object"], "Collect for Export"), + (&["Object"], "Plug-ins"), + (&["Type"], "Font"), + (&["Type"], "Recent Fonts"), + (&["Type"], "Size"), + (&["Type"], "Bold"), + (&["Type"], "Italic"), + (&["Type"], "Glyphs"), + (&["Type"], "Insert Special Character"), + (&["Type"], "Insert Whitespace Character"), + (&["Type"], "Insert Break Character"), + (&["Type"], "Type on a Path"), + (&["Type"], "Dynamic Text Presets"), + (&["Type"], "Threaded Text"), + (&["Type"], "Find Font…"), + (&["Type"], "Change Case"), + (&["Type"], "Bullets and Numbering"), + (&["Type"], "Show Hidden Characters"), + (&["Type"], "Hide Hidden Characters"), + (&["Type"], "Type Orientation"), + (&["Select"], "Same"), + (&["Select"], "Object"), + (&["Select"], "Saved Selection"), + (&["Effect"], "Apply Last Effect"), + (&["Effect"], "Last Effect…"), + (&["Effect"], "3D and Materials"), + (&["Effect"], "Color Adjustments"), + (&["Effect"], "Color Effects"), + (&["Effect"], "Convert to Shape"), + (&["Effect"], "Crop Marks"), + (&["Effect"], "Distort & Transform"), + (&["Effect"], "Path"), + (&["Effect"], "Path Effects"), + (&["Effect"], "Pathfinder"), + (&["Effect"], "Rasterize…"), + (&["Effect"], "Stylize"), + (&["Effect"], "SVG Filters"), + (&["Effect"], "Warp"), + (&["Effect"], "Effect Gallery…"), + (&["Effect"], "Artistic"), + (&["Effect"], "Blur"), + (&["Effect"], "Brush Strokes"), + (&["Effect"], "Distort"), + (&["Effect"], "Pixelate"), + (&["Effect"], "Sharpen"), + (&["Effect"], "Sketch"), + (&["Effect"], "Texture"), + (&["Effect"], "Video"), + (&["Effect"], "Plug-ins"), + (&["View"], "Outline"), + (&["View"], "Preview"), + (&["View"], "Pixel Preview"), + (&["View"], "Trim View"), + (&["View"], "Presentation Mode"), + (&["View"], "Screen Mode"), + (&["View"], "Proof Setup"), + (&["View"], "Zoom In"), + (&["View"], "Zoom Out"), + (&["View"], "Fit Artboard in Window"), + (&["View"], "Fit All in Window"), + (&["View"], "Actual Size"), + (&["View"], "Rotate View"), + (&["View"], "Rotate View to Selection"), + (&["View"], "Reset Rotate View"), + (&["View"], "Hide Edges"), + (&["View"], "Show Edges"), + (&["View"], "Hide Artboards"), + (&["View"], "Show Artboards"), + (&["View"], "Hide Template"), + (&["View"], "Show Template"), + (&["View"], "Rulers"), + (&["View"], "Hide Bounding Box"), + (&["View"], "Show Bounding Box"), + (&["View"], "Hide Text Threads"), + (&["View"], "Show Text Threads"), + (&["View"], "Hide Gradient Annotator"), + (&["View"], "Show Gradient Annotator"), + (&["View"], "Hide Corner Widget"), + (&["View"], "Show Corner Widget"), + (&["View"], "Show Live Paint Gaps"), + (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Guides"), + (&["View"], "Smart Guides"), + (&["View"], "Perspective Grid"), + (&["View"], "Show Grid"), + (&["View"], "Hide Grid"), + (&["View"], "Snap to Grid"), + (&["View"], "Snap to Pixel"), + (&["View"], "Snap to Point"), + (&["View"], "Snap to Glyph"), + (&["View"], "Saved View"), +]; + /// The command spec of plug-in `p`'s command `c`: its id, its label as menus show it (escaped and -/// capped), its menu (Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a live -/// effect: never a menu the manifest names) and its params description. +/// capped, and followed by the plug-in's name when it is listed in another menu), its menu +/// ([`placed_menu`], else Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a +/// live effect) and its params description. fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { let m = p.manifest(); let id = command_id(&m.id, &c.id); - let label = c.shown_label(); + let placed = placed_menu(p, c); + let label = if placed.is_some() { c.menu_label(&m.name) } else { c.shown_label() }; let top = if m.kind == Kind::Effect { "Effect" } else { "Object" }; let name = permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME); + let submenu = [top, "Plug-ins", name.as_str()]; + let path: &[&str] = placed.unwrap_or(&submenu); let mut fields = String::from("ids?: [object id] (left out or null: the selection), params?: {…} (its parameters; or give them as top-level keys)"); let doc = m.for_command(c).params_doc(); @@ -518,11 +793,14 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); - let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == [top, "Plug-ins", name.as_str()] && s.params == params; + let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == path && s.params == params; if let Some(s) = made.iter().find(same) { return s; } - let menu: &'static [&'static str] = Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()); + let menu: &'static [&'static str] = match placed { + Some(path) => path, + None => Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()), + }; let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec { id: registry::intern(&id), label: registry::intern(&label), @@ -1301,7 +1579,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..ec7d3ac989 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -60,6 +60,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pathtools.erase", "addon.pathtools.expandDashes", "addon.pathtools.extend", + "addon.pathtools.inscribedCircle", "addon.pathtools.inspect", "addon.pathtools.mergeEdge", "addon.pathtools.removeKeepShape", @@ -466,6 +467,7 @@ pub(super) const ALLOWED: &[&str] = &[ "path.moveAnchor", "path.moveAnchors", "path.quickPen", + "path.quickPenLength", "path.rectCut", "path.removeAnchor", "path.removeAnchors", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 81a26dd46e..890f72455d 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)), p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool), + p!("deleteKeepsPathsJoined", "General", "Options", "Delete Removes Anchor Points and Keeps Paths Joined", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..2640433606 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}; a missing grants file lists none, and one that is there but cannot be read, is too large, is not a grants file of this version or holds no list of grants, or whose lock cannot be taken, is an error (a grant in it that is not well formed is left out)", always, grants ), @@ -369,7 +369,8 @@ fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); // A script or a granted path outside the automation read roots is named by its file name alone. - let mut grants = script::files::stored_grants(dir); + let mut grants = + script::files::stored_grants(dir).map_err(|e| EngineError::Other(format!("the script file permissions could not be read: {e}")))?; for g in &mut grants { for key in ["script", "path"] { if let Some(name) = g[key].as_str().and_then(hidden_name) { diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index e159ad9090..c4db83826e 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -17,6 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; +use super::clipboard::resources::numbered_name; use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file}; use super::menucmds::squash; use super::package::free_name; @@ -49,7 +50,7 @@ pub fn specs() -> Vec { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1029,55 +1030,27 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) name } -/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered -/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own -/// swatches of those names, so that a color the art brings under a numbered name does not take one -/// of them. While the import runs, a placeholder swatch holds each such name the art does not -/// bring, and a copy of the library's color holds each one the art brings, which the art then -/// takes. The placeholders are removed before it returns, and so is a copy the art did not take; -/// a copy the art took is listed with the colors the import brought. Names of the patterns the -/// import brings are not held. -fn import_holding( - d: &mut vectorcraft_doc::Document, - src: &vectorcraft_doc::Document, - pattern: &str, - names: &HashMap<&str, &Swatch>, -) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> { - let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())); - let taken = taken_names(d); - let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect(); - free.sort_unstable(); - let (mut held, mut copies): (Vec, Vec) = (vec![], vec![]); - if !free.is_empty() { - let brings = patternlib::brought_names(src, pattern); - let patterns = patternlib::brought_patterns(src, pattern); - for n in free.into_iter().filter(|n| !patterns.contains(*n)) { - if !brings.contains(n) { - held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false }); - } else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) { - copies.push((*w).clone()); - } +/// The name of the document's swatch for library pattern swatch `w`, whose pattern came in as +/// `target`, the import having made swatch `made` for it (removed again). A numbered name skips +/// the names of the library's other swatches (`lib_by_name`), as for a color; so does a swatch +/// named after its pattern when the pattern's name is one of them. The swatch takes the library +/// swatch's numbered name when it is free and the library has no other swatch of that name, and leaves a +/// numbered name the library gives an earlier swatch to that one. +fn pattern_swatch_name(w: &Swatch, target: &str, made: Option, taken: &mut HashSet, lib_by_name: &HashMap<&str, &Swatch>) -> String { + let reserved = |n: &str| lib_by_name.contains_key(n); + let owns = lib_by_name.get(w.name.as_str()).is_some_and(|o| *o == w); + let named_after = matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == w.name); + match made { + _ if named_after && owns && numbered_name(&w.name) && !taken.contains(&w.name) => w.name.clone(), + _ if !owns && numbered_name(&w.name) && !taken.contains(&w.name) => { + let mut held = taken.clone(); + held.insert(w.name.clone()); + free_copy_in(&mut held, &w.name, reserved) } + Some(made) if named_after => made, + None if named_after && (target == w.name || !reserved(target)) => free_copy_in(taken, target, reserved), + _ => free_copy_in(taken, &w.name, reserved), } - let start = d.swatches.len(); - d.swatches.extend(held.iter().chain(&copies).cloned()); - let imported = patternlib::import(d, src, pattern); - let used = |n: &str| { - imported - .as_ref() - .is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n)) - }; - let used: HashSet = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect(); - let mut i = 0; - d.swatches.retain(|w| { - i += 1; - let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint); - !(i > start && ours && !used.contains(&w.name)) - }); - let (target, mut colors, mut took) = imported?; - took.retain(|(from, _)| !used.contains(from)); - colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n))); - Ok((target, colors, took)) } /// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors @@ -1202,6 +1175,25 @@ fn add(s: &mut Session, p: &Value) -> Result { for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) { lib_by_name.entry(w.name.as_str()).or_insert(w); } + // A swatch a pattern's art brings under a numbered name skips the library's numbered names, + // which a later add looks up as those swatches'. Only the names a picked pattern's swatches and + // patterns can come in under, their own or one numbered after them, are needed. + let mut brings_names: HashSet = HashSet::new(); + if let Some(src) = patterns.as_ref().filter(|_| lib_by_name.keys().any(|n| numbered_name(n))) { + let picked_patterns: BTreeSet<&str> = picked + .iter() + .filter_map(|(_, w)| match &w.paint { + Paint::Pattern { pattern, .. } => Some(pattern.as_str()), + _ => None, + }) + .collect(); + for pattern in picked_patterns { + brings_names.extend(patternlib::brought_resource_names(src, pattern)); + } + } + let can_take = |n: &str| brings_names.contains(n) || n.rsplit_once(' ').is_some_and(|(base, _)| brings_names.contains(base)); + let lib_names: patternlib::Reserved = + Arc::new(lib_by_name.iter().filter(|(n, _)| numbered_name(n) && can_take(n)).map(|(n, w)| (n.to_string(), (*w).clone())).collect()); let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect(); // A color whose name the document gives another color, or a color group, is the numbered copy // of it that an earlier add or a pattern's art brought in, when that copy is the same color. A @@ -1233,7 +1225,7 @@ fn add(s: &mut Session, p: &Value) -> Result { if let Some(src) = &patterns { for (_, w) in &picked { let Paint::Pattern { pattern, .. } = &w.paint else { continue }; - present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern)); + present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern, &lib_names)); } } // Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors @@ -1438,7 +1430,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?; + let (_, colors, took) = patternlib::import(&mut probe, src, pattern, &lib_names)?; for (from, to) in colors_of(&probe, &colors, &took) { if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { e.insert(to); @@ -1448,7 +1440,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?; + let (target, colors, took) = patternlib::import(d, src, pattern, &lib_names)?; // Those colors are the ones the library's tints of them link to, unless the // document already has one for them. A name the copy gave that the import // into the document did not give is replaced, and the tints linked to it are @@ -1483,11 +1475,7 @@ fn add(s: &mut Session, p: &Value) -> Result { d.swatches.retain(|x| x.name != *made); } taken = taken_names(d); - let name = match made { - Some(made) if w.name == *pattern => made, - None if w.name == *pattern => d.free_swatch_name(&target), - _ => free_in(&mut taken, &w.name), - }; + let name = pattern_swatch_name(w, &target, made, &mut taken, &lib_by_name); taken.insert(name.clone()); // The library swatch's placement of its pattern is kept. let paint = match &w.paint { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 1b0766e658..734e7fd972 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1895,14 +1895,21 @@ enum Step { /// The Type tool's selected text while it edits (its typing session ends first: one undo step, /// with typing that Real-time Drawing off left unapplied applied first). pub(crate) fn editing_range(s: &mut Session) -> Result> { - let o = s.tool_options(); - let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; + let Some(range) = selected_range(s) else { return Ok(None) }; if super::edit::typing_in_progress(s) { s.set_tool_option("commitTyping", &Value::Bool(true)); super::edit::settle_interaction(s)?; } + Ok(Some(range)) +} + +/// The Type tool's selected text while it edits, as [`editing_range`] reads it, with its typing +/// session left running. +pub(crate) fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> { + let o = s.tool_options(); + let id = o.get("editing").and_then(Value::as_u64).map(NodeId)?; let at = |k: &str| byte_param(&o, k).unwrap_or(0); - Ok(Some((id, at("start"), at("end")))) + Some((id, at("start"), at("end"))) } /// The frames of the story whose whole text the Type tool has selected after Select All in a diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 12d8559dff..3ca9435cc8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -107,6 +107,19 @@ pub struct Session { /// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd /// lends the other tools. None until one is chosen. pub(crate) last_selection_tool: Option<&'static str>, + /// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the + /// Selection tool. None until one is chosen. + pub(crate) last_part_selection_tool: Option<&'static str>, + /// The selection tool Cmd lent the last press, which also takes the double-click or + /// triple-click that follows it, with the uid of the document and the id of the tool it was + /// lent from: a follow-up in another document, after a tool switch (also one back to the same + /// tool) or after the tool starts afresh is not lent. None when the press was not lent. + pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, + /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] + /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with + /// the document state, active tool and keys it was found for. None when it was last asked + /// without Cmd. + pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>, pub(crate) last_view: ViewInfo, /// The selection tools' measurements for the active document as it is: a pointer move or a /// cursor asked for again over an unchanged document and selection measures nothing again. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 91580248c5..990cbd25c2 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -55,6 +55,12 @@ pub struct Prefs { /// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the /// default), the handles of a moved anchor move with it and the other handles stay. pub interpolate_control_points: bool, + /// General › Delete Removes Anchor Points and Keeps Paths Joined: the default of the + /// `keepJoined` param of `edit.clear` (the Delete and Backspace keys and Edit › Clear). On, + /// Clear removes the direct-selected anchors of a path as Remove Anchor Points does, refitting + /// the curve around each one, instead of deleting them with their segments. Off (the default), + /// Clear opens the path there. + pub delete_keeps_paths_joined: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the @@ -479,6 +485,7 @@ impl Default for Prefs { corner_radius: 12.0, disable_auto_add_delete: false, interpolate_control_points: false, + delete_keeps_paths_joined: false, use_precise_cursors: false, show_tool_tips: true, show_tool_cards: false, diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 9bd7815c8b..476fbde5ad 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -923,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { /// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read /// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let Ok(_lock) = lock_store(store) else { return Vec::new() }; - load_store(store, false).unwrap_or_default() + list_store(store).unwrap_or_default() +} + +/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock +/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of +/// this version or holds no list of grants. +fn list_store(store: &Path) -> std::io::Result> { + let _lock = lock_store(store)?; + load_store(store, false) } /// The grants the grants file at `store` holds, to change and write back; none when it is missing, @@ -940,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result> { fn load_store(store: &Path, strict: bool) -> std::io::Result> { let bytes = match read_head(store, MAX_STORE_BYTES) { Ok(bytes) => bytes, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + // A link whose target is missing is there but cannot be read. + Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()), Err(e) => return Err(e), }; if bytes.len() > MAX_STORE_BYTES { @@ -958,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result MAX_STORED_GRANTS || !grants.iter().all(valid) { return Err(std::io::Error::other("the grants file holds a grant that cannot be read")); } return Ok(grants.clone()); } - Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default()) + Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()) } /// The number in the name of the next file [`write_store`] writes before it takes the grants file's @@ -1065,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result { } /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of -/// its text, the path and whether it may be written (`script.grants`). -pub(crate) fn stored_grants(data_dir: &Path) -> Vec { - read_store(&data_dir.with_file_name(GRANTS_FILE)) +/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them. +pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result> { + list_store(&data_dir.with_file_name(GRANTS_FILE)) } /// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2ca404c9d7..d924813def 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -69,6 +69,9 @@ impl Session { selection_at_lend: None, lent_selection: None, last_selection_tool: None, + last_part_selection_tool: None, + press_lent: None, + hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), depth: 0, @@ -211,6 +214,7 @@ impl Session { return; } self.press_type_selection = None; + self.press_lent = None; let view = self.last_view; // The edit the tool computes on another thread and the input held for it belong to the // document being left. The switch goes on whatever they did, as for the deactivation. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 17e25ed2e3..05f9591eaa 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,6 +49,7 @@ mod curvature_circle; mod cut; mod dashalign; mod dcs; +mod delete_keeps_joined; mod distort; mod docsetup; mod document_close; @@ -123,6 +124,7 @@ mod outlineobject; pub(super) mod outlinestroke; mod overprint; mod package; +mod paintopacity; mod paintproxy; mod panelcmds; mod paragraphs; diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index 00b20ca6a1..672bb4b561 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -776,6 +776,15 @@ fn overprint_black_and_print_fixes_reach_a_colorized_images_color() { let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap(); assert_eq!(v["whiteOverprintRemoved"], 1, "{v}"); assert!(!overprints(&s), "white knocks out again"); + // A white spot ink is an ink: Remove White Overprint leaves its overprint. + s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert!(overprints(&s), "the spot white overprints"); + let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap(); + assert_eq!(v["whiteOverprintRemoved"], 0, "{v}"); + assert!(overprints(&s), "the spot white keeps overprinting"); } /// A flattening for a file that writes colorized images in their ink (EPS) keeps the image, and diff --git a/crates/engine/src/tests/delete_keeps_joined.rs b/crates/engine/src/tests/delete_keeps_joined.rs new file mode 100644 index 0000000000..8a0b625e8e --- /dev/null +++ b/crates/engine/src/tests/delete_keeps_joined.rs @@ -0,0 +1,227 @@ +//! General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`). With +//! it on, Delete (`edit.clear`) removes the direct-selected anchors of a path as Remove Anchor +//! Points does, without opening the path. Off (the default), Delete removes them with their +//! segments. + +use serde_json::json; +use vectorcraft_geom::{PathData, Point}; + +use super::history; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn keep_joined(s: &mut Session, on: bool) { + s.execute("prefs.set", &json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap(); +} + +fn path_of(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned()) +} + +fn points(s: &Session, id: NodeId) -> Vec { + path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() +} + +fn create(s: &mut Session, anchors: serde_json::Value, closed: bool) -> NodeId { + NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": closed })).unwrap()["id"].as_u64().unwrap()) +} + +fn square(s: &mut Session, x: f64) -> NodeId { + create(s, json!([{"x": x, "y": 100}, {"x": x + 100.0, "y": 100}, {"x": x + 100.0, "y": 200}, {"x": x, "y": 200}]), true) +} + +fn line(s: &mut Session, y: f64) -> NodeId { + create(s, json!([{"x": 100, "y": y}, {"x": 150, "y": y - 20.0}, {"x": 200, "y": y}, {"x": 250, "y": y + 20.0}, {"x": 300, "y": y}]), false) +} + +fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value, mode: &str) { + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap(); +} + +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum() +} + +#[test] +fn off_by_default_delete_opens_a_closed_path() { + let mut s = session(); + assert!(!s.prefs.delete_keeps_paths_joined); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert!(!path.subpaths[0].closed, "the path opens where the anchor was"); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} + +#[test] +fn with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + let before = history(&s).0; + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed, "the path stays closed"); + assert!(!points(&s, id).contains(&Point::new(200.0, 100.0)), "the selected anchor is gone"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id], "the path stays selected"); + assert_eq!(st.selection.anchors[&id], [(0, 1)].into(), "the anchor after the removed one is selected"); + // A second Delete goes on along the path. + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(points(&s, id), vec![Point::new(100.0, 100.0), Point::new(100.0, 200.0)]); +} + +#[test] +fn an_open_path_loses_an_end_anchor_and_an_interior_anchor_without_splitting() { + let mut s = session(); + keep_joined(&mut s, true); + let id = line(&mut s, 300.0); + select(&mut s, id, json!([[0, 0], [0, 2]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1, "one piece"); + assert!(!path.subpaths[0].closed); + assert_eq!( + points(&s, id), + vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0), Point::new(300.0, 300.0)], + "the path is shorter at its start" + ); + assert_eq!(objects(&s), 1, "no new object"); + assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the anchor after the last removed one is selected"); + // Removing the last anchor of an open path selects the one before it. + select(&mut s, id, json!([[0, 2]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(points(&s, id), vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0)], "the path is shorter at its end"); + assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the new end anchor is selected"); +} + +#[test] +fn a_subpath_left_with_one_anchor_goes_and_the_path_stays_selected_whole() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + let sq = json!({"closed": true, "anchors": [{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]}); + let pair = json!({"closed": false, "anchors": [{"x": 300, "y": 100}, {"x": 400, "y": 100}]}); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [sq, pair]})).unwrap(); + select(&mut s, id, json!([[1, 0]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1, "the subpath left with one anchor goes"); + assert!(path.subpaths[0].closed && path.subpaths[0].anchors.len() == 4, "the other subpath is untouched"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id], "the path stays selected"); + assert!(st.selection.anchors.get(&id).is_none_or(|a| a.is_empty()), "no anchor is left to go on from"); +} + +#[test] +fn a_path_left_with_fewer_than_two_anchors_is_deleted() { + let mut s = session(); + keep_joined(&mut s, true); + let id = create(&mut s, json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}]), false); + let other = square(&mut s, 400.0); + select(&mut s, id, json!([[0, 1]]), "set"); + select(&mut s, other, json!([[0, 0]]), "add"); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(path_of(&s, id).is_none(), "a single anchor is no path"); + assert!(path_of(&s, other).unwrap().subpaths[0].closed, "the other path keeps its other anchors joined"); + assert_eq!(s.doc().unwrap().selection.objects, vec![other]); +} + +#[test] +fn several_paths_and_an_object_selected_whole_change_in_one_undo_step() { + let mut s = session(); + keep_joined(&mut s, true); + let (a, b, whole) = (square(&mut s, 100.0), line(&mut s, 400.0), square(&mut s, 500.0)); + select(&mut s, a, json!([[0, 0]]), "set"); + select(&mut s, b, json!([[0, 1], [0, 3]]), "add"); + s.execute("select.add", &json!({"ids": [whole.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let before = history(&s).0; + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + assert!(path_of(&s, whole).is_none(), "the object selected whole is deleted"); + assert!(path_of(&s, a).unwrap().subpaths[0].closed); + assert_eq!(path_of(&s, a).unwrap().subpaths[0].anchors.len(), 3); + assert_eq!(points(&s, b), vec![Point::new(100.0, 400.0), Point::new(200.0, 400.0), Point::new(300.0, 400.0)]); + let st = s.doc().unwrap(); + assert!(st.selection.anchors.contains_key(&a) && st.selection.anchors.contains_key(&b), "both paths keep an anchor selected"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, doc, "Undo restores every path"); +} + +#[test] +fn a_compound_path_keeps_its_members_and_loses_one_left_with_no_segment() { + let mut s = session(); + keep_joined(&mut s, true); + let (outer, inner) = (square(&mut s, 100.0), create(&mut s, json!([{"x": 130, "y": 150}, {"x": 170, "y": 150}]), false)); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, outer, json!([[0, 2]]), "set"); + select(&mut s, inner, json!([[0, 0]]), "add"); + s.execute("edit.clear", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the member left with one anchor goes"); + assert_eq!(d.parent_of(outer), Some(compound), "the other member stays in the compound path"); + assert!(path_of(&s, outer).unwrap().subpaths[0].closed); + assert_eq!(path_of(&s, outer).unwrap().subpaths[0].anchors.len(), 3); +} + +#[test] +fn a_selected_segment_is_still_cut() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 0]]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert!(!path.subpaths[0].closed, "the segment's connection is removed"); + assert_eq!(path.subpaths[0].anchors.len(), 4, "every anchor stays"); +} + +#[test] +fn the_keep_joined_param_overrides_the_preference_and_must_be_a_boolean() { + let mut s = session(); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + assert!(s.execute("edit.clear", &json!({"keepJoined": "yes"})).is_err()); + assert_eq!(path_of(&s, id).unwrap().subpaths[0].anchors.len(), 4, "a refused call changes nothing"); + s.execute("edit.clear", &json!({"keepJoined": true})).unwrap(); + assert!(path_of(&s, id).unwrap().subpaths[0].closed); + keep_joined(&mut s, true); + s.execute("edit.clear", &json!({"keepJoined": false})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "false opens the path with the preference on"); +} + +#[test] +fn a_replay_removes_anchors_as_the_recorded_step_did() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + let start = s.journal.len(); + s.execute("edit.clear", &json!({})).unwrap(); + let removed = path_of(&s, id); + assert!(removed.as_ref().is_some_and(|p| p.subpaths[0].closed), "the path stays closed"); + let (cmd, params) = s.journal.since(start).last().cloned().unwrap(); + assert_eq!(params["keepJoined"], json!(true), "{cmd}: journaled"); + s.execute("edit.undo", &json!({})).unwrap(); + keep_joined(&mut s, false); + select(&mut s, id, json!([[0, 1]]), "set"); + s.replay(&cmd, ¶ms).unwrap(); + assert_eq!(path_of(&s, id), removed); + // A step saved before the preference existed has no `keepJoined` and still opens the path. + s.execute("edit.undo", &json!({})).unwrap(); + keep_joined(&mut s, true); + select(&mut s, id, json!([[0, 1]]), "set"); + s.replay("edit.clear", &json!({})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed); +} diff --git a/crates/engine/src/tests/docsetup.rs b/crates/engine/src/tests/docsetup.rs index 0fdb189d67..01fc0dbff7 100644 --- a/crates/engine/src/tests/docsetup.rs +++ b/crates/engine/src/tests/docsetup.rs @@ -482,6 +482,13 @@ fn discard_white_overprint_keeps_white_overprints_in_overprint_preview() { s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap(); let [r, g, b, _] = centre(&s); assert!(r > 200 && g < 60 && b < 60, "a white overprint vanishes: {:?}", [r, g, b]); + // A white spot ink is an ink: it overprints with the option on too. + s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [white]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + let [r, g, b, _] = centre(&s); + assert!(r > 200 && g < 60 && b < 60, "the spot white overprints: {:?}", [r, g, b]); } #[test] diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index d58f8da2ff..25f954dc4b 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4860,6 +4860,460 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() { s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap(); } +#[test] +fn cmd_lends_the_selection_tool_direct_selection_or_group_selection_chosen_last() { + // Cmd held with the Selection tool: Direct Selection takes the press until the release, so a + // Cmd-click picks one path inside a group where a plain click picks the group. + let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() }); + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&none), None); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&none), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the Cmd-click picks the path, not its group"); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap(); + assert!(s.active().unwrap().selection.contains(group), "a plain click picks the group"); + // Cmd pressed once a drag is under way lends nothing: the pointer and the named tool stay. + s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 500.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 650.0, 550.0), v).unwrap(); + assert_eq!(s.cursor(Point::new(650.0, 550.0), cmd, v), s.cursor(Point::new(650.0, 550.0), none, v)); + assert_eq!(s.shown_tool_id(&cmd), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 650.0, 550.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + // Group Selection lends the Selection tool, and once chosen, is what the Selection tool borrows. + s.select_tool("groupSelection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("selection")); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("groupSelection")); + s.select_tool("directSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); +} + +#[test] +fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() { + // With the Selection tool, Cmd-clicks go to Direct Selection, and so does the double-click + // after them: it does not isolate the group as the Selection tool's double-click would. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.tool_id(), "selection"); + assert_eq!(s.doc().unwrap().isolation, None, "Direct Selection's double-click does not isolate the group"); + // With Group Selection chosen last, the second click selects the group, and the double-click + // still goes to Group Selection, as both clicks did. + s.select_tool("groupSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.doc().unwrap().isolation, None, "Group Selection's double-click does not isolate the group"); + s.execute("select.none", &json!({})).unwrap(); + // A plain double-click is the Selection tool's: it isolates the group. + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0), v).unwrap(); + } + assert!(s.doc().unwrap().isolation.is_some()); +} + +#[test] +fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() { + // With the Selection tool, a Cmd-click on type goes to Direct Selection, and so does the + // Cmd double-click after it, which edits the type. Once another tool is chosen, the + // double-click is that tool's: Group Selection's does not edit the type. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 200, "size": 48, "text": "Type"})).unwrap()["id"].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().center(); + let clicks = |s: &mut Session, then: Option<&str>| { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, c.x, c.y).with_mods(cmd), v).unwrap(); + } + if let Some(tool) = then { + s.select_tool(tool, v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y).with_mods(cmd), v).unwrap() + }; + assert_eq!(clicks(&mut s, None), [UiRequest::SwitchTool("type".into())], "Direct Selection's double-click edits the type"); + assert_eq!(clicks(&mut s, Some("groupSelection")), [], "Group Selection's double-click does not"); + assert_eq!(s.tool_id(), "groupSelection"); +} + +#[test] +fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() { + // A Cmd-click with the Selection tool goes to Direct Selection. After a switch to another tool + // and back to the Selection tool, or a fresh start of the tool (another view of the document), + // the Cmd double-click is the Selection tool's: it isolates the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + for reset in [false, true] { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + if reset { + s.reset_tool(); + } else { + s.select_tool("rectangle", v).unwrap(); + s.select_tool("selection", v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + assert!(s.doc().unwrap().isolation.is_some(), "the Selection tool's double-click isolates the group (reset: {reset})"); + s.execute("object.exitIsolation", &json!({})).unwrap(); + } +} + +#[test] +fn a_cmd_press_on_a_selected_object_keeps_select_behind() { + // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; + // with Select Behind off, Direct Selection takes the press there too. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The canvas shows the marks of the tool a press at the pointer takes, and the status bar and + // the help bar name it. + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.shown_tool_id(&cmd), "selection", "the press selects behind: nothing is lent"); + s.cursor(Point::new(500.0, 500.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + // The bounding box's top middle handle, on the middle of the top segment: the press is lent. + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 150.0)), &cmd, v), "directSelection", "on a box handle"); + // Turning Select Behind off changes what the bars name over the selection. + s.cursor(Point::new(200.0, 200.0), cmd, v); + s.prefs.ctrl_click_selects_behind = false; + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + s.prefs.ctrl_click_selects_behind = true; + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + // On a selected object's anchor, Direct Selection takes the press. + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.prefs.ctrl_click_selects_behind = false; + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { + // Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which + // the Selection tool still hits: a Cmd press there selects the object behind. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + assert!(!s.prefs.use_preview_bounds); + let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // 15 pt outside the path, on its stroke. + let at = Point::new(200.0, 135.0); + assert_eq!(s.hover_tool_at(Some(at), &cmd, v), "selection", "the press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn a_cmd_press_on_a_lone_selected_object_is_lent() { + // With nothing behind the selected object, there is nothing to select behind: Direct Selection + // takes the press. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() { + // A layer effect draws the selected object 250 pt to the right of its path, over the object + // behind it: a Cmd press where it is drawn selects behind. A drop shadow there is not hit, so + // the press is lent. Outline view hits the path where it is, and Preview afterwards still finds + // the moved art. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let outline = ViewInfo { outline: true, ..view() }; + let drawn = Point::new(450.0, 200.0); + // On both rectangles' top edges, which Outline view hits, away from the box's handles. + let path = Point::new(170.0, 150.0); + for effect in ["distort.transform", "stylize.dropShadow"] { + let mut s = session(); + let back = rect(&mut s, 50.0, 150.0, 700.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + let layer = s.doc().unwrap().doc.layers[0].id; + let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) }; + s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The back rectangle is drawn moved too, so it is under both points. + if effect == "distort.transform" { + assert_eq!(s.hover_tool_at(Some(path), &cmd, outline), "selection", "Outline view: on the path"); + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "selection", "Preview: where the effect draws it"); + s.pointer(&PointerEvent::new(PointerKind::Down, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + } else { + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "directSelection", "on the shadow"); + } + } +} + +#[test] +fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { + // The first Cmd-click on an unselected group lends Direct Selection, which selects the path + // under the pointer. The group holds that selected path, so the next Cmd-click there selects + // the object behind the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 210.0, 150.0, 40.0, 40.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 170.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 170.0).with_mods(cmd), v).unwrap(); + }; + click(&mut s); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the first Cmd-click picks the path"); + assert_eq!(s.hover_tool_at(Some(Point::new(170.0, 170.0)), &cmd, v), "selection", "the next press selects behind"); + click(&mut s); + // Made quickly, the two clicks are also a double-click, which neither isolates the group nor + // changes what the second click selected, also with Cmd let go before it. + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 170.0, 170.0), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group"); +} + +#[test] +fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { + // A double-click that follows a Cmd-click selecting behind keeps what it selected, but only + // while the document stays as that click left it. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() { + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() { + // A Cmd press that selects behind and then drags is not a click, also when the drag ends where + // it began and moves nothing, so a double-click there is a double-click of its own. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_select_behind() { + // The automation interface can send the release far from the press with no drag between. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 270.0, 270.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() { + // The second press and the double-click can come in one frame, before the release. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None, "the double-click neither isolates nor edits"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(front) && !picked.contains(back), "the press selects behind, back to the topmost"); +} + +#[test] +fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() { + // The group counts as selected wherever its art is, not only over its selected member. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 300.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member"); + s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group"); +} + +#[test] +fn a_cmd_click_on_a_selected_lines_segment_selects_behind() { + // An open, unfilled path is only hit near its segments: a Cmd press there selects the object + // behind it, and a Cmd press on its anchor is Direct Selection's. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = line(&mut s, 150.0, 150.0, 250.0, 250.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor"); + // On the segment, away from the anchors and the bounding box's handles. + s.pointer(&PointerEvent::new(PointerKind::Down, 180.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for() { + // While the view moves, the canvas reads the last hover's decision: it does not carry over to + // another tool or another selection. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "nothing is selected now"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection"); + s.select_tool("rectangle", v).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), s.lent_tool_id(&cmd).unwrap(), "the new tool's lend"); +} + +#[test] +fn the_marks_follow_this_frames_pointer_with_cmd_held() { + // The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for + // the pointer where it is now, and with the pointer off the canvas, the tool Cmd lends. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection", "away from the selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "over the selection"); + assert_eq!(s.hover_tool_at(None, &cmd, v), "directSelection", "off the canvas"); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "kept while the view moves"); + assert_eq!(s.hover_tool_at(None, &Mods::default(), v), "selection", "without Cmd"); +} + #[test] fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() { // #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor, diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index fc1305a0a7..2f88f5acc9 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1212,6 +1212,26 @@ fn select_part_refuses_hidden_and_locked_objects_of_the_art() { s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1, 1]})).unwrap(); } +#[test] +fn a_cmd_click_with_the_selection_tool_keeps_the_instance_selected_whole() { + // Cmd lends Direct Selection the Selection tool: the press picks one object of a dynamic + // instance, and back with the Selection tool after the release, the instance stays selected, + // whole, as choosing the Selection tool leaves it. + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Mods::default() }; + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.doc().unwrap().selection.symbol_part.is_some(), "the lent tool picks the object"); + s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let sel = &s.doc().unwrap().selection; + assert_eq!((&sel.objects, &sel.symbol_part), (&vec![inst], &None)); +} + #[test] fn choosing_the_selection_tool_again_picks_the_instance_whole() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 11330bac10..b65d4a4b9a 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -533,6 +533,102 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() { assert_eq!(history(&s), before); } +/// Rearrange with `indices` lays out only those artboards, in document order whatever order they +/// are listed in, with the grid's top-left at `at`: their art and guides go along, and the other +/// artboards, their art and their guides stay where they are, all in one undo step. +#[test] +fn rearrange_lays_out_only_the_listed_artboards() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4})); + let before = boards(&s); + let art: Vec = before + .iter() + .map(|r| { + NodeId( + s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"] + .as_u64() + .unwrap(), + ) + }) + .collect(); + for i in [0, 1] { + s.execute("guide.add", &json!({"vertical": true, "pos": before[i].x0 + 5.0, "artboard": i})).unwrap(); + } + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"indices": [3, 1], "layout": "row", "spacing": 10, "at": [500, 400]}); + let r = s.execute("artboard.rearrange", &p).unwrap(); + assert_eq!(r, json!({"artboards": 4, "indices": [1, 3], "moved": 2, "rows": 1, "columns": 2})); + let after = boards(&s); + assert_eq!((after[0], after[2]), (before[0], before[2]), "the artboards not listed stay"); + assert_eq!((after[1], after[3]), (Rect::new(500.0, 400.0, 600.0, 450.0), Rect::new(610.0, 400.0, 710.0, 450.0))); + let d = &s.doc().unwrap().doc; + for (id, r) in art.iter().zip(&after) { + let b = d.node(*id).unwrap().geometric_bounds().unwrap(); + assert_eq!((b.x0, b.y0), (r.x0 + 10.0, r.y0 + 10.0), "the art is on its artboard"); + } + let guides: Vec = d.ruler_guides().iter().map(|g| g.pos).collect(); + assert_eq!(guides, [before[0].x0 + 5.0, 505.0]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(boards(&s), before); +} + +/// Without `at`, the grid of the listed artboards starts at the first one's top-left; one listed +/// artboard is laid out alone; a listed locked artboard stays and keeps its cell; when every listed +/// artboard is locked, nothing moves, no undo step is recorded and `moved` is 0. +#[test] +fn rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4, "artboardLayout": {"layout": "row", "spacing": 20}})); + let before = boards(&s); + // Artboards 1 and 3 in one column, from artboard 1's corner. + let r = s.execute("artboard.rearrange", &json!({"indices": [1, 3], "layout": "column", "spacing": 10})).unwrap(); + assert_eq!(r["moved"], 1); + let after = boards(&s); + assert_eq!(after[1], before[1]); + assert_eq!(after[3], Rect::new(before[1].x0, before[1].y1 + 10.0, before[1].x1, before[1].y1 + 60.0)); + // One artboard goes to `at`. + s.execute("artboard.rearrange", &json!({"indices": [2], "at": [-300, -200]})).unwrap(); + assert_eq!(boards(&s)[2], Rect::new(-300.0, -200.0, -200.0, -150.0)); + // Artboard 0 locked keeps its place and its cell: artboard 2 goes to the second cell from 0's. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let r = s.execute("artboard.rearrange", &json!({"indices": [0, 2], "layout": "row", "spacing": 5, "at": [1000, 0]})).unwrap(); + assert_eq!(r["moved"], 1); + assert_eq!((boards(&s)[0], boards(&s)[2]), (before[0], Rect::new(1105.0, 0.0, 1205.0, 50.0))); + // Every listed artboard locked: nothing moves. + let placed = boards(&s); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("artboard.rearrange", &json!({"indices": [0], "at": [3000, 3000]})).unwrap(); + assert_eq!(r, json!({"artboards": 4, "indices": [0], "moved": 0, "rows": 1, "columns": 1})); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), (placed, undo)); +} + +/// Rearrange refuses `indices` that are not a non-empty list of artboards, and an `at` that is not +/// [x, y], before anything moves, and leaves the document as it was when `at` would put an +/// artboard past the canvas; a listed index given twice counts once. +#[test] +fn rearrange_refuses_bad_indices_and_at() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); + let before = (boards(&s), s.doc().unwrap().history.undo.len()); + for (p, msg) in [ + (json!({"indices": []}), "invalid parameters for `artboard.rearrange`: `indices` must be a non-empty list of artboard indices"), + (json!({"indices": 1}), "invalid parameters for `artboard.rearrange`: `indices` must be a list of artboard indices"), + (json!({"indices": [1.5]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": [-1]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": ["1"]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": [0, 3]}), "no such artboard"), + (json!({"indices": [0, 1], "at": [1]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"indices": [0, 1], "at": "0,0"}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"at": [0, "1"]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"indices": [0], "at": [1e20, 0]}), "result would exceed the canvas (coordinates out of range)"), + (json!({"at": [0, -4.000001e6]}), "result would exceed the canvas (coordinates out of range)"), + ] { + let err = s.execute("artboard.rearrange", &p).unwrap_err().to_string(); + assert_eq!(err, msg, "{p}"); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), before, "{p}"); + } + let r = s.execute("artboard.rearrange", &json!({"indices": [2, 2], "at": [0, 500]})).unwrap(); + assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0))); +} + /// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 9474973adb..344b5e436e 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -792,7 +792,7 @@ fn the_document_info_report_has_every_category() { assert!(text.contains(&format!("\n{h}\n")), "{h}: {text}"); } assert!(text.contains("Images: 3") && text.contains("Source Sans 3 Regular: built in; embedding allowed"), "{text}"); - assert!(text.contains("red.png: 600 × 300 px — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}"); + assert!(text.contains("red.png: PNG; 600 × 300 px; 72 ppi — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}"); let fonts = run(&mut s, "document.info", json!({"format": "text", "category": "fonts"}))["text"].as_str().unwrap().to_string(); assert!(fonts.contains("FONTS") && !fonts.contains("OBJECTS"), "{fonts}"); let i = run(&mut s, "document.info", json!({"category": "linkedImages"})); @@ -802,7 +802,7 @@ fn the_document_info_report_has_every_category() { // embedded one with no file. let linked: Vec = i["imageObjects"].as_array().unwrap().iter().filter(|o| o["linked"] == true).cloned().collect(); for (o, r) in linked.iter().zip(i["sections"][0]["rows"].as_array().unwrap()) { - let shown = format!("{} × {} px — {}", o["width"], o["height"], o["file"].as_str().unwrap()); + let shown = format!("PNG; {} × {} px; 72 ppi — {}", o["width"], o["height"], o["file"].as_str().unwrap()); assert_eq!((&o["name"], shown.as_str()), (&r[0], r[1].as_str().unwrap())); } assert_eq!(linked.len(), 2); diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs new file mode 100644 index 0000000000..c2e80f983a --- /dev/null +++ b/crates/engine/src/tests/paintopacity.rs @@ -0,0 +1,485 @@ +//! `opacity` on `paint.setFill` and `paint.setStroke`: the opacity of the fill or stroke item the +//! paint goes to, and `fillOpacity` and `strokeOpacity` on `paint.proxies`. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::tooling::ViewInfo; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 50})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn text(s: &mut Session) -> NodeId { + let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn fill_opacity(s: &Session, id: NodeId) -> f32 { + node(s, id).appearance.fill().unwrap().opacity +} + +fn undo_labels(s: &Session) -> Vec { + s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn proxies(s: &mut Session) -> Value { + s.execute("paint.proxies", &json!({})).unwrap() +} + +/// `paint.setFill {opacity}` alone sets the opacity of the selected object's top fill item, as one +/// undo step named Opacity, and leaves its paint, its stroke and the object's own opacity as they +/// were; `paint.setStroke {opacity}` does the same for the top stroke, and `paint.proxies` answers +/// both. +#[test] +fn opacity_alone_sets_the_fill_or_stroke_item() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let before = node(&s, id); + let undo = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + let n = node(&s, id); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + assert_eq!(n.appearance.fill_paint(), before.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().unwrap().opacity, 1.0); + assert_eq!(n.opacity, 1.0); + let labels = undo_labels(&s); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + assert_eq!(proxies(&mut s)["strokeOpacity"], 100.0); + // The defaults for new art keep their paint. + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE)); + + s.execute("paint.setStroke", &json!({"opacity": 25})).unwrap(); + assert!((node(&s, id).appearance.stroke().unwrap().opacity - 0.25).abs() < 1e-6); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + assert_eq!(proxies(&mut s)["strokeOpacity"], 25.0); +} + +/// A selected group stands for its contents: every member's fill takes the opacity, as one undo step. +#[test] +fn a_group_sets_every_member_in_one_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let undo = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"opacity": 60})).unwrap(); + assert!((fill_opacity(&s, a) - 0.6).abs() < 1e-6 && (fill_opacity(&s, b) - 0.6).abs() < 1e-6); + assert_eq!(undo_labels(&s).len(), undo + 1); +} + +/// A group with a fill of its own: without an active Appearance row, `paint.proxies` answers the +/// opacity of the contents' fills, which `paint.setFill {opacity}` sets, not the group's own fill. +#[test] +fn a_group_with_its_own_fill_answers_for_its_contents() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let g = s.doc().unwrap().selection.subjects()[0]; + select(&mut s, &[g]); + s.execute("appearance.addFill", &json!({})).unwrap(); + let own = node(&s, g).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("paint.setFill", &json!({"item": own, "opacity": 30})).unwrap(); + select(&mut s, &[g]); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0); + s.execute("paint.setFill", &json!({"opacity": 60})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 60.0); + assert!((node(&s, g).appearance.items[own].opacity() - 0.3).abs() < 1e-6, "the group's own fill keeps its opacity"); +} + +/// A targeted layer without an active Appearance row: `paint.proxies` answers the opacity of the +/// layer's editable art, which `paint.setFill {opacity}` sets, not that of a locked object before it. +#[test] +fn a_targeted_layer_answers_for_its_editable_art() { + let mut s = session(); + let (locked, open) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + s.execute("paint.setFill", &json!({"ids": [locked.0], "opacity": 20})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [open.0], "opacity": 80})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 80.0); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert!((fill_opacity(&s, open) - 0.4).abs() < 1e-6); + assert!((fill_opacity(&s, locked) - 0.2).abs() < 1e-6, "the locked object keeps its opacity"); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); +} + +/// With the Appearance panel's lower fill row active, that row takes the opacity and the top fill +/// keeps its own. +#[test] +fn the_active_appearance_row_takes_the_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + s.execute("appearance.addFill", &json!({})).unwrap(); // [Fill, Stroke, Fill] + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.execute("paint.setFill", &json!({"opacity": 30})).unwrap(); + let ap = node(&s, id).appearance; + assert!((ap.items[0].opacity() - 0.3).abs() < 1e-6); + assert_eq!(ap.items[2].opacity(), 1.0); + assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); +} + +/// With a path of a compound path selected and its fill row active, the command edits the compound +/// path's fill, and `paint.proxies` answers that fill's opacity, not the member's own. +#[test] +fn an_active_row_of_a_compound_member_answers_for_its_compound() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "opacity": 40})).unwrap(); + // A fill row of the member's own, at 100%. + s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(fill_opacity(&s, a), 1.0); + select(&mut s, &[a]); + let row = node(&s, a).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); + assert!((fill_opacity(&s, compound) - 0.7).abs() < 1e-6); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0); + + // A fill row of the member's at an index that is not a fill in the compound path: the command + // edits the compound path's top fill, which the proxy answers. + s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap(); + let (member, outer) = (node(&s, a).appearance, node(&s, compound).appearance); + let row = (0..member.items.len()).find(|i| member.items[*i].is_fill() && !outer.items.get(*i).is_some_and(|it| it.is_fill())).unwrap(); + select(&mut s, &[a]); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0); + s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert!((fill_opacity(&s, compound) - 0.2).abs() < 1e-6); + assert_eq!(proxies(&mut s)["fillOpacity"], 20.0); +} + +/// A color and an opacity change together in one undo step, and the same call again records no +/// step. +#[test] +fn color_and_opacity_are_one_step_and_a_repeat_records_none() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let undo = undo_labels(&s).len(); + let p = json!({"color": "#ff0000", "opacity": 50}); + s.execute("paint.setFill", &p).unwrap(); + assert_eq!(node(&s, id).appearance.fill_paint(), Paint::solid(Color::rgb8(255, 0, 0))); + assert!((fill_opacity(&s, id) - 0.5).abs() < 1e-6); + assert_eq!(undo_labels(&s).len(), undo + 1); + assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Fill Color")); + s.execute("paint.setFill", &p).unwrap(); + s.execute("paint.setFill", &json!({"opacity": 50})).unwrap(); + assert_eq!(undo_labels(&s).len(), undo + 1); +} + +/// Bad values, nothing selected, and characters selected with the Type tool answer errors and leave +/// the document and the defaults for new art as they were. +#[test] +fn errors_leave_the_document_and_defaults_alone() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + for bad in [json!(101), json!(-1), json!("50"), json!(true)] { + let e = s.execute("paint.setFill", &json!({"opacity": bad})).unwrap_err(); + assert!(e.to_string().contains("`opacity` must be a number from 0 to 100"), "{bad}: {e}"); + } + let e = s.execute("paint.setFill", &json!({})).unwrap_err(); + assert!(e.to_string().contains("give color, none, swatch, gradient or opacity"), "{e}"); + // An opacity alone places no gradient across the selection. + let doc = s.doc().unwrap().doc.clone(); + for (span, says) in [(json!("selection"), "give `gradient`"), (json!("all"), "span must be \"object\" or \"selection\"")] { + let e = s.execute("paint.setFill", &json!({"opacity": 40, "span": span})).unwrap_err(); + assert!(e.to_string().contains(says), "{span}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + s.execute("paint.setFill", &json!({"opacity": 40, "span": "object"})).unwrap(); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + s.execute("select.none", &json!({})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("select objects or give ids"), "{p}: {e}"); + } + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE)); + assert_eq!(*s.doc().unwrap().doc, *doc); + + // Characters selected with the Type tool. + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap(); + } + s.tool_text("Sample", v).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 3})); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{p}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// Select characters of `t` with the Type tool. +fn select_characters(s: &mut Session, t: NodeId) { + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 2})); +} + +/// While the Type tool has characters selected, `paint.proxies` answers no opacity even when the +/// type object has a fill row of its own that the Appearance panel has active, since +/// `paint.setFill {opacity}` would give the opacity to the characters. +#[test] +fn with_characters_selected_the_proxy_answers_no_opacity() { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + s.execute("appearance.addFill", &json!({})).unwrap(); + let row = node(&s, t).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the type object's own fill row"); + select_characters(&mut s, t); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// While the Type tool has characters selected, an object named by `id` takes the opacity and the +/// paint, and the characters keep theirs. +#[test] +fn with_characters_selected_an_id_takes_the_opacity() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let t = text(&mut s); + select(&mut s, &[t]); + select_characters(&mut s, t); + let before = node(&s, t); + s.execute("paint.setFill", &json!({"id": r.0, "opacity": 40})).unwrap(); + assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); + s.execute("paint.setStroke", &json!({"id": r.0, "color": "#ff0000", "opacity": 30})).unwrap(); + let stroke = node(&s, r).appearance.stroke().unwrap().clone(); + assert!((stroke.opacity - 0.3).abs() < 1e-6); + assert_eq!(stroke.paint, Paint::solid(Color::rgb8(255, 0, 0))); + assert_eq!(node(&s, t), before, "the characters keep their paint"); +} + +/// A type object whose characters take the paint is left alone beside a rectangle that takes the +/// opacity, with no error; alone, it answers the characters error. +#[test] +fn type_beside_other_art_is_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let t = text(&mut s); + let runs = |s: &Session| match &node(s, t).kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + }; + let before = (node(&s, t), runs(&s)); + select(&mut s, &[r, t]); + let out = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert_eq!(out["objects"], 1, "only the rectangle took the opacity"); + assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); + assert_eq!((node(&s, t), runs(&s)), before); + select(&mut s, &[t]); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!((node(&s, t), runs(&s)), before); +} + +/// A color with an opacity on type alone answers the characters error and takes the color back too. +#[test] +fn type_alone_takes_back_the_paint_given_with_an_opacity() { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + let doc = s.doc().unwrap().doc.clone(); + let undo = undo_labels(&s).len(); + let e = s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(undo_labels(&s).len(), undo); + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE), "the defaults keep their paint"); +} + +/// An opacity that no target takes (the only selected object has no fill item) is an error, with or +/// without a paint, and leaves the document as it was; `paint.proxies` answers null for it, and +/// beside an object with a fill item it answers that object's opacity. +#[test] +fn an_opacity_no_target_takes_is_an_error() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + assert!(node(&s, a).appearance.fill().is_none()); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let doc = s.doc().unwrap().doc.clone(); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}"); + assert_eq!(*s.doc().unwrap().doc, *doc); + // A paint given with the opacity creates the fill, which takes the opacity. + s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap(); + assert!((fill_opacity(&s, a) - 0.4).abs() < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *doc); + + select(&mut s, &[b]); + s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); + select(&mut s, &[a, b]); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0, "the first selected object with a fill item answers"); + let out = s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert_eq!(out["objects"], 1, "the object without a fill item is not counted"); + assert!((fill_opacity(&s, b) - 0.2).abs() < 1e-6); + assert!(node(&s, a).appearance.fill().is_none()); +} + +/// An object selected in a dynamic symbol instance has no opacity of its own: `opacity` is an error +/// that leaves the document alone, and `paint.proxies` answers null. +#[test] +fn an_object_in_a_symbol_instance_refuses_an_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone(); + s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("an object selected in a symbol instance has no fill or stroke opacity of its own"), "{p}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows +/// it; the object's fill item and the other points stay as they were. +#[test] +fn a_picked_mesh_point_takes_the_fill_opacity() { + let mut s = session(); + let m = rect(&mut s, 10.0); + select(&mut s, &[m]); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + select(&mut s, &[m]); + let v = ViewInfo::default(); + let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") }; + let q = g.points[4].p; + s.select_tool("mesh", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y), v).unwrap(); + } + s.execute("paint.setFill", &json!({"opacity": 30})).unwrap(); + let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") }; + let o: Vec = g.points.iter().map(|p| p.opacity).collect(); + assert!((o[4] - 0.3).abs() < 1e-6, "{o:?}"); + assert!(o.iter().enumerate().all(|(i, a)| i == 4 || *a == 1.0), "{o:?}"); + assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); +} + +/// A null `id` or `ids` names no object, so while the Type tool has characters selected the paint +/// goes to those characters only, and the rest of the type keeps its paint. +#[test] +fn a_null_id_leaves_the_paint_to_the_selected_characters() { + for key in ["id", "ids"] { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 1})); + s.execute("paint.setFill", &json!({"color": "#ff0000", key: null})).unwrap(); + let NodeKind::Text(tx) = &node(&s, t).kind else { panic!("not type") }; + let fills: Vec = tx.runs.iter().map(|r| r.style.fill.clone()).collect(); + assert_eq!(fills.first(), Some(&Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}"); + assert!(fills.len() > 1 && fills[1..].iter().all(|f| *f != Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}"); + let e = s.execute("paint.setFill", &json!({"opacity": 40, key: null})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{key}: {e}"); + } +} + +/// A selected Live Paint group stands for its faces in a fill opacity and for its edges in a stroke +/// opacity, and `paint.proxies` answers from those same parts. +#[test] +fn a_live_paint_group_answers_from_the_parts_it_sets() { + let mut s = session(); + let id = rect(&mut s, 10.0); + s.execute("livePaint.make", &json!({"ids": [id.0]})).unwrap(); + let g = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[g]); + s.execute("paint.setStroke", &json!({"opacity": 30})).unwrap(); + assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0); +} + +/// While the Live Paint Bucket is the active tool, a fill or stroke chosen goes to the bucket, so +/// `paint.proxies` answers no opacity for the selection and an opacity is an error that leaves the +/// document as it was. +#[test] +fn the_live_paint_bucket_answers_no_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); + let doc = s.doc().unwrap().doc.clone(); + assert!(s.execute("paint.setFill", &json!({"opacity": 40})).is_err()); + assert_eq!(*s.doc().unwrap().doc, *doc); +} + +/// The Eyedropper armed to sample into the Live Paint Bucket's gradient works for the bucket, so +/// the proxies answer no opacity for the selection then too, as they show no paint of its own. +#[test] +fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's"); + s.set_tool_option("stop", &json!("livePaintBucket")); + assert!(s.bucket_paints()); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); +} + +/// A `swatch` that is no name does not turn a request into an opacity alone: it is an error and +/// leaves the document as it was. +#[test] +fn a_swatch_that_is_no_name_is_refused_with_an_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let doc = s.doc().unwrap().doc.clone(); + for cmd in ["paint.setFill", "paint.setStroke"] { + for swatch in [json!(5), json!(true), json!(["a"]), json!({})] { + assert!(s.execute(cmd, &json!({"swatch": swatch, "opacity": 40})).is_err(), "{cmd} {swatch}"); + } + // A null swatch names none, so the opacity goes alone. + s.execute(cmd, &json!({"swatch": null, "opacity": 40})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(*s.doc().unwrap().doc, *doc); +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1c0539a2f9..0e183e0a6e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4798,6 +4798,82 @@ fn plugin_commands_are_registered_run_and_removed() { assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs"); } +/// At API level 2 a command's `menu` lists it in that menu with its plug-in's name after its +/// label, and `plugin.list` gives its `menu` with `after` escaped. A command whose label reads like +/// a built-in command of that menu, or like a command a plug-in with a lower id places there, +/// stays in its plug-in's submenu, and `plugin.list` marks it `placed: false`. Replaced by a module +/// whose command has no `menu`, a command is back in its submenu. +#[test] +fn placed_plugin_commands_are_listed_in_their_menu() { + let mut s = session(); + let placing = |id: &str, name: &str, commands: &str| { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + tpl::returning(&manifest, r#"{"objects":[]}"#) + }; + let (ant, bee, cat) = ("test.engine.place.ant", "test.engine.place.bee", "test.engine.place.cat"); + let low = |id: &str| crate::cmd::plugin::command_id(id, "low"); + let menu_of = |s: &Session, command: &str| listed(s, command).map(|c| c.menu.iter().map(|m| m.to_string()).collect::>()); + let in_select = json!([{"id": "low", "label": "Low Area", "menu": {"path": ["Select"], "after": "\u{202E}Inverse"}}]).to_string(); + let in_select = in_select.as_str(); + + let info = install_wat(&mut s, &placing(ant, "Tidy", in_select)); + let menu = &info["commands"][0]["menu"]; + assert_eq!(menu["path"], json!(["Select"])); + assert!(menu["after"].as_str().is_some_and(|a| a.ends_with("Inverse") && !a.contains('\u{202E}')), "escaped: {menu}"); + assert!(menu.get("placed").is_none(), "{menu}"); + let c = listed(&s, &low(ant)).expect("listed"); + assert_eq!((c.label, menu_of(&s, &low(ant))), ("Low Area (Tidy)", Some(vec!["Select".to_string()]))); + + // Another plug-in of the same name placing the same label at the same spot stays in its submenu. + let info = install_wat(&mut s, &placing(bee, "Tidy", in_select)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert_eq!(listed(&s, &low(bee)).map(|c| c.label), Some("Low Area")); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Select".to_string()])); + + // `Paste (in Place)` reads like Edit's Paste in Place; Keep is placed. + let edit = r#"[{"id":"paste","label":"Paste","menu":{"path":["Edit"]}},{"id":"keep","label":"Keep","menu":{"path":["Edit"]}}]"#; + let info = install_wat(&mut s, &placing(cat, "in Place", edit)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert!(info["commands"][1]["menu"].get("placed").is_none()); + let paste = crate::cmd::plugin::command_id(cat, "paste"); + assert_eq!(menu_of(&s, &paste), Some(vec!["Object".into(), "Plug-ins".into(), "in Place".into()])); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(cat, "keep")), Some(vec!["Edit".to_string()])); + // `Stop Global (Edit)` reads like the other label of Select's Start Global Edit. + let dog = "test.engine.place.dog"; + let info = install_wat(&mut s, &placing(dog, "Edit", r#"[{"id":"stop","label":"Stop Global","menu":{"path":["Select"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": dog})); + // Object's Show All has one label, so `Hide (All)` is placed beside it. + let all = "test.engine.place.all"; + let info = install_wat(&mut s, &placing(all, "All", r#"[{"id":"hide","label":"Hide","menu":{"path":["Object"]}}]"#)); + assert!(info["commands"][0]["menu"].get("placed").is_none(), "{}", info["commands"][0]); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(all, "hide")), Some(vec!["Object".to_string()])); + run(&mut s, "plugin.remove", json!({"id": all})); + // `Hide (Edges)` reads like the desktop app's View › Hide Edges, with or without the desktop app. + let edges = "test.engine.place.edges"; + let info = install_wat(&mut s, &placing(edges, "Edges", r#"[{"id":"hide","label":"Hide","menu":{"path":["View"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": edges})); + // Inspecting a plug-in that is not installed reports what installing it gives: of two commands + // with one label at one spot, the second stays in its submenu. + let twice = r#"[{"id":"a","label":"Low","menu":{"path":["Select"]}},{"id":"b","label":"Low","menu":{"path":["Select"]}}]"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(placing("test.engine.place.eel", "Eel", twice)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert!(inspected["commands"][0]["menu"].get("placed").is_none(), "{inspected}"); + assert_eq!(inspected["commands"][1]["menu"]["placed"], json!(false), "{inspected}"); + + // Replaced by a module whose command has no `menu`, Ant's command is back in its submenu and + // Bee's takes the spot. + install_wat(&mut s, &placing(ant, "Tidy", r#"[{"id":"low","label":"Low Area"}]"#)); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Select".to_string()])); + for id in [ant, bee, cat] { + run(&mut s, "plugin.remove", json!({"id": id})); + } + assert!(listed(&s, &low(bee)).is_none()); +} + /// A command run is journaled like any other, so an action records it with its parameters and /// plays it back. #[test] diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 375f648ac8..d9945fa723 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -550,6 +550,18 @@ fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { key(s, ToolKey::AltTap); } +/// Whether the tool shows only the path's points and its length handles (a handle and the line to +/// it from the path's end): no hover preview, label or Smart Guide. +fn only_points(s: &mut Session, v: ViewInfo) -> bool { + let o = s.overlays(v); + let handles: Vec = o.iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect(); + o.iter().all(|o| match o { + Overlay::CurvePoint { .. } | Overlay::Handle { .. } => true, + Overlay::Line { b, .. } => handles.contains(b), + _ => false, + }) +} + /// The last point of the path the tool drew (any other path is a two-point line). fn drawn_end(s: &Session) -> Point { let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); @@ -710,9 +722,8 @@ fn a_hover_shows_nothing_after_smart_guides_change() { s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); let off_anchor = label(&mut s, on).unwrap() - at; assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on)); - assert!(only_points(&mut s, off), "only the path's points show"); + assert!(only_points(&mut s, off), "only the path's points and length handles show"); // A click before the pointer moves does not bring the stale hover back. press_in(&mut s, &[(400.0, 300.0)], off); assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); @@ -746,7 +757,6 @@ fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { s.execute("select.set", &json!({"ids": []})).unwrap(); continuous_arc_after_a_line(&mut s, on); s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on), "the anchor's guide shows"); assert!(only_points(&mut s, off)); let steps = undo_steps(&s); @@ -891,6 +901,467 @@ fn path_quick_pen_refuses_bad_params() { assert_eq!(paths(&s).len(), before.len()); } +/// The handle beyond the end of the path being drawn makes its last line longer, as one undo step, +/// and the next click goes on from the new end. +#[test] +fn dragging_the_end_handle_lengthens_the_last_line() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + // The handle stands 20 screen points beyond the end, along the line. + press(&mut s, &[(220.0, 100.0), (250.0, 130.0), (280.0, 140.0)]); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, 260.0, 200.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0), pt(260.0, 200.0)], "the drawing went on"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(200.0, 100.0)); +} + +/// Dragged by its end handle, the last sharp-corner arc goes on around its circle and stays the +/// last piece, so C still flips it and `[` `]` still change its size. +#[test] +fn a_dragged_last_arc_still_flips() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + // The half circle over (200, 300) ends heading down, so its end handle is 20 points below. The + // handle turned a quarter around the center, to (180, 400), takes the end to (200, 400). + press(&mut s, &[(300.0, 320.0), (260.0, 400.0), (180.0, 400.0)]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6, "three quarters around: {:?}", sp.anchors.last()); + assert_eq!(sp.anchors.len(), 4); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert!(flipped.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 2); + // `]` makes the dragged arc 15° larger: it keeps its ends and gains its own undo step. + key(&mut s, ToolKey::BracketRight); + let larger = only_path(&s); + assert_ne!(larger, flipped); + assert!(larger.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 3); +} + +/// Dragged back past its start, the last sharp-corner arc stops at 1°. +#[test] +fn a_dragged_last_arc_keeps_at_least_one_degree() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + // The half circle about (200, 300) runs over the top from (100, 300) to (300, 300); its end + // handle is 20 points below the end. The pointer goes back around the circle from there, past + // the start of the arc. + let (c, r) = (pt(200.0, 300.0), (100.0f64 * 100.0 + 20.0 * 20.0).sqrt()); + let a0 = 20.0f64.atan2(100.0); + let mut pts = vec![(300.0, 320.0)]; + for d in [45.0f64, 90.0, 135.0, 175.0, 185.0] { + let a = a0 - d.to_radians(); + pts.push((c.x + r * a.cos(), c.y + r * a.sin())); + } + press(&mut s, &pts); + let sp = only_path(&s); + let one = 181f64.to_radians(); + let end = pt(200.0 + 100.0 * one.cos(), 300.0 + 100.0 * one.sin()); + assert!(sp.anchors.last().unwrap().p.distance(end) < 1e-6, "{:?}", sp.anchors.last()); + assert_eq!(sp.anchors.first().unwrap().p, pt(100.0, 300.0)); +} + +/// When the last arc goes on around the circle of the arc before it, its end handle still changes +/// the last arc alone, which C then still flips. +#[test] +fn the_end_handle_changes_the_last_arc_on_a_shared_circle() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "turn", "value": 90})).unwrap(); + // A quarter more around the circle about (200, 300), ending heading left. + click(&mut s, 200.0, 400.0); + let r = 100.0 * std::f64::consts::FRAC_1_SQRT_2; + let to = pt(200.0 - r, 300.0 + r); + // The handle at (180, 400) turned 45° more around the center takes the end there with it. + let (sin, cos) = std::f64::consts::FRAC_PI_4.sin_cos(); + let (hx, hy) = (-20.0, 100.0); + let pointer = (200.0 + hx * cos - hy * sin, 300.0 + hx * sin + hy * cos); + press(&mut s, &[(180.0, 400.0), (170.0, 400.0), pointer]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(to) < 1e-6, "135° from (300, 300): {:?}", sp.anchors.last()); + assert!(sp.anchors.get(2).unwrap().p.distance(pt(300.0, 300.0)) < 1e-9, "the first arc stays"); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); +} + +/// Once another path is selected while one was being drawn, the selected path shows its handles. +#[test] +fn another_selected_path_shows_its_handles() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let r = s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 400, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + let handle = + |s: &mut Session| s.overlays(view()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { p, .. } if *p == pt(420.0, 300.0))); + assert!(handle(&mut s)); + assert_eq!(s.cursor(pt(420.0, 300.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); +} + +/// A selected path that is not being drawn shows its handles: the one before its start makes the +/// first arc shorter around its circle. Escape during a drag takes the drag back. +#[test] +fn the_start_handle_of_a_selected_path_shortens_its_arc() { + let mut s = session(); + let r = s + .execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100, "action": "sharpArc"}, {"x": 300, "y": 100}]})) + .unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + quick_pen(&mut s); + let undo = undo_steps(&s); + let before = only_path(&s); + // The half circle leaves (100, 100) heading up, so its start handle is 20 points below. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 70.0), v).unwrap(); + assert_ne!(only_path(&s), before, "previewed"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 70.0), v).unwrap(); + assert_eq!(only_path(&s), before, "taken back"); + assert_eq!(undo_steps(&s), undo); + // The handle turned a quarter around the center, to (130, 50), takes the start to the top of + // the circle: the arc is a quarter from there to (200, 100). + press(&mut s, &[(100.0, 120.0), (130.0, 50.0)]); + let sp = only_path(&s); + assert!(sp.anchors.first().unwrap().p.distance(pt(150.0, 50.0)) < 1e-6, "{:?}", sp.anchors.first()); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// A click on a length handle that does not drag is an ordinary click: while drawing it adds a +/// point there, and with no path being drawn it starts a new path. +#[test] +fn a_click_on_a_handle_adds_a_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + click(&mut s, 220.0, 100.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(220.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + // After Escape the path stays selected with its handles; a click on one starts a new path. + key(&mut s, ToolKey::Escape); + assert_eq!(s.cursor(pt(240.0, 100.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); + click(&mut s, 240.0, 100.0); + assert_eq!(paths(&s).len(), 2); +} + +/// During a length drag the tool shows the handle and no preview of a next piece to where the +/// pointer was before the press. +#[test] +fn a_length_drag_shows_no_next_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + let o = s.overlays(v); + assert!(o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { .. }))); + assert!(!o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. } | vectorcraft_tools::Overlay::Measure { .. })), "{o:?}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); +} + +/// A press on a length handle clears the Smart Guides of the hover before it, so none show during +/// the drag. +#[test] +fn a_length_drag_shows_no_smart_guide() { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 220, "y1": 100, "x2": 220, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let on = ViewInfo { smart_guides: true, ..Default::default() }; + // The end handle stands on the other line's anchor, so the hover there shows its guide. + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), on).unwrap(); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), on).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), on).unwrap(); + assert!(only_points(&mut s, on), "no guide during the drag: {:?}", s.overlays(on)); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), on).unwrap(); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert_eq!(drawn.1.subpaths[0].anchors.last().unwrap().p, pt(260.0, 100.0)); +} + +/// A length drag that would take the path past the canvas leaves it where the drag last put it, +/// and the drawing goes on from there. +#[test] +fn a_length_drag_stays_on_the_canvas() { + let mut s = session(); + quick_pen(&mut s); + let x = vectorcraft_doc::MAX_COORD - 1000.0; + click(&mut s, x, 100.0); + click(&mut s, x + 500.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at x + 520; a drag to x + 2000 would put the end at x + 1980, past the canvas. + press(&mut s, &[(x + 520.0, 100.0), (x + 2000.0, 100.0)]); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + press(&mut s, &[(x + 520.0, 100.0), (x + 820.0, 100.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 800.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, x + 800.0, 200.0); + assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); +} + +/// A length drag across a line, or out along it and back, leaves its length as it was: it changes +/// nothing and records no undo step, on the path being drawn and on a selected path. +#[test] +fn a_length_drag_that_keeps_the_length_records_no_undo_step() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at (220, 100); the first drag goes straight down from it, the second out + // along the line and back. + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } + key(&mut s, ToolKey::Escape); + let undo = undo_steps(&s); + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } +} + +/// The paths of a selected compound path show length handles, also after a drag selected the +/// compound again. +#[test] +fn a_compound_path_shows_the_length_handles_of_its_paths() { + let mut s = session(); + let a = s.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100}]})).unwrap(); + let b = s.execute("path.quickPen", &json!({"start": [100, 300], "pieces": [{"x": 200, "y": 300}]})).unwrap(); + s.execute("select.set", &json!({"ids": [a["id"], b["id"]]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + quick_pen(&mut s); + press(&mut s, &[(220.0, 100.0), (250.0, 100.0), (280.0, 100.0)]); + press(&mut s, &[(220.0, 300.0), (250.0, 300.0), (270.0, 300.0)]); + let mut ends: Vec = paths(&s).iter().filter_map(|(_, pd)| pd.subpaths[0].anchors.last().map(|a| a.p)).collect(); + ends.sort_by(|p, q| p.y.total_cmp(&q.y)); + assert_eq!(ends, [pt(260.0, 100.0), pt(250.0, 300.0)]); +} + +/// An edit made outside the tool during a length press ends the press: a later drag does not +/// preview from the path as the press found it, and so does not undo the edit. +#[test] +fn an_outside_edit_during_a_length_press_is_kept() { + // The edit comes before the first drag event, or after the drag began. + for began in [false, true] { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + if began { + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + } + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "began: {began}"); + } + // Escape after the edit takes the drag back without taking the edit back. + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "escape"); +} + +/// C and `[` `]` wait for a length drag to end: they neither add an undo step of their own nor +/// change the arc the drag is changing. +#[test] +fn piece_keys_do_nothing_during_a_length_drag() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 320.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 400.0), v).unwrap(); + let during = only_path(&s); + for k in [ToolKey::Letter('c'), ToolKey::BracketRight, ToolKey::BracketLeft] { + assert!(s.tool_claims_key(k, view()), "{k:?} stays with the tool"); + key(&mut s, k); + assert_eq!(only_path(&s), during, "{k:?}"); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 400.0), v).unwrap(); + assert_eq!(undo_steps(&s), undo + 1); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); +} + +/// Choosing Quick Pen again during a length drag leaves the drawing alone: the drag goes on, ends +/// where the pointer is let go, and the next click goes on drawing the same path. +#[test] +fn choosing_the_tool_again_during_a_length_drag_keeps_the_drawing() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 130.0), v).unwrap(); + quick_pen(&mut s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + click(&mut s, 260.0, 200.0); + assert_eq!(paths(&s).len(), 1, "the drawing went on"); + assert_eq!(only_path(&s).anchors.len(), 3); +} + +/// A length drag ends where the pointer is let go, also when no drag event came after the press. +#[test] +fn a_length_drag_ends_at_the_release_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + // A press let go away from the handle without a drag event drags too. + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(300.0, 100.0)); + assert_eq!(only_path(&s).anchors.len(), 2); + assert_eq!(undo_steps(&s), undo + 2); +} + +/// `path.quickPenLength` refuses a result past the canvas, not only one past the input limit. +#[test] +fn path_quick_pen_length_stays_on_the_canvas() { + let mut s = session(); + let x = vectorcraft_doc::MAX_COORD - 500_000.0; + let r = s.execute("path.quickPen", &json!({"start": [x, 0], "pieces": [{"x": x + 10.0, "y": 0}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let before = only_path(&s); + let undo = undo_steps(&s); + let e = s.execute("path.quickPenLength", &json!({"id": id, "length": 1_000_000})).unwrap_err().to_string(); + assert!(e.contains("would exceed the canvas"), "{e}"); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + s.execute("path.quickPenLength", &json!({"id": id, "length": 400_000})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 400_000.0, 0.0)); +} + +/// Dragged by the start handle while the path is being drawn, the first line changes and the last +/// sharp-corner arc stays the last piece, so C still flips it. +#[test] +fn the_start_handle_keeps_the_last_arc_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 300.0); + click(&mut s, 200.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 400.0, 300.0); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + let undo = undo_steps(&s); + // The line leaves (100, 300) heading left, seen from the start, so its handle is 20 points left. + press(&mut s, &[(80.0, 300.0), (60.0, 300.0), (50.0, 300.0)]); + let sp = only_path(&s); + assert_eq!(sp.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view()), "the last arc is still a piece"); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert_eq!(flipped.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert!(flipped.anchors.last().unwrap().p.distance(pt(400.0, 300.0)) < 1e-9); +} + +/// `path.quickPenLength` sets the length of a line or an arc at either end; the same length +/// changes nothing and records no undo step; bad params are refused. +#[test] +fn path_quick_pen_length_sets_an_end() { + let mut s = session(); + let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 200, "y": 0, "action": "sharpArc"}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let r = s.execute("path.quickPenLength", &json!({"id": id, "end": "start", "length": 40})).unwrap(); + assert_eq!((r["kind"].as_str(), r["length"].as_f64()), (Some("line"), Some(40.0))); + assert_eq!(only_path(&s).anchors.first().unwrap().p, pt(60.0, 0.0)); + let undo = undo_steps(&s); + let r = s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 50.0})).unwrap(); + assert_eq!(r["kind"], "arc"); + assert_eq!(undo_steps(&s), undo, "unchanged"); + s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 25.0})).unwrap(); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + assert_eq!(undo_steps(&s), undo + 1); + let before = paths(&s); + let bad: [Value; 7] = [ + json!({"length": 10}), + json!({"id": id}), + json!({"id": id, "length": "10"}), + json!({"id": id, "length": 0}), + json!({"id": id, "length": 1e7, "end": "start"}), + json!({"id": id, "length": 10, "end": "middle"}), + json!({"id": id, "length": 10, "subpath": 1}), + ]; + for p in bad { + assert!(s.execute("path.quickPenLength", &p).is_err(), "{p}"); + } + let curve = s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap(); + s.execute("path.convertAnchor", &json!({"id": curve["id"], "anchor": 1, "to": "smooth", "x": 150, "y": 360})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": curve["id"], "length": 10})).is_err(), "not a line or an arc"); + s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": id, "length": 10})).is_err(), "closed"); + assert_eq!(paths(&s).len(), before.len() + 1); +} + /// With `id` and `keep`, the points after the first `keep` are replaced by the pieces. #[test] fn path_quick_pen_replaces_the_points_after_keep() { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 5ebebb783b..e5d854850d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -653,7 +653,7 @@ fn a_grants_change_without_its_lock_changes_nothing() { } /// Reading and changing the grants file wait for a lock another handle holds only for a bounded -/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. #[test] fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { @@ -668,7 +668,8 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let waits = std::rc::Rc::new(std::cell::Cell::new(0)); let counted = waits.clone(); WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); - assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + let listed = stored_grants(&data); + assert_eq!(listed.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut), "grants are not listed without the lock"); assert_eq!(waits.get(), LOCK_TRIES - 1); waits.set(0); let refused = revoke_grants(&data, None, None); @@ -1319,6 +1320,55 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { } } +/// `script.grants` fails on a grants file that is there but cannot be read (another version, not +/// JSON, no list of grants, over the size limit, not a file, or on Unix a link to a missing file), +/// lists none when it is missing, and +/// lists the well-formed grants of one that holds a grant that is not. +#[test] +fn script_grants_fails_on_a_grants_file_that_cannot_be_read() { + let mut big = b"{\"version\": 1, \"grants\": []}".to_vec(); + big.resize((4 << 20) + 1, b' '); + let cases = [ + ("list-newer", br#"{"version": 2, "grants": []}"#.to_vec()), + ("list-broken", b"{ not json".to_vec()), + ("list-nolist", br#"{"version": 1, "grants": {}}"#.to_vec()), + ("list-big", big), + ]; + for (name, held) in cases { + let base = folder(name); + write(&base.join("settings/Script Grants.json"), &held); + let mut s = with_data(&base); + let e = s.execute("script.grants", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the script file permissions could not be read"), "{name}: {e}"); + let _ = std::fs::remove_dir_all(base); + } + let base = folder("list-folder"); + std::fs::create_dir_all(base.join("settings/Script Grants.json")).unwrap(); + let mut s = with_data(&base); + assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place"); + let _ = std::fs::remove_dir_all(base); + #[cfg(unix)] + { + let base = folder("list-dangling"); + std::fs::create_dir_all(base.join("settings")).unwrap(); + std::os::unix::fs::symlink(base.join("gone.json"), base.join("settings/Script Grants.json")).unwrap(); + let mut s = with_data(&base); + assert!(s.execute("script.grants", &json!({})).is_err(), "a link to a missing file in the grants file's place"); + let _ = std::fs::remove_dir_all(base); + } + let base = folder("list-missing"); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none"); + let _ = std::fs::remove_dir_all(base); + let base = folder("list-mixed"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant, {"script": "x"}]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` of a file over 8 MiB is refused, as opening one is. #[test] fn script_file_copy_is_held_to_the_file_limit() { diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 5d94eecc69..f72beb71c2 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1313,6 +1313,811 @@ fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() { assert!(doc(&s).swatch("Ink 2").is_none(), "{r}"); } +/// A tint or gradient of a numbered library name ("Ink 2") that a library pattern's art brings +/// keeps that name when the document gives the art's color "Ink" another color, so adding the +/// library's "Ink 2" next finds it. +#[test] +fn a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name() { + let tint = json!({"name": "Ink 2", "swatch": "Ink", "tint": 50}); + let gradient = json!({"name": "Ink 2", "gradient": {"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}}); + for numbered in [tint, gradient] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", numbered.clone()); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{numbered}: {first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{numbered}: {first} {r}"); + } +} + +/// A library pattern swatch that comes in under a numbered name skips the names the library gives +/// its other swatches: adding the library's "Dots 2" next adds it under its own name. +#[test] +fn a_library_pattern_swatchs_copy_skips_the_librarys_other_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Dots", |d, _| { + let paint = vectorcraft_doc::pattern::pattern_paint("Squares"); + d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false }); + Ok(()) + }) + .unwrap(); + run(&mut s, "swatch.new", json!({"name": "Dots 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Dots", "color": "#ff0000"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots 2"]})); + assert_eq!(r["added"], json!(["Dots 2"]), "{first} {r}"); + assert!(is_global(&s, "Dots 2", "#00ff00"), "{first} {r}"); +} + +/// A library whose spot color "Ink" shares its name with a global color in a color group: a +/// pattern's art painted with both brings both. A library tint of the spot color, picked before +/// the pattern, links to the document's copy of the spot color the art takes, not to the global +/// color the art brings under a numbered name, whether that color has another paint or the same. +/// The library's own spot "Ink 2" is green, so the document's blue "Ink 2" is not that swatch. +#[test] +fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() { + for global_color in ["#ff0000", "#0000ff"] { + a_library_tint_skips_a_namesake_the_pattern_brings(global_color); + } +} + +fn a_library_tint_skips_a_namesake_the_pattern_brings(global_color: &str) { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": global_color, "global": true})); + let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone(); + let red = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]})); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [red]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, red]})); + run(&mut s, "select.set", json!({"ids": [blue, red]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + // The global color becomes "Ink" in a color group, and the pattern's art links to it by that name. + s.edit("Rename", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Crimson").unwrap(); + let mut global = d.swatches.remove(i); + global.name = "Ink".into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Reds".into(), swatches: vec![global] }); + let def = d.pattern_mut("Tiles").unwrap(); + for node in &mut def.art { + for it in &mut std::sync::Arc::make_mut(node).appearance.items { + it.paint_mut().map_links(&mut |_, link, _| { + let red = link.as_deref() == Some("Crimson"); + if red { + *link = Some("Ink".into()); + } + red + }); + } + } + Ok(()) + }) + .unwrap(); + let art_links: Vec> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert_eq!(art_links, [Some("Ink".to_string()), Some("Ink".to_string())]); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Tiles"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{global_color}: {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| w.spot), "{global_color}: {r}"); +} + +/// A color of a numbered library name ("Ink 2") that a pattern's art brings comes in under that +/// name when the document does not use it, not as the document's copy of it ("Ink 2 2"), so +/// adding the library's "Ink 2" next finds it. +#[test] +fn a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{first} {r}"); +} + +/// A pattern that a library pattern's art is painted with ("Inner"), brought under a numbered name +/// because the document has a swatch "Inner", skips the name "Inner 2" that the library gives a +/// color, as does the swatch that comes with it. +#[test] +fn a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Inner", "color": "#ff0000"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + assert!(doc(&s).pattern("Inner 2").is_none(), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}"); + assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}"); +} + +/// A library pattern that was pasted into the document with its art linked to the document's +/// copy of a numbered library color ("Ink 2 2" for "Ink 2") is found when it is added from the +/// library, not added again. +#[test] +fn a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true})); + run(&mut s, "edit.paste", json!({})); + assert!(doc(&s).swatch("Ink 2").is_none(), "the paste reused the copy"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); +} + +/// A library pattern swatch named after its pattern ("Tiles 2") that comes in with a new pattern +/// under a numbered name ("Tiles 2 2"), because the document has another pattern of that name +/// without a swatch, takes the library swatch's name. +#[test] +fn a_new_patterns_swatch_takes_the_library_swatchs_free_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + assert!(doc(&s).pattern("Tiles 2").is_some(), "the document keeps its pattern"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{r}"); + let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Tiles 2"), "{r} {paint:?}"); + // Added again after its swatch is deleted, it reuses the pattern under the same swatch name. + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(again["added"], json!(["Tiles 2"]), "{r} {again}"); + assert_eq!(doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()), paint, "{r} {again}"); +} + +/// A library pattern swatch "Tiles" named after its pattern, added to a document that has another +/// pattern "Tiles" without a swatch, is named after the pattern that comes in ("Tiles 2"), as +/// before numbered names were reserved: only a numbered name is kept for the library swatch. +#[test] +fn a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string(); + assert_ne!(added, "Tiles", "{r}"); + let paint = doc(&s).swatch(&added).map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if *pattern == added), "{r} {paint:?}"); + assert!(doc(&s).swatch("Tiles").is_none(), "{r}"); +} + +/// A library whose process color "Ink 2" shares its name with a global color in a color group +/// that a pattern's art is painted with: the global color comes in numbered, so adding the +/// library's "Ink 2" next adds the process color under its own name. +#[test] +fn a_numbered_name_is_kept_for_the_library_swatch_it_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + group_as(&mut s, "Crimson", "Ink 2"); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}"); +} + +/// A library pattern pasted with Add, whose color came in as "Ink 2" and was then deleted without +/// unlinking the art, is not reused through a new "Ink 2" when the library gives that name another +/// color: adding that color next adds it under its own name. This holds too when the document has +/// a pattern "Ink 2" without a swatch. +#[test] +fn a_pasted_pattern_is_not_reused_by_taking_a_librarys_name() { + for bare in [false, true] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + if bare { + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Ink 2", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"]})); + assert!(doc(&s).pattern("Ink 2").is_some(), "the document keeps its pattern"); + } + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2 ({bare})"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{bare} {first} {r}"); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{bare} {first} {r}"); + } +} + +/// A library pattern painted with two global colors of one paint, "Ink" and "Ink 2", added beside +/// the document's red "Ink" brings them as "Ink 3" and "Ink 2". Adding the pattern again finds it, +/// in either order of the library's colors: "Ink" does not reuse the library's "Ink 2". +#[test] +fn a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names() { + for ink_first in [true, false] { + let mut s = session(); + let names = if ink_first { ["Ink", "Ink 2"] } else { ["Ink 2", "Ink"] }; + for n in names { + run(&mut s, "swatch.new", json!({"name": n, "color": "#0000ff", "global": true})); + } + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 3", "#0000ff"), "{ink_first} {first}"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{ink_first} {first} {r}"); + } +} + +/// A library pattern painted with a blue global "Ink" and a green global "Ink 2", added to a +/// document with a red "Ink" and a blue global "Ink 2": the art's "Ink" is the document's "Ink 2", +/// since that is not the library's "Ink 2", and no third copy comes in. +#[test] +fn a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(doc(&s).swatch("Ink 3").is_none(), "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 2 2", "#00ff00"), "{r}"); +} + +/// A library pattern painted with a blue global "Ink", from a library that also has a blue global +/// "Ink 2" the art does not use, added beside the document's red "Ink" after the library's "Ink 2" +/// came in: the art's "Ink" does not reuse the library's "Ink 2" and comes in as "Ink 3". +#[test] +fn a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 3", "#0000ff"), "{first} {r}"); + let links: Vec> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert_eq!(links, vec![Some("Ink 3".to_string())], "{first} {r}"); +} + +/// A library pattern painted with a blue global "Ink", pasted beside the document's red "Ink" and +/// then left without its color "Ink 2" (deleted without unlinking), is not reused by bringing the +/// library's "Ink" back as "Ink 2" when the library has its own blue "Ink 2": the pattern links to +/// another copy. +#[test] +fn a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string(); + let pattern = match doc(&s).swatch(&added).map(|w| w.paint.clone()) { + Some(Paint::Pattern { pattern, .. }) => pattern, + p => panic!("{r} {p:?}"), + }; + let links: Vec> = doc(&s).pattern(&pattern).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert!(!links.contains(&Some("Ink 2".to_string())), "{r} {links:?}"); +} + +/// A library pattern painted with two alike gradients of its blue global "Ink", "Ramp 2" and then +/// "Ramp", added beside the document's red "Ink": the color comes in as "Ink 2", and both +/// gradients come in under their own names, linked to it, instead of "Ramp" taking "Ramp 2". +#[test] +fn alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let ramp = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}); + run(&mut s, "swatch.new", json!({"name": "Ramp 2", "gradient": ramp})); + run(&mut s, "swatch.new", json!({"name": "Ramp", "gradient": ramp})); + let mut dots = vec![]; + for (i, n) in ["Ramp 2", "Ramp"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + assert!(doc(&s).swatch("Ramp").is_some() && doc(&s).swatch("Ramp 2").is_some(), "{r}"); +} + +/// A library pattern painted with blue globals "Ink" and "Ink 2", pasted twice beside the +/// document's red "Ink" and blue "Ink 2" (with Add, both fills on "Ink 2"; with Merge, one on the +/// red "Ink"), is found again as the copy that keeps its blue, not the merged one. +#[test] +fn a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let links = |s: &Session, p: &str| -> Vec> { + doc(s).pattern(p).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect() + }; + let kept: Vec = doc(&s).patterns.iter().map(|p| p.name.clone()).filter(|p| !links(&s, p).contains(&Some("Ink".into()))).collect(); + assert_eq!((doc(&s).patterns.len(), kept.len()), (2, 1), "one pasted copy keeps the blue color"); + for w in doc(&s).swatches.clone().iter().filter(|w| matches!(w.paint, Paint::Pattern { .. })) { + run(&mut s, "swatch.delete", json!({"names": [w.name]})); + } + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) { + Some(Paint::Pattern { pattern, .. }) => pattern, + p => panic!("{r} {p:?}"), + }; + assert_eq!((doc(&s).patterns.len(), &pattern), (2, &kept[0]), "{r}"); +} + +/// A library whose color "Tiles 2" shares its name with a pattern swatch in a color group: adding +/// the group gives the pattern swatch another name, so adding the color next adds it under its own. +#[test] +fn a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Dots", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true})); + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Dots").unwrap(); + let mut w = d.swatches.remove(i); + w.name = "Tiles 2".into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}"); +} + +/// As above, with the grouped swatch named after its pattern "Tiles 2", which the document holds +/// (pasted there) without a swatch: the reused pattern's swatch leaves the name to the color too. +#[test] +fn a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles 2", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "swatch.new", json!({"name": "Bright", "color": "#00ff00", "global": true})); + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Tiles 2").unwrap(); + let w = d.swatches.remove(i); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + d.swatches.iter_mut().find(|w| w.name == "Bright").unwrap().name = "Tiles 2".into(); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "edit.paste", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + assert!(doc(&s).pattern("Tiles 2").is_some() && doc(&s).swatch("Tiles 2").is_none(), "the pasted pattern stays"); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}"); +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, whose library swatch "Inner 2" +/// places it with an offset, leaves the name to that swatch: adding the library's "Inner 2" next +/// adds it under its own name with its placement. Picked first, "Inner 2" comes in under its own +/// name too. +#[test] +fn a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise() { + for outer_first in [true, false] { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + let offset = Paint::Pattern { pattern: "Inner 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) }; + let lib_paint = offset.clone(); + s.edit("Offset", move |d, _| { + d.swatches.iter_mut().find(|w| w.name == "Inner 2").unwrap().paint = lib_paint; + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let picks = if outer_first { ["Outer", "Inner 2"] } else { ["Inner 2", "Outer"] }; + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[0]]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[1]]})); + assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), Some(offset), "{outer_first} {first} {r}"); + assert_eq!(doc(&s).patterns.len(), 2, "{outer_first} {first} {r}"); + } +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, brought under a numbered name +/// because the document has another pattern "Inner 2" without a swatch, comes with a swatch under +/// the library swatch's free name "Inner 2": adding the library's "Inner 2" next finds it. +#[test] +fn a_nested_patterns_swatch_takes_the_library_swatchs_free_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [own]})); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 14, "height": 14})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]})); + assert!(doc(&s).pattern("Inner 2").is_some(), "the document keeps its pattern"); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + let paint = doc(&s).swatch("Inner 2").map(|w| w.paint.clone()); + assert!( + matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Inner 2" && doc(&s).pattern(pattern).is_some()), + "{first} {paint:?}" + ); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!([]), "{first} {r}"); + assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), paint, "{first} {r}"); + assert_eq!(doc(&s).patterns.len(), 3, "{first} {r}"); +} + +/// A library with a pattern swatch "Tiles 2" and, in a color group, a swatch of the same name that +/// places the same pattern with an offset: adding the group first leaves the name to the +/// ungrouped swatch, which comes in under it next. +#[test] +fn a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Group", |d, _| { + let offset = Paint::Pattern { pattern: "Tiles 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) }; + let w = vectorcraft_color::Swatch { name: "Tiles 2".into(), paint: offset, global: false, spot: false }; + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { xf, .. }) if *xf == kurbo::Affine::IDENTITY), "{first} {r} {paint:?}"); +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, whose swatch the library +/// deleted before giving the name "Inner 2" to a color, comes in under another name, so adding +/// that color next adds it under its own name. +#[test] +fn a_nested_pattern_does_not_take_a_name_the_library_gives_a_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]})); + assert!(doc(&s).pattern("Inner 2").is_some(), "the library keeps the pattern"); + run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}"); + assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}"); +} + +/// A library pattern pasted into the document, whose global color "Ink 2" (in a color group) was +/// then deleted without unlinking the art, is not reused by bringing that color back as "Ink 2" +/// when the library also has a process color "Ink 2": adding that color next adds it under its +/// own name. +#[test] +fn a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + group_as(&mut s, "Crimson", "Ink 2"); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "edit.paste", json!({})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the global color as Ink 2"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}"); +} + +/// Move swatch `name` of `s`'s document into a new color group under the name `to`, and link the +/// art of every pattern linked to it to `to`. +fn group_as(s: &mut Session, name: &str, to: &str) { + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == name).unwrap(); + let mut w = d.swatches.remove(i); + w.name = to.into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + for def in &mut d.patterns { + for node in &mut def.art { + for it in &mut std::sync::Arc::make_mut(node).appearance.items { + it.paint_mut().map_links(&mut |_, link, _| { + let hit = link.as_deref() == Some(name); + if hit { + *link = Some(to.into()); + } + hit + }); + } + } + } + Ok(()) + }) + .unwrap(); +} + +/// The swatch paint `p` links to. +fn tint_link(p: &Paint) -> Option { + match p { + Paint::Solid { swatch, .. } => swatch.clone(), + _ => None, + } +} + +/// A library pattern "Tiles" added beside the document's own swatch "Tiles" does not take the name +/// "Tiles 2" that the library gives a color, neither for the pattern nor for its swatch; nor does +/// its swatch when the document holds the pattern as "Tiles 2" (pasted there) without a swatch. +#[test] +fn a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names() { + for pasted in [false, true] { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Tiles", "color": "#ff0000"})); + if pasted { + run(&mut s, "edit.paste", json!({})); + assert!(doc(&s).pattern("Tiles 2").is_some(), "the paste numbers the pattern"); + let names: Vec = doc(&s) + .swatches_iter() + .filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Tiles 2")) + .map(|w| w.name.clone()) + .collect(); + run(&mut s, "swatch.delete", json!({"names": names})); + } + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{pasted}: {first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{pasted}: {first} {r}"); + } +} + /// A library tint added without its global color to a document that has no swatch of the color's /// name brings the color along under its own name. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 1fa5fa8ded..b94baa9233 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,6 +10,25 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind use crate::{EngineError, Prefs, Result, Session}; +/// What a hover's lend decision holds for ([`Session::hover_tool_at`]). +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct HoverKey { + /// The active document's uid and revision, which moves with the selection. + doc: Option<(u64, u64)>, + tool: &'static str, + mods: Mods, + /// The selection tool and the part selection tool chosen last. + last_tools: (Option<&'static str>, Option<&'static str>), + ctrl_click_selects_behind: bool, + object_selection_by_path_only: bool, + type_selection_by_path_only: bool, + selection_tolerance: f64, + anchor_size: u32, + use_preview_bounds: bool, + type_glyph_bounds: bool, + show_handles_multiple_anchors: bool, +} + /// The tool whose radius is General › Corner Radius. const ROUNDED_RECTANGLE: &str = "roundedRectangle"; @@ -183,6 +202,9 @@ impl Session { if self.tool.id() == id { return Ok(()); } + // A double-click or triple-click after the switch is the new tool's, also when the switch + // comes back to the tool a Cmd press was lent from. + self.press_lent = None; // Sampling type keeps its highlighted characters as the target, and a whole story that // Select All selected. Capture before the Type tool deactivates (which commits typing and // clears its editing state). @@ -208,6 +230,9 @@ impl Session { } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); + if id != "selection" { + self.last_part_selection_tool = Some(self.tool.id()); + } self.select_whole_instance(id); } Ok(()) @@ -251,8 +276,10 @@ impl Session { /// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract). /// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the /// object (#3901; ). + /// Group Selection lends the Selection tool, and the Selection tool lends Direct Selection or + /// Group Selection, whichever was chosen last (Direct Selection until one is). /// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane. - /// None for the other selection tools and the view tools. + /// None for the view tools. fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> { use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool}; if matches!(id, "hand" | "zoom" | "rotateView") { @@ -261,6 +288,12 @@ impl Session { if id == "directSelection" && mods.cmd { return Some(if mods.alt { "groupSelection" } else { "selection" }); } + if id == "groupSelection" && mods.cmd { + return Some("selection"); + } + if id == "selection" && mods.cmd { + return Some(self.last_part_selection_tool.unwrap_or("directSelection")); + } if id == "perspectiveSelection" && mods.cmd && mods.alt { return None; } @@ -280,15 +313,118 @@ impl Session { self.lent_tool(self.tool.id(), mods) } - /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the - /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, - /// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event - /// for the tool, and the warnings of a preview that keeping the typing applied. - fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec)> { - if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() { + /// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd + /// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and + /// the active tool is not computing an edit, else the active tool. Over a selected object where + /// a Cmd press selects behind, as the cursor last found it, it names the active tool. + pub fn shown_tool_id(&self, mods: &Mods) -> &'static str { + match self.hovered_lent(mods) { + Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The tool whose marks the canvas shows with `mods` held: the selection tool a Cmd press at + /// the pointer would borrow, as [`Self::hover_tool_at`] or [`Self::cursor`] last found it + /// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas + /// asks this while the view moves, when it does not hit-test the art under the pointer. + pub fn hover_tool_id(&self, mods: &Mods) -> &'static str { + match self.hovered_lent(mods) { + Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The selection tool a Cmd press with `mods` would borrow at the pointer: the one + /// [`Self::hover_tool_at`] or [`Self::cursor`] last found, while the document, the selection, + /// the active tool and the keys are as they were then (none where the press selects behind), + /// else the one [`Self::lent_tool_id`] names. + fn hovered_lent(&self, mods: &Mods) -> Option<&'static str> { + match self.hover_lent { + Some((key, lent)) if key == self.hover_key(mods) => lent, + _ => self.lent_tool_id(mods), + } + } + + /// What a hover's lend decision holds for: the active document's state (its uid and revision, + /// which moves with the selection), the active tool, the keys, the selection tools chosen last + /// and the preferences a press's hit test reads. + fn hover_key(&self, mods: &Mods) -> HoverKey { + let p = &self.prefs; + HoverKey { + doc: self.active().map(|d| (d.uid, d.revision)), + tool: self.tool.id(), + mods: *mods, + last_tools: (self.last_selection_tool, self.last_part_selection_tool), + ctrl_click_selects_behind: p.ctrl_click_selects_behind, + object_selection_by_path_only: p.object_selection_by_path_only, + type_selection_by_path_only: p.type_selection_by_path_only, + selection_tolerance: p.selection_tolerance, + anchor_size: p.anchor_size, + use_preview_bounds: p.use_preview_bounds, + type_glyph_bounds: p.type_glyph_bounds, + show_handles_multiple_anchors: p.show_handles_multiple_anchors, + } + } + + /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the + /// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow + /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the + /// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move. + pub fn hover_tool_at(&mut self, p: Option, mods: &Mods, view: ViewInfo) -> &'static str { + let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = match p { + _ if !lends => None, + Some(p) => self.lent_tool_at(p, mods, view), + None => self.lent_tool_id(mods), + }; + let key = self.hover_key(mods); + self.hover_lent = lends.then_some((key, lent)); + lent.unwrap_or(self.tool.id()) + } + + /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when + /// the Selection tool keeps a Cmd press on a selected object to select the object behind it + /// (Selection & Anchor Display › Command Click to Select Objects Behind). + fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { + let id = self.lent_tool(self.tool.id(), mods)?; + let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); + (!behind).then_some(id) + } + + /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks + /// before the press, to tell a gesture of the tool in hand from one of a lent tool. + pub fn press_lends_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> bool { + ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.lent_tool_at(ev.pos, &ev.mods, view).is_some() + } + + /// A press with Cmd held (Ctrl elsewhere): the selection tool [`Self::lent_tool_at`] names + /// takes the gesture, pressing without Cmd (a plain click, not Select Behind). The tool lent to + /// stays as it was, unaware, until the release. With a selection tool active, the double-click + /// or triple-click that follows Cmd-clicks goes to the tool the clicks went to, with Cmd kept + /// (Cmd+Shift releases a guide), and that tool is given back after it. → the event for the tool, + /// and the warnings of a preview that keeping the typing applied. + fn lend_selection_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<(PointerEvent, Vec)> { + let follow_up = + matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick) && vectorcraft_tools::catalog::is_selection_tool(self.tool.id()); + if ev.kind == PointerKind::Down { + self.press_lent = None; + } + if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() { return Ok((*ev, vec![])); } - let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) }; + // A follow-up goes where the press before it went, whatever that press selected, while the + // document and the active tool are the ones that press found. + let at = (self.active().map(|d| d.uid), self.tool.id()); + let id = if follow_up { + self.press_lent.filter(|(doc, tool, _)| (*doc, *tool) == at).map(|(.., id)| id) + } else { + self.lent_tool_at(ev.pos, &ev.mods, view) + }; + let Some(id) = id else { return Ok((*ev, vec![])) }; + if !follow_up { + self.press_lent = Some((at.0, at.1, id)); + } // Typing in progress is kept as its own step first: the lent tool's drag previews from the // document its interaction started from, which would drop the typing (#1881). When it // can't be kept, the press is not lent. @@ -316,7 +452,8 @@ impl Session { } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); - Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) + let cmd = follow_up && ev.mods.cmd; + Ok((PointerEvent { mods: Mods { cmd, ..ev.mods }, ..*ev }, settled)) } /// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the @@ -341,6 +478,9 @@ impl Session { self.back_to_bucket = outer_bucket; self.keep_tool_settings(); self.tool = lender; + // Back with the Selection or Group Selection tool, a symbol part the lent Direct + // Selection picked gives way to its instance, as choosing the tool does. + self.select_whole_instance(self.tool.id()); if let Some(points) = mesh_points { self.tool.set_option("meshPoints", &points); } @@ -771,7 +911,7 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); - let (ev, settled) = self.lend_selection_tool(ev)?; + let (ev, settled) = self.lend_selection_tool(ev, view)?; let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -795,7 +935,7 @@ impl Session { PointerKind::Up => self.press_point = None, _ => {} } - if ev.kind == PointerKind::Up { + if ev.kind == PointerKind::Up || (lent && matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick)) { self.give_back_tool(view)?; } r @@ -1305,7 +1445,11 @@ impl Session { /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. - let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None }; + // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. + let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None }; + let key = self.hover_key(&mods); + self.hover_lent = lends.then_some((key, lent)); match lent { Some(id) => { let lent = self.make_tool(id); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 1413bb17bb..6664828398 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -93,7 +93,7 @@ fn every_command_without_a_document() { } /// Regression: huge column counts used to panic with `capacity overflow`; in every layout and -/// order (#681), with huge and negative spacing too. +/// order (#681), with huge and negative spacing too, and with `indices` and `at`. #[test] fn artboard_rearrange_huge_columns() { for fx in Fixture::ALL { @@ -106,6 +106,11 @@ fn artboard_rearrange_huge_columns() { } } } + // Listed artboards, out of range, and the grid's top-left at the far ends of the plane. + for (indices, at) in [(json!([0]), json!([1e308, -1e308])), (json!([0, u64::MAX]), json!([0, 0])), (json!([]), json!([-1e308, 1e308]))] { + let p = json!({ "indices": indices, "at": at, "columns": u64::MAX, "spacing": 1e308 }); + assert_eq!(probe(fx, "artboard.rearrange", &p), None); + } } } diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 081b6b49dd..18e0cb1f84 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -711,9 +711,10 @@ proptest! { } /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with - /// control and bidirectional override characters, a `menu` naming another menu, junk - /// parameters) parse to an error or to commands whose menu labels show no hidden character and - /// that sit under Plug-ins alone; installing one and running each of its commands ends as an + /// control and bidirectional override characters, a `menu` of any shape naming any menu, junk + /// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no + /// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest + /// may name, with the plug-in's name; installing one and running each of its commands ends as an /// error or an edit, never a panic, and the document then renders and exports. #[test] fn hostile_manifest_commands_never_crash( @@ -727,7 +728,17 @@ proptest! { 1 => "[a-z\u{0007}\n]{1,8}".prop_map(Value::from), 1 => arb_junk(), ], - prop_oneof![Just(Value::Null), Just(json!("File")), arb_junk()], + prop_oneof![ + Just(Value::Null), + Just(json!("File")), + Just(json!({"path": ["Select"], "after": "Inverse"})), + Just(json!({"path": ["Object", "Path"]})), + Just(json!({"path": ["File"]})), + Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})), + arb_junk().prop_map(|j| json!({"path": j})), + arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})), + arb_junk(), + ], prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], ) .prop_map(|(id, label, menu, params)| { @@ -746,8 +757,9 @@ proptest! { ), junk in prop::option::weighted(0.1, arb_junk()), given in prop_oneof![Just(json!({})), Just(json!({"by": 3})), arb_junk()], + api in 1u32..=2, ) { - let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind}); + let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind, "api": api}); if matches!(kind, "exporter" | "importer") { m["extensions"] = json!(["fz"]); } @@ -760,6 +772,12 @@ proptest! { let shown = c.shown_label(); prop_assert!(!shown.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown); prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let placed = c.menu_label(&man.name); + prop_assert!(!placed.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", placed); + if let Some(place) = &c.place { + prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place); + prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed); + } } } let mut s = rich_session(); @@ -778,7 +796,9 @@ proptest! { let ran = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; prop_assert!(ran.is_empty() || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); for (id, menu) in &ran { - prop_assert!(menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"), "{id}: {menu:?}"); + let submenu = menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"); + let place = api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&menu.as_slice()); + prop_assert!(submenu || place, "{id}: {menu:?}"); } renders(&s, "after hostile commands")?; vectorcraft_plugins::registry::remove("fuzz.commands"); diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index d80314978c..1193839d0b 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -607,7 +607,9 @@ impl<'a> Scene<'a> { // (a plate's colors come from the separator, which has applied it already); a // spot ink with a white color still overprints, as it is written as that ink. Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { - let discarded = !self.plate && self.doc.discards_white_overprint(p); + let discarded = !self.plate + && vectorcraft_doc::overprint::is_white(p) + && vectorcraft_doc::overprint::DiscardWhite::of(self.doc).discards(p); let on = self.overprint_on(n.colorize_overprints() && !discarded); self.colorized_image(im, blob, p, on); self.overprint_off(on); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ebbf43c814..3822e71ed0 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1597,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index d5fe994bed..032576e605 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -6,13 +6,15 @@ //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes //! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles //! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines -//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch -//! two or three shapes ([`tangent_circles`]). +//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]), the circles that touch +//! two or three shapes ([`tangent_circles`]) and the largest circle inside a shape +//! ([`inscribed_circle`]). mod bridge; mod crossings; mod dashes; mod extend; +mod inscribed; pub mod shapes; mod shared_edge; mod slide; @@ -33,6 +35,10 @@ pub use bridge::{ pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; +pub use inscribed::{ + INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_CELLS, MAX_INSCRIBED_EDGES, MAX_INSCRIBED_WORK, inscribed_circle, + inscribed_circle_within, +}; pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; diff --git a/crates/pathops/src/addons/pathtools/inscribed.rs b/crates/pathops/src/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..7b021d512e --- /dev/null +++ b/crates/pathops/src/addons/pathtools/inscribed.rs @@ -0,0 +1,373 @@ +//! Add Inscribed Circle: the largest circle inside a filled outline, the center of which is the +//! outline's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). +//! +//! The outline is first resolved under its fill rule into simple contours (outer contours and +//! holes, as [`crate::try_normalize`] resolves them, narrow ones kept), so overlapping and self-crossing subpaths count as the area they fill +//! and only real edges bound the circle. The contours are flattened, and square cells covering +//! their box are searched best first: a cell's center lies some distance inside the outline, and no +//! point of the cell lies more than half the cell's diagonal farther in, so a cell that cannot beat +//! the best center found by more than the precision is not split. The radius is then measured from +//! the center to the curves themselves. + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use kurbo::{ParamCurveNearest, Point, Rect, Shape}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, PathEl}; + +use crate::boolean::{Tidy, fill_bezpath, normalize_bez}; + +#[cfg(test)] +mod tests; + +#[cfg(test)] +thread_local! { + /// The distances from a point to an edge that the last [`search`] on this thread measured. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How close to the largest circle's radius the search gets, in points, for outlines whose box is +/// at least 10 pt across; a smaller box gets a thousandth of its narrower side. +pub const INSCRIBED_PRECISION: f64 = 0.01; +/// Most straight edges the flattened outline may have. +pub const MAX_INSCRIBED_EDGES: usize = 1 << 18; +/// Most distances from a point to an edge that one search measures, or that the searches of one +/// [`inscribed_circle_within`] budget measure together. +pub const MAX_INSCRIBED_WORK: usize = 1 << 27; +/// Most cells the box is first cut into. +const MAX_FIRST_CELLS: f64 = 4096.0; +/// Most cells the search keeps waiting to be split. +pub const MAX_INSCRIBED_CELLS: usize = 1 << 20; +/// How many times an outline the flattening does not resolve is flattened 16 times finer. +const FINER_FLATTENINGS: usize = 4; + +/// The largest circle inside an outline: its center and radius. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Inscribed { + pub center: Point, + pub radius: f64, +} + +/// Why [`inscribed_circle`] found no circle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InscribedError { + /// The outline fills no area. + NoArea, + /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] anchors in its + /// subpaths of two or more or more than as many edges once flattened, or the + /// search would measure more than its limit or keep more than [`MAX_INSCRIBED_CELLS`] cells + /// waiting, or the outline is so thin for its length that it flattens to no area. + TooComplex, +} + +/// The largest circle inside the area that `path` fills under `rule`, within twice the precision +/// of the largest radius: the search's precision and the flattening, at half of it. The precision +/// is [`INSCRIBED_PRECISION`], or a thousandth of the narrower side of the filled area's box when +/// that is less than 10 pt. A curve whose control polygon is longer than 4096² times the +/// flattening tolerance (83,886 pt at 0.005 pt) is flattened more coarsely +/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much; so can a curved hole +/// narrower than the flattening tolerance. The bounds hold for the fill as the path operations +/// resolve it: holes and gaps narrower than 1e-6 pt close up, and edges can move by as much. Open +/// subpaths are closed as the other path operations close them, handles included. The searches +/// for one outline measure at most [`MAX_INSCRIBED_WORK`] distances in all, the final distances +/// to the curves included. +pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result { + inscribed_circle_within(path, rule, &mut MAX_INSCRIBED_WORK.clone()) +} + +/// [`inscribed_circle`], measuring at most `work` distances from a point to an edge (and never +/// more than [`MAX_INSCRIBED_WORK`]) and taking the ones it measured off `work`, so several +/// searches can share one budget. +pub fn inscribed_circle_within(path: &PathData, rule: FillRule, work: &mut usize) -> Result { + // A path with more anchors than the edge limit, in the subpaths that are filled, is refused + // before it is resolved. + let mut filled_anchors = path.subpaths.iter().map(|sp| sp.anchors.len()).filter(|&n| n >= 2); + if filled_anchors.try_fold(0usize, |total, n| total.checked_add(n).filter(|&t| t <= MAX_INSCRIBED_EDGES)).is_none() { + return Err(InscribedError::TooComplex); + } + let filled = fill_bezpath(path); + let b = filled.bounding_box(); + if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { + return Err(InscribedError::NoArea); + } + let precision = precision_for(b); + // Every contour of the fill's boundary counts, however narrow, down to the sweep's tolerance + // (1e-6 pt; [`crate::boolean::eps_for`]): a hairline hole is still outside the fill. Curves the + // sweep split are rebuilt from the input's own. + let contours = normalize_bez(&filled, rule).map_err(|_| InscribedError::TooComplex)?; + // The resolved boundary can have far more pieces than the input; past the edge limit it is + // refused before it is copied. + if contours.contours().map(|c| c.path.segments().count()).sum::() > MAX_INSCRIBED_EDGES { + return Err(InscribedError::TooComplex); + } + let tidy = Tidy::keeping(precision, [&filled]); + let mut curves = kurbo::BezPath::new(); + for c in contours.contours() { + curves.extend(tidy.repair(&c.path)); + } + let b = curves.bounding_box(); + if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { + return Err(InscribedError::NoArea); + } + // The fill rule can leave a much narrower area than the outline's box. + let precision = precision.min(precision_for(b)); + // The attempts for this outline share one allowance, taken off `work` as it is spent. + let start = (*work).min(MAX_INSCRIBED_WORK); + let mut allowance = start; + let found = measure(&curves, b, precision, &mut allowance); + *work = work.saturating_sub(start - allowance); + found +} + +/// The largest circle in the resolved `curves`, whose box is `b`, searched to `precision`, +/// measuring at most `allowance` distances and taking them off it. +fn measure(curves: &kurbo::BezPath, b: Rect, precision: f64, allowance: &mut usize) -> Result { + // Flattening can close up or move an area thinner than its tolerance, so that the flattened + // outline holds nothing or its best center lies outside the curves: the outline is then + // flattened 16 times finer, up to 4 times (down to 1/65,536 of the tolerance). The resolved + // contours have an area, so an outline that is still not measured is past what the + // flattening can resolve (very long curves are flattened more coarsely). + let mut tolerance = precision / 2.0; + // The last edges searched: a finer tolerance can flatten to the same ones (very long curves), + // which would give the same center again. + let mut searched = None; + for attempt in 0..=FINER_FLATTENINGS { + let edges = edges(curves, tolerance)?; + let held = area(&edges); + let last = attempt == FINER_FLATTENINGS; + let fresh = searched.as_ref() != Some(&edges); + if fresh && (held > tolerance * tolerance || (last && held.partial_cmp(&0.0) == Some(Ordering::Greater))) { + match search(&edges, b, precision, allowance) { + Ok(center) => { + // The circle touches the nearest curve, whatever the flattening moved; those + // distances come out of the allowance too. + let pieces = curves.segments().count(); + if *allowance < pieces { + return Err(InscribedError::TooComplex); + } + *allowance -= pieces; + let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); + if radius.is_finite() && radius > 0.0 && fill_contains(curves, FillRule::NonZero, center) { + return Ok(Inscribed { center, radius }); + } + } + Err(InscribedError::NoArea) => {} + Err(e) => return Err(e), + } + searched = Some(edges); + } + tolerance /= 16.0; + } + Err(InscribedError::TooComplex) +} + +/// The search's precision for an area whose box is `b`. +fn precision_for(b: Rect) -> f64 { + INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0) +} + +/// The straight edges of `curves` flattened to within `tolerance`, each subpath closed. +fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, InscribedError> { + let mut out = vec![]; + let (mut start, mut last) = (None, None); + let close = |out: &mut Vec<(Point, Point)>, start: Option, last: Option| { + if let (Some(a), Some(b)) = (last, start) + && a != b + { + out.push((a, b)); + } + }; + // Once past the limit, no further curve is flattened. + let over = std::cell::Cell::new(false); + vectorcraft_geom::flatten(curves.iter().take_while(|_| !over.get()), tolerance, |el| { + if over.get() { + return; + } + match el { + PathEl::MoveTo(p) => { + close(&mut out, start, last); + (start, last) = (Some(p), Some(p)); + } + PathEl::LineTo(p) => { + if let Some(a) = last { + out.push((a, p)); + } + last = Some(p); + } + PathEl::ClosePath => { + close(&mut out, start, last); + last = start; + } + _ => {} + } + over.set(out.len() > MAX_INSCRIBED_EDGES); + }); + close(&mut out, start, last); + if over.get() || out.len() > MAX_INSCRIBED_EDGES { + return Err(InscribedError::TooComplex); + } + Ok(out) +} + +/// The area the closed `edges` hold: their outer contours and holes turn opposite ways. Each +/// contour's points are taken from its first one, so a small area far from the origin is not +/// rounded away. +fn area(edges: &[(Point, Point)]) -> f64 { + let (mut total, mut contour) = (0.0, 0.0); + let (mut o, mut last) = (Point::ZERO, None); + for &(a, b) in edges { + // An edge that does not start where the last one ended starts the next contour. + if last != Some(a) { + total += contour; + (contour, o) = (0.0, a); + } + contour += (a - o).cross(b - o); + last = Some(b); + } + ((total + contour) / 2.0).abs() +} + +/// How far `p` lies inside the closed `edges` (nonzero winding): the distance to the nearest edge, +/// negative outside. +fn inside(edges: &[(Point, Point)], p: Point) -> f64 { + let mut winding = 0; + let mut nearest = f64::INFINITY; + for &(a, b) in edges { + if (a.y <= p.y) != (b.y <= p.y) { + let side = (b - a).cross(p - a); + if b.y > a.y && side > 0.0 { + winding += 1; + } else if b.y <= a.y && side < 0.0 { + winding -= 1; + } + } + nearest = nearest.min(distance_sq_to_segment(p, a, b)); + } + let d = nearest.sqrt(); + if winding != 0 { d } else { -d } +} + +fn distance_sq_to_segment(p: Point, a: Point, b: Point) -> f64 { + 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 }; + (p - (a + ab * t)).hypot2() +} + +/// A square cell of the search: its center, half its side, how far its center lies inside the +/// outline, and the most any of its points can. +#[derive(Clone, Copy)] +struct Cell { + center: Point, + half: f64, + inside: f64, + best: f64, +} + +impl Cell { + fn new(edges: &[(Point, Point)], center: Point, half: f64) -> Self { + let inside = inside(edges, center); + Self { center, half, inside, best: inside + half * std::f64::consts::SQRT_2 } + } +} + +impl PartialEq for Cell { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl Eq for Cell {} + +impl PartialOrd for Cell { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Cell { + fn cmp(&self, other: &Self) -> Ordering { + self.best.total_cmp(&other.best) + } +} + +/// The point of the closed `edges`, inside box `b`, farthest from every edge, within `precision`, +/// measuring at most `budget` distances from a point to an edge, and never more than +/// [`MAX_INSCRIBED_WORK`], and taking the ones it measured off `budget`. +fn search(edges: &[(Point, Point)], b: Rect, precision: f64, budget: &mut usize) -> Result { + let mut work = 0usize; + let found = search_measuring(edges, b, (precision, (*budget).min(MAX_INSCRIBED_WORK), MAX_INSCRIBED_CELLS), &mut work); + *budget = budget.saturating_sub(work); + found +} + +/// [`search`] with `(precision, limit, max_cells)`, measuring at most `limit` distances (counted +/// in `work`) and keeping at most `max_cells` cells waiting. +fn search_measuring(edges: &[(Point, Point)], b: Rect, limits: (f64, usize, usize), work: &mut usize) -> Result { + let (precision, limit, max_cells) = limits; + // Square cells as wide as the box's narrower side, or wider when that would make more than + // `first` along the box or in all: at most MAX_FIRST_CELLS, and at most a quarter of the work + // limit, so the first cells take at most about three quarters of it. + let first = MAX_FIRST_CELLS.min((limit / edges.len().max(1) / 4) as f64).max(1.0); + let size = b.width().min(b.height()).max((b.area() / first).sqrt()).max(b.width().max(b.height()) / first); + let (cols, rows) = ((b.width() / size).ceil() as usize, (b.height() / size).ceil() as usize); + // Each cell is measured only when the limit still has room for it. + let measure = |work: &mut usize, center: Point, half: f64| { + let Some(after) = work.checked_add(edges.len()).filter(|&after| after <= limit) else { + return Err(InscribedError::TooComplex); + }; + *work = after; + #[cfg(test)] + MEASURED.with(|m| m.set(*work)); + Ok(Cell::new(edges, center, half)) + }; + // No circle in the box is wider than its narrower side. + let ceiling = b.width().min(b.height()) / 2.0; + // Until a center inside the outline is found, every cell that may hold one is split; after + // that, only cells that may beat the best center by more than the precision. + let open = |cell: &Cell, best: &Cell| cell.best > 0.0 && (best.inside <= 0.0 || cell.best - best.inside > precision); + let done = |best: &Cell| best.inside > 0.0 && best.inside >= ceiling - precision; + let mut best = measure(work, b.center(), 0.0)?; + let mut cells = BinaryHeap::new(); + let add = |cells: &mut BinaryHeap, best: &mut Cell, cell: Cell| { + if cell.inside > best.inside { + *best = cell; + } + // A best center at the ceiling ends the search, full queue or not. + if !done(best) && open(&cell, best) { + if cells.len() >= max_cells { + return Err(InscribedError::TooComplex); + } + cells.push(cell); + } + Ok(()) + }; + for row in 0..rows { + for col in 0..cols { + if done(&best) { + return Ok(best.center); + } + let at = Point::new(b.x0 + (col as f64 + 0.5) * size, b.y0 + (row as f64 + 0.5) * size); + let cell = measure(work, at, size / 2.0)?; + add(&mut cells, &mut best, cell)?; + } + } + while let Some(cell) = cells.pop() { + if done(&best) || !open(&cell, &best) { + break; + } + let h = cell.half / 2.0; + for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { + if done(&best) { + return Ok(best.center); + } + let child = measure(work, cell.center + (dx, dy), h)?; + add(&mut cells, &mut best, child)?; + } + } + if best.inside <= 0.0 { + return Err(InscribedError::NoArea); + } + Ok(best.center) +} diff --git a/crates/pathops/src/addons/pathtools/inscribed/tests.rs b/crates/pathops/src/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..1731d798a0 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/inscribed/tests.rs @@ -0,0 +1,304 @@ +use kurbo::{Point, Rect}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Anchor, FillRule, PathData, SubPath, shapes}; + +use super::*; + +fn polygon(pts: &[(f64, f64)]) -> PathData { + PathData::new(vec![SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)]) +} + +fn circle(x: f64, y: f64, r: f64) -> SubPath { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)).subpaths.remove(0) +} + +/// Points around the circle `c`, a little inside its edge. +fn rim(c: Inscribed) -> impl Iterator { + (0..360).map(move |i| { + let a = (i as f64).to_radians(); + c.center + kurbo::Vec2::new(a.cos(), a.sin()) * (c.radius - 1e-6) + }) +} + +/// The circle lies in the filled area and is within twice the precision of `largest`, which may +/// be `slack` too small: a circle of four curves bulges up to 0.03% past a true circle. +fn holds_within(path: &PathData, rule: FillRule, c: Inscribed, largest: f64, slack: f64) { + let bp = path.to_bezpath(); + assert!(rim(c).all(|p| fill_contains(&bp, rule, p)), "{c:?} reaches outside the fill"); + assert!(c.radius <= largest + slack + 1e-6 && c.radius >= largest - 2.0 * INSCRIBED_PRECISION, "{c:?}, largest {largest}"); +} + +fn holds(path: &PathData, rule: FillRule, c: Inscribed, largest: f64) { + holds_within(path, rule, c, largest, 0.0); +} + +#[test] +fn a_square_holds_the_circle_at_its_center() { + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + holds(&sq, FillRule::NonZero, c, 50.0); + assert!((c.center - Point::new(50.0, 50.0)).hypot() < 2.0 * INSCRIBED_PRECISION, "{c:?}"); +} + +#[test] +fn a_concave_shape_holds_the_circle_in_its_corner() { + // An L whose arms are 30 wide: the box's center (50, 50) is outside it. The largest circle + // touches the two outer edges and the inner corner (30, 30): c = √2 (30 − c). + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + holds(&l, FillRule::NonZero, c, largest); +} + +#[test] +fn a_ring_holds_the_circle_beside_its_hole_under_even_odd() { + let ring = PathData::new(vec![circle(0.0, 0.0, 100.0), circle(0.0, 0.0, 40.0)]); + let c = inscribed_circle(&ring, FillRule::EvenOdd).unwrap(); + holds_within(&ring, FillRule::EvenOdd, c, 30.0, 0.0003 * 140.0); + assert!((c.center.to_vec2().hypot() - 70.0).abs() < 0.1, "{c:?}"); + // Both subpaths turn the same way, so under nonzero the inner one fills in and is no hole. + let c = inscribed_circle(&ring, FillRule::NonZero).unwrap(); + holds_within(&ring, FillRule::NonZero, c, 100.0, 0.0003 * 100.0); +} + +#[test] +fn overlapping_subpaths_count_as_the_area_they_fill() { + // Two squares overlapping by half: under nonzero they fill one 150 × 100 rectangle, and the + // edges inside it do not bound the circle. + let a = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let b = polygon(&[(50.0, 0.0), (150.0, 0.0), (150.0, 100.0), (50.0, 100.0)]); + let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::NonZero).unwrap(); + holds(&both, FillRule::NonZero, c, 50.0); +} + +#[test] +fn a_small_shape_is_measured_to_its_own_scale() { + // The L of the concave test, a thousandth of its size. + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0, y / 1000.0))); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}"); +} + +#[test] +fn a_shape_narrower_than_the_default_precision_gets_a_circle() { + // 0.005 pt square: resolved at 0.01 pt it would be dropped as a sliver. + let sq = polygon(&[(0.0, 0.0), (0.005, 0.0), (0.005, 0.005), (0.0, 0.005)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + assert!(c.radius <= 0.0025 + 1e-12 && c.radius > 0.0025 * 0.99, "{c:?}"); +} + +#[test] +fn a_tiny_shape_far_from_the_origin_gets_a_circle() { + let sq = polygon(&[(10_000.0, 10_000.0), (10_000.000_1, 10_000.0), (10_000.000_1, 10_000.000_1), (10_000.0, 10_000.000_1)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}"); + // With a second tiny square far from the first, each square's area is measured from its own + // corner. + let near = polygon(&[(0.0, 0.0), (0.0001, 0.0), (0.0001, 0.0001), (0.0, 0.0001)]); + let far = polygon(&[(1e6, 1e6), (1e6 + 0.0001, 1e6), (1e6 + 0.0001, 1e6 + 0.0001), (1e6, 1e6 + 0.0001)]); + let both = PathData::new(near.subpaths.into_iter().chain(far.subpaths).collect()); + let a = area(&edges(&both.to_bezpath(), 0.005).unwrap()); + assert!((a - 2e-8).abs() < 1e-10, "{a}"); +} + +#[test] +fn a_hairline_hole_bounds_the_circle() { + // A 100 pt square with a hole 0.001 pt wide down its middle: the circle stays on one side. + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let slit = polygon(&[(49.9995, 10.0), (50.0005, 10.0), (50.0005, 90.0), (49.9995, 90.0)]); + let both = PathData::new(sq.subpaths.into_iter().chain(slit.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::EvenOdd).unwrap(); + assert!((c.center.x - 50.0).abs() >= c.radius - 2.0 * INSCRIBED_PRECISION, "{c:?}"); + assert!(c.radius < 30.0, "{c:?}"); +} + +#[test] +fn a_long_thin_shape_is_refused_without_measuring_past_the_work_limit() { + // A strip 5,000 long, 1 high at one end and 2 at the other, whose top edge has 5,000 pieces: + // cut into cells as wide as it is high, the first cells alone would measure 2,500 times every + // edge. + let n = 5000; + let top: Vec<(f64, f64)> = (0..=n).map(|i| (i as f64, 0.0)).collect(); + let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 2.0)]).collect(); + let e = edges(&polygon(&pts).to_bezpath(), 0.005).unwrap(); + let limit = 100 * e.len(); + assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 2.0), 0.01, &mut limit.clone()), Err(InscribedError::TooComplex)); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured <= limit, "{measured} measured, limit {limit}"); +} + +#[test] +fn a_long_rectangle_stops_once_no_wider_circle_fits() { + // Every point of the center line is 50 from the long sides: the box's center is already the + // largest circle's, and the search stops at the first cells. + let r = polygon(&[(0.0, 0.0), (100_000.0, 0.0), (100_000.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + holds(&r, FillRule::NonZero, c, 50.0); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured <= (MAX_FIRST_CELLS as usize + 1) * 4, "{measured} measured"); +} + +#[test] +fn a_fill_far_smaller_than_the_precision_still_gets_a_circle() { + // Two 0.001 pt squares at opposite corners of a 100 pt box, which sets the precision to + // 0.01 pt. + let a = polygon(&[(0.0, 0.0), (0.001, 0.0), (0.001, 0.001), (0.0, 0.001)]); + let b = polygon(&[(99.999, 99.999), (100.0, 99.999), (100.0, 100.0), (99.999, 100.0)]); + let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + assert!(fill_contains(&both.to_bezpath(), FillRule::NonZero, c.center), "{c:?}"); +} + +#[test] +fn a_lens_thinner_than_the_flattening_tolerance_gets_a_circle() { + // A straight side and a curve bowed 0.001 pt from it, 141 pt long: flattened to 0.005 pt the + // curve would lie on the straight side. + let lens = |side: f64| { + let n = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt() * (0.001 / 0.75); + let (a, b) = (Point::ZERO, Point::new(side, side)); + PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(a, Point::new(side / 3.0, side / 3.0) + n, a), + Anchor::with_handles(b, b, Point::new(side * 2.0 / 3.0, side * 2.0 / 3.0) + n), + ], + true, + )]) + }; + let l = lens(100.0); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + assert!(fill_contains(&l.to_bezpath(), FillRule::NonZero, c.center), "{c:?}"); + // A curve that long is flattened too coarsely to show the bow at all: too complex, not empty. + assert_eq!(inscribed_circle(&lens(1e6), FillRule::NonZero), Err(InscribedError::TooComplex)); +} + +#[test] +fn a_bowed_strip_thinner_than_the_flattening_tolerance_is_not_reported_empty() { + // Two curves 0.001 pt apart, both bowed 0.003 pt the same way: flattened to 0.005 pt they + // become a straight strip that lies outside the bowed one. + let strip = |side: f64| { + let unit = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt(); + let (bow, gap) = (unit * (0.003 / 0.75), unit * 0.001); + let (a, b) = (Point::ZERO, Point::new(side, side)); + let third = (b - a) / 3.0; + let (a1, b1) = (a + gap, b + gap); + PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(a, a, a + third + bow), + Anchor::with_handles(b, b - third + bow, b), + Anchor::with_handles(b1, b1, b1 - third + bow), + Anchor::with_handles(a1, a1 + third + bow, a1), + ], + true, + )]) + }; + let inside = |s: &PathData, c: Inscribed| { + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + // Measured against the curves flattened to 1e-8 pt by kurbo itself, which does not + // coarsen long curves: kurbo's winding can miss a curve a point lies this close to. + let mut polyline = kurbo::BezPath::new(); + kurbo::flatten(s.to_bezpath(), 1e-8, |el| polyline.push(el)); + let fine = edges(&polyline, 1e-8).unwrap(); + assert!(rim(c).all(|p| super::inside(&fine, p) > 1e-8), "{c:?} reaches outside"); + }; + // 28 and 141 pt long: a circle inside it, or too complex to measure; never "no area". + for side in [20.0, 100.0] { + let s = strip(side); + match inscribed_circle(&s, FillRule::NonZero) { + Ok(c) => inside(&s, c), + e => assert_eq!(e, Err(InscribedError::TooComplex), "{side}"), + } + } +} + +#[test] +fn a_thin_turned_rectangle_gets_the_circle_at_its_center() { + // 100 pt long and 0.009998 pt wide, turned 45°: no wider than twice the flattening tolerance. + let (u, v) = (kurbo::Vec2::new(1.0, 1.0) / 2f64.sqrt(), kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt()); + let (along, across) = (u * 100.0, v * 0.009998); + let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across]; + let r = polygon(&corners.map(|p| (p.x, p.y))); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + holds(&r, FillRule::NonZero, c, 0.004999); + assert!(c.radius > 0.004999 * 0.99, "{c:?}"); + // 1,000 pt long and 0.0001 pt wide: also measured at the center. + let (along, across) = (u * 1000.0, v * 0.0001); + let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across]; + let r = polygon(&corners.map(|p| (p.x, p.y))); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}"); +} + +#[test] +fn a_search_past_its_cell_limit_is_too_complex() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let e = edges(&l.to_bezpath(), 0.005).unwrap(); + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + assert!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, MAX_INSCRIBED_CELLS), &mut 0).is_ok()); + assert_eq!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, 10), &mut 0), Err(InscribedError::TooComplex)); +} + +#[test] +fn an_outline_with_too_many_edges_is_too_complex() { + let zigzag: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, (i % 2) as f64)).chain([(0.0, -10.0)]).collect(); + let bp = polygon(&zigzag).to_bezpath(); + assert_eq!(edges(&bp, 0.005), Err(InscribedError::TooComplex)); + // Too many anchors are refused before the outline is resolved, even on a line that would + // otherwise fill no area. + let line: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, 0.0)).collect(); + assert_eq!(inscribed_circle(&polygon(&line), FillRule::NonZero), Err(InscribedError::TooComplex)); + assert_eq!(inscribed_circle(&polygon(&line[..1000]), FillRule::NonZero), Err(InscribedError::NoArea)); + assert_eq!(edges(&polygon(&zigzag[..1000]).to_bezpath(), 0.005).map(|e| e.len()), Ok(1000)); +} + +#[test] +fn a_search_past_its_work_limit_is_too_complex() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let e = edges(&l.to_bezpath(), 0.005).unwrap(); + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + assert!(search(&e, b, 0.01, &mut MAX_INSCRIBED_WORK.clone()).is_ok()); + assert_eq!(search(&e, b, 0.01, &mut (20 * e.len())), Err(InscribedError::TooComplex)); +} + +#[test] +fn searches_that_share_a_budget_stop_when_it_runs_out() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let mut work = MAX_INSCRIBED_WORK; + assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok()); + let one = MAX_INSCRIBED_WORK - work; + assert!(one > 0); + // Enough for one search and half of another: the first fits, the second runs out. + let mut work = one + one / 2; + assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok()); + assert!(work < one, "{work} left of {one}"); + assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex)); + // One distance short of a whole search: refused without measuring past the budget. + let mut work = one - 1; + assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex)); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured < one, "{measured} measured, budget {}", one - 1); +} + +#[test] +fn an_area_the_fill_rule_leaves_small_is_measured_to_its_own_scale() { + // Two identical 100 pt squares cancel under even-odd, leaving the small L of the test above: + // the outline's box is 100 pt across, the filled area's 0.1 pt. + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let l = polygon( + &[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0 + 50.0, y / 1000.0 + 50.0)), + ); + let all = PathData::new(sq.subpaths.iter().cloned().chain(sq.subpaths.iter().cloned()).chain(l.subpaths).collect()); + let c = inscribed_circle(&all, FillRule::EvenOdd).unwrap(); + let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}"); +} + +#[test] +fn a_shape_with_no_area_has_no_circle() { + let flat = polygon(&[(0.0, 0.0), (100.0, 0.0), (50.0, 0.0)]); + assert_eq!(inscribed_circle(&flat, FillRule::NonZero), Err(InscribedError::NoArea)); + assert_eq!(inscribed_circle(&PathData::default(), FillRule::NonZero), Err(InscribedError::NoArea)); +} diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index a18314309e..4a1369b9f0 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -114,6 +114,9 @@ pub(crate) struct Exporter<'a> { /// Overprinting characters' fills and strokes are drawn with Darken, as a separation's plate /// draws its overprinting fills and strokes ([`vectorcraft_doc::overprint::darken_overprints`]). pub darken_overprints: bool, + /// Document Setup → Discard White Overprint as it applies to the document's paints, read from + /// the document on first use ([`Self::paper_white`]). + discard_white: Option, /// An overprinting fill or stroke was drawn so. pub overprinted: bool, /// Characters with neither fill nor stroke, or whose fill is drawn as art (outlines filled diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index 498c12ca04..c1fc8defe7 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -64,6 +64,7 @@ impl<'a> Exporter<'a> { mask_art_left_out: false, overprint: false, darken_overprints: false, + discard_white: None, overprinted: false, invisible: false, inline_depth: 0, diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 6a511260a2..b3b5de36a4 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -523,12 +523,11 @@ impl Exporter<'_> { } /// Draw image `im` of node `n` colorized with `p` ([`Self::colorized_image`]), overprinting - /// when its color does ([`Node::colorize_overprints`]). A white color that is not a spot ink - /// ([`Document::spot_ink`]) and overprints (Discard White Overprint off) puts no ink down, so - /// it paints nothing. + /// when its color does ([`Node::colorize_overprints`]). A paper white color ([`Self::paper_white`]) + /// that overprints (Discard White Overprint off) puts no ink down, so it paints nothing. fn colorized(&mut self, s: &mut Surface, n: &Node, im: &vectorcraft_doc::ImageObject, p: &Paint) { let overprint = n.colorize_overprints() && self.overprint; - if overprint && !self.doc.setup.discard_white_overprint && !self.doc.spot_ink(p) && vectorcraft_doc::overprint::is_white(p) { + if overprint && !self.doc.setup.discard_white_overprint && self.paper_white(p) { return; } match self.colorized_image(im, p, !n.extras().pixelated, overprint) { @@ -634,11 +633,10 @@ impl Exporter<'_> { } /// Draw a fill or stroke of `paint` with `draw`: as a form marked to overprint when it - /// `overprints`, paints and overprints are kept (but not a white one with Discard White - /// Overprint, [`Document::discards_white_overprint`]). + /// `overprints`, paints and overprints are kept (but not a paper white one with Discard White + /// Overprint, [`Self::discards_white`]). pub(super) fn overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) { - let white = || self.doc.discards_white_overprint(paint); - if overprints && self.overprint && !paint.is_none() && !white() { + if overprints && self.overprint && !paint.is_none() && !self.discards_white(paint) { self.overprinted = true; crate::forms::form(s, Mark::Overprint, |s| draw(self, s)); } else { @@ -647,11 +645,10 @@ impl Exporter<'_> { } /// [`Self::overprinting`] for a character fill or stroke, which has no blend mode of its own: - /// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a white one - /// with Discard White Overprint). + /// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a paper + /// white one with Discard White Overprint). pub(super) fn char_overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) { - let white = self.doc.discards_white_overprint(paint); - if overprints && self.darken_overprints && !paint.is_none() && !white { + if overprints && self.darken_overprints && !paint.is_none() && !self.discards_white(paint) { s.push_blend_mode(krilla::blend::BlendMode::Darken); self.overprinting(s, overprints, paint, draw); s.pop(); @@ -660,6 +657,26 @@ impl Exporter<'_> { } } + /// Whether paint `p` knocks out where it overprints under Document Setup → Discard White + /// Overprint ([`vectorcraft_doc::overprint::DiscardWhite::discards`]). + fn discards_white(&mut self, p: &Paint) -> bool { + self.doc.setup.discard_white_overprint && self.paper_white(p) + } + + /// Whether paint `p` is paper white ([`vectorcraft_doc::overprint::DiscardWhite::paper_white`]): + /// white, and not a tint above 0% of one of the document's spot inks. The spot ink names are + /// read only for a white linked to a swatch. + fn paper_white(&mut self, p: &Paint) -> bool { + if !vectorcraft_doc::overprint::is_white(p) { + return false; + } + if !matches!(p, Paint::Solid { swatch: Some(_), .. }) { + return true; + } + let doc = self.doc; + self.discard_white.get_or_insert_with(|| vectorcraft_doc::overprint::DiscardWhite::of(doc)).paper_white(p) + } + /// 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 diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 66c5092391..38e46654cf 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -238,7 +238,7 @@ impl<'a> Separator<'a> { /// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and /// overprinting character fills and strokes, that put none of ink `plate` down leave its plate - /// as it is: they are drawn as nothing on it (white ones that `discard_white` knocks out + /// as it is: they are drawn as nothing on it (paper white ones that `discard_white` knocks out /// aside, [`DiscardWhite::discards`]). A writer without blending modes (PostScript) then keeps the ink below them, /// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on /// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting @@ -296,7 +296,7 @@ impl<'a> Separator<'a> { /// ink the plate below shows through instead of being knocked out. pub fn plate(&self, plate: &str) -> Document { let mut d = self.doc.clone(); - let discard_white = DiscardWhite::of(self.doc); + let discard_white = DiscardWhite::printing(&d, |n| !self.converts(n)); let mut colorized = BTreeSet::new(); let nodes = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.patterns.iter_mut().flat_map(|p| p.art.iter_mut())); for n in nodes { diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 1287c814d5..f26b1f95e0 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -399,6 +399,16 @@ fn a_white_spot_ink_image_overprints_with_discard_white_overprint() { assert_eq!(p.layers[0].children().unwrap()[0].visible, name == "White Ink", "{name}"); } } + // Printed as process inks, the white ink is paper white: the image knocks out on every plate. + let converted = serde_json::json!({"output": {"mode": "separations", "inks": [{"name": "White Ink", "convertToProcess": true}]}}); + let settings: PrintSettings = serde_json::from_value(converted).unwrap(); + for postscript in [true, false] { + let job = plan(&d, &PrintOptions { settings: settings.clone(), postscript, ..Default::default() }).unwrap(); + assert!(!job.plates.is_empty()); + for p in &job.plates { + assert!(p.layers[0].children().unwrap()[0].visible, "a converted white ink knocks out"); + } + } } /// An overprinting colorized image whose pixels don't take its color (a color preview of its diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index 9f8335c089..0f24a54faa 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -352,6 +352,28 @@ fn white_overprint_is_discarded_as_the_document_setup_says() { assert_eq!(overprints(&d, json!({})).1, 3); } +#[test] +fn a_white_spot_ink_keeps_overprinting_under_discard_white_overprint() { + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let mut d = overprinting(white); + d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + let paint = |d: &mut Document, p: &Paint| { + for n in std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().into_iter().flatten() { + let n = std::sync::Arc::make_mut(n); + if let Some(f) = n.appearance.fill_mut().filter(|f| f.overprint) { + f.paint = p.clone(); + } + if let NodeKind::Text(t) = &mut n.kind { + t.runs.iter_mut().for_each(|r| r.style.fill = p.clone()); + } + } + }; + paint(&mut d, &Paint::solid(white)); + assert_eq!(overprints(&d, json!({})).1, 1, "paper white fills and characters knock out"); + paint(&mut d, &Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }); + assert_eq!(overprints(&d, json!({})).1, 3, "a white spot ink overprints, characters too"); +} + #[test] fn pdf_a_overprint_mode_is_0() { let r = export(&overprinting(RED), json!({"standard": "pdfA2b", "compression": {"compressText": false}})); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 3995a45829..04e598a0a4 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch}; +use vectorcraft_color::{BlendMode, Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch}; use vectorcraft_doc::{Appearance, Artboard, Document, LayerColor, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::raster::render_region; @@ -903,6 +903,47 @@ fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscri assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill"); } +#[test] +fn a_white_spot_ink_keeps_overprinting_on_plates_and_in_simulated_composites() { + // With Discard White Overprint on (the default), a paper white square over cyan knocks the + // cyan out; one in a white spot ink overprints: it puts no cyan down, so the cyan plate draws + // nothing for it, and Simulate composites it with Darken. + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let square = |paint: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(paint, Paint::None, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + let mut d = over_cyan(vec![n]); + d.swatches.push(Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + d + }; + let (paper, spot) = (square(Paint::solid(white)), square(Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 })); + assert!(paper.setup.discard_white_overprint); + let cyan_fills = |d: &Document, output: serde_json::Value| { + let opts = PrintOptions { settings: settings(json!({"output": output})), ..Default::default() }; + let p = plan(d, &opts).unwrap(); + let mut count = 0; + p.plates[0].walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + let seps = json!({"mode": "separations"}); + assert_eq!((cyan_fills(&paper, seps.clone()), cyan_fills(&spot, seps)), (2, 1), "paper white knocks out; the spot white leaves the cyan"); + // The white ink printed as process inks is paper white. + let converted = json!({"mode": "separations", "inks": [{"name": "Opaque White", "convertToProcess": true}]}); + assert_eq!(cyan_fills(&spot, converted), 2, "a converted spot white knocks out"); + assert_eq!(cyan_fills(&spot, json!({"mode": "separations", "spotsToProcess": true})), 2, "so does one with every spot converted"); + let blends = |d: &Document| { + let opts = PrintOptions { settings: settings(json!({"advanced": {"overprints": "simulate"}})), ..Default::default() }; + let p = plan(d, &opts).unwrap(); + let mut out = vec![]; + p.doc.walk(|n| out.extend(n.appearance.fill().filter(|f| f.paint.color() == Some(white)).map(|f| f.blend))); + out + }; + assert_eq!((blends(&paper), blends(&spot)), (vec![BlendMode::Normal], vec![BlendMode::Darken])); +} + #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..dada995bb3 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -52,7 +52,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; +pub use manifest::{Budget, Command, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 899cdb9152..b9e36cfd24 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -34,6 +34,74 @@ pub const MAX_ALLOWED_COMMANDS: usize = 256; /// Longest command id a manifest's `commandAllowlist` names, in bytes. pub const MAX_ALLOWED_ID: usize = 128; +/// The menus a command's `menu` may name, each as its path of English menu labels. File, Window, +/// Help and the application menu are not among them, and neither are the submenus that list +/// files, fonts, panels or other plug-ins. +pub const MENU_PLACES: &[&[&str]] = &[ + &["Edit"], + &["Edit", "Edit Colors"], + &["Object"], + &["Object", "Transform"], + &["Object", "Arrange"], + &["Object", "Path"], + &["Object", "Compound Path"], + &["Object", "Clipping Mask"], + &["Type"], + &["Select"], + &["Select", "Same"], + &["Select", "Object"], + &["Effect"], + &["View"], +]; + +/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the +/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when +/// `after` is left out or names no built-in item there. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct MenuPlace { + pub path: &'static [&'static str], + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, +} + +impl MenuPlace { + /// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`. + fn read(v: &Value) -> std::result::Result { + let wrong_path = || { + let k = "menu.path"; + let places: Vec = + MENU_PLACES.iter().map(|p| format!("[{}]", p.iter().map(|l| format!("{l:?}")).collect::>().join(", "))).collect(); + format!("`{k}` must be one of {}", places.join(", ")) + }; + let Some(o) = v.as_object() else { + let key = "menu"; + return Err(format!("`{key}` must be an object")); + }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(format!("unknown key `{k}`; the keys here are {}", "path, after")); + } + let path: Vec<&str> = match o.get("path").and_then(Value::as_array) { + Some(path) => path.iter().map(Value::as_str).collect::>().ok_or_else(wrong_path)?, + None => return Err(wrong_path()), + }; + let path = *MENU_PLACES.iter().find(|p| **p == path.as_slice()).ok_or_else(wrong_path)?; + let key = "menu.after"; + let after = match o.get("after") { + None => None, + Some(Value::String(s)) => { + let trimmed = s.trim(); + if trimmed.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) { + return Err(format!("`{key}` must be 1-64 printable characters")); + } + Some(trimmed.to_string()) + } + Some(_) => return Err(format!("`{key}` must be a string")), + }; + Ok(MenuPlace { path, after }) + } +} + /// What a plug-in is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -223,9 +291,9 @@ pub struct Param { } /// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the -/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command -/// `plugin..`, and calls the plug-in's `vc_run` with `_context.command` set to -/// `id` and the parameters it declares. +/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it +/// as the command `plugin..`, and calls the plug-in's `vc_run` with +/// `_context.command` set to `id` and the parameters it declares. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Command { /// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest. @@ -236,6 +304,13 @@ pub struct Command { /// Parameters in declaration (dialog) order, declared as the manifest's own are. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] pub params: Vec<(String, Param)>, + /// The menu it is listed in instead of the plug-in's submenu (`menu`, read at + /// [`crate::permissions::MENU_API`] and later). + #[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")] + pub place: Option, + /// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them. + #[serde(skip)] + pub(crate) declared_menu: Vec, } impl Command { @@ -244,6 +319,18 @@ impl Command { pub fn shown_label(&self) -> String { crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME) } + + /// The label its menu item shows for plug-in `plugin_name`: [`Command::shown_label`], and for a + /// command placed in another menu, followed by the plug-in's name in parentheses. + pub fn menu_label(&self, plugin_name: &str) -> String { + match self.place { + None => self.shown_label(), + Some(_) => { + let name = crate::permissions::display_text(plugin_name.trim(), crate::permissions::MAX_SHOWN_NAME); + format!("{} ({name})", self.shown_label()) + } + } + } } impl From for Param { @@ -364,8 +451,9 @@ impl Manifest { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } - let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; + let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; man.validate()?; + man.read_places()?; Ok(man) } @@ -401,6 +489,31 @@ impl Manifest { self.commands.iter().find(|c| c.id == id) } + /// Reads each command's `menu` into its [`Command::place`] at + /// [`crate::permissions::MENU_API`] and later, and drops it below that level, where the key is + /// ignored. A `menu` that names a menu outside [`MENU_PLACES`], has the wrong shape or is given + /// twice is refused, and the error names the command. + fn read_places(&mut self) -> Result<()> { + let reads = self.api >= permissions::MENU_API; + for (i, c) in self.commands.iter_mut().enumerate() { + let menus = std::mem::take(&mut c.declared_menu); + if !reads { + continue; + } + let name = command_name(i, &c.id); + let place = match menus.as_slice() { + [] => continue, + [menu] => MenuPlace::read(menu), + _ => { + let key = "menu"; + Err(format!("duplicate field `{key}`")) + } + }; + c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?); + } + Ok(()) + } + /// Checks what the module declared: its id, name and text lengths, its extensions, a budget its /// kind may have (only a filter may be heavy), and each parameter and its dialog layout. fn validate(&self) -> Result<()> { @@ -809,7 +922,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu 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 (mut id, mut label, mut params, mut menu) = (None::, None::, None::, Vec::::new()); 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()))) }; @@ -828,6 +941,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu params = Some(map.next_value().map_err(|e| named(&id, &e))?); false } + // A repeated `menu` is refused only where the key is read ([`Manifest::parse`]). + "menu" => { + menu.push(map.next_value().map_err(|e| named(&id, &e))?); + false + } "id" | "label" | "params" => true, _ => { map.next_value::()?; @@ -844,7 +962,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu let Some(label) = label else { return Err(named(&Some(id), &"missing field `label`")); }; - Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() }) + Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu }) } } @@ -1220,7 +1338,7 @@ mod tests { } /// A filter or a live effect lists menu commands with their own parameters; a `menu` key is - /// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many + /// ignored at API level 1. A malformed entry, a bad or repeated id, a label that isn't printable and too many /// commands are refused, and the error names the command. #[test] fn commands_are_checked_and_errors_name_them() { @@ -1242,7 +1360,7 @@ mod tests { assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none()); let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap(); assert_eq!(effect.commands.len(), 1); - let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label(); + let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label(); assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe"); let many: Vec = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect(); @@ -1298,6 +1416,65 @@ mod tests { assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped"); } + /// At API level 2 a command's `menu` places it in one of [`MENU_PLACES`], after a named item or + /// at the end; a menu outside them (File, Help, Window, Edit › Preferences) or a `menu` of the + /// wrong shape is refused and the error names the command. At level 1 the key is ignored. + #[test] + fn a_command_menu_names_an_allowed_place() { + let with = |api: u32, menu: &str| { + format!( + r#"{{"id":"org.example.low","name":"Low Area","api":{api},"kind":"filter","commands":[{{"id":"low","label":"Low Area Closed Paths","menu":{menu}}}]}}"# + ) + }; + let m = Manifest::parse(with(2, r#"{"path":["Select"],"after":" Inverse "}"#).as_bytes()).unwrap(); + let c = &m.commands[0]; + assert_eq!(c.place, Some(MenuPlace { path: &["Select"], after: Some("Inverse".into()) })); + assert_eq!(c.menu_label(&m.name), "Low Area Closed Paths (Low Area)", "a placed item names its plug-in"); + assert_eq!(serde_json::to_value(&m).unwrap()["commands"][0]["menu"], json!({"path": ["Select"], "after": "Inverse"})); + let end = Manifest::parse(with(2, r#"{"path":["Select","Same"]}"#).as_bytes()).unwrap(); + assert_eq!(end.commands[0].place, Some(MenuPlace { path: &["Select", "Same"], after: None })); + + // API level 1 ignores the key, as hosts before it did: the command stays in the plug-in's submenu. + for menu in [r#"{"path":["Select"]}"#, r#""File""#, r#"{"path":["File"]}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#] { + let old = Manifest::parse(with(1, menu).as_bytes()).unwrap(); + assert_eq!(old.commands[0].place, None, "{menu}"); + assert_eq!(old.commands[0].menu_label(&old.name), "Low Area Closed Paths"); + } + + let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65)); + let padded = format!(r#"{{"path":["Select"],"after":" {} "}}"#, "x".repeat(64)); + for (menu, says) in [ + (r#"{"path":["File"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Help"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Window"]}"#, "`menu.path` must be one of"), + (r#"{"path":["VectorCraft"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Edit","Preferences"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Object","Plug-ins"]}"#, "`menu.path` must be one of"), + (r#"{"path":["select"]}"#, "`menu.path` must be one of"), + (r#"{"path":[]}"#, "`menu.path` must be one of"), + (r#"{"path":"Select"}"#, "`menu.path` must be one of"), + (r#"{"path":["Select",1]}"#, "`menu.path` must be one of"), + (r#"{"after":"Inverse"}"#, "`menu.path` must be one of"), + (r#""Select""#, "`menu` must be an object"), + (r#"["Select"]"#, "`menu` must be an object"), + (r#"{"path":["Select"],"before":"Inverse"}"#, "unknown key `before`"), + (r#"{"path":["Select"],"after":3}"#, "`menu.after` must be a string"), + (r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"), + (r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"],"after":"\nInverse\n"}"#, "`menu.after` must be 1-64 printable characters"), + (long.as_str(), "`menu.after` must be 1-64 printable characters"), + (padded.as_str(), "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"), + ] { + let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string(); + assert!(e.contains("command `low`") && e.contains(says), "{menu}: {e}"); + } + let twice = + r#"{"id":"a","name":"x","api":2,"kind":"filter","commands":[{"id":"x","label":"A","menu":{"path":["Edit"]},"menu":{"path":["Edit"]}}]}"#; + assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`")); + } + #[test] fn strings_and_number_lists_resolve_like_the_other_types() { let m = Manifest::parse( diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..a07b7a7a64 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -25,6 +25,10 @@ pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). pub const INPUTS_API: u32 = 2; +/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key +/// is ignored. +pub const MENU_API: u32 = 2; + /// Most permissions a manifest may list. pub const MAX_PERMISSIONS: usize = 16; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 8c0fe6f6da..b7950f0056 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -4,7 +4,7 @@ use wasmi::{ Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, ValType, WasmParams, WasmResults, }; -use wasmparser::{Validator, WasmFeatures}; +use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; @@ -42,12 +42,46 @@ const WASM_FEATURES: WasmFeatures = WasmFeatures::MUTABLE_GLOBAL .union(WasmFeatures::EXTENDED_CONST) .union(WasmFeatures::FLOATS); +/// The most parameters or results a function type may have: the limit `EnforcedLimits::strict()` +/// sets in wasmi 2.0.0. +const MAX_FUNC_TYPE_VALUES: usize = 32; + /// Validates `bytes` with only [`WASM_FEATURES`] on, before wasmi reads the module. A module that -/// uses any other proposal is refused with the validator's error, which names the proposal. +/// uses any other proposal is refused with the validator's error, which names the proposal. A +/// function type with more than [`MAX_FUNC_TYPE_VALUES`] parameters or results is refused before +/// any function body is validated. fn check_features(bytes: &[u8]) -> Result<()> { + check_func_types(bytes)?; Validator::new_with_features(WASM_FEATURES).validate_all(bytes).map(|_| ()).map_err(|e| Error::Module(e.to_string())) } +/// Refuses a function type in the type section with more than [`MAX_FUNC_TYPE_VALUES`] parameters +/// or results, with wasmi's message. Reading stops at the code section. A section that doesn't +/// parse is left to the validator, which reports it. +fn check_func_types(bytes: &[u8]) -> Result<()> { + for payload in Parser::new(0).parse_all(bytes) { + let types = match payload { + Ok(Payload::TypeSection(types)) => types, + Ok(Payload::CodeSectionStart { .. }) | Err(_) => return Ok(()), + Ok(_) => continue, + }; + for group in types { + let Ok(group) = group else { return Ok(()) }; + for ty in group.types() { + if let CompositeInnerType::Func(f) = &ty.composite_type.inner { + if f.params().len() > MAX_FUNC_TYPE_VALUES { + return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters"))); + } + if f.results().len() > MAX_FUNC_TYPE_VALUES { + return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results"))); + } + } + } + } + } + Ok(()) +} + /// Sets each WebAssembly proposal that wasmi's `Config` has a setter for in this build on or off, /// to match [`WASM_FEATURES`]. fn set_features(config: &mut Config) -> &mut Config { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 40f855a897..176828fae2 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -198,6 +198,23 @@ fn a_plugin_may_use_the_listed_webassembly_proposals_and_no_others() { } } +/// A function type with more than 32 parameters or results is refused before any function body is +/// validated: the module's extra function has an invalid body, and the error names the limit. A +/// type with 32 of each loads. +#[test] +fn a_function_type_past_32_values_is_refused_before_any_function_body_is_validated() { + let i32s = |n: usize| vec!["i32"; n].join(" "); + for (word, field) in [("parameters", "param"), ("results", "result")] { + let fits = module(MANIFEST, tpl::ECHO, &format!("(type (func ({field} {})))", i32s(32))); + assert!(Plugin::load(&fits, Limits::default()).is_ok(), "32 {word}"); + let past = module(MANIFEST, tpl::ECHO, &format!("(type (func ({field} {}))) (func (i32.add))", i32s(33))); + match Plugin::load(&past, Limits::default()) { + Err(Error::Module(m)) => assert_eq!(m, format!("a function type exceeds the limit of 32 {word}")), + other => panic!("33 {word}: {:?}", other.err()), + } + } +} + #[test] fn budgets_stop_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index 18e25a1e5a..ed38102f61 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -36,7 +36,7 @@ use vectorcraft_color::{Color, Paint, Swatch, SwatchGroup}; pub use vectorcraft_doc::inks::{Inks, Link, Plate, inks, map_document_colors, map_node_colors, plates, spot_color}; use vectorcraft_doc::inks::{StopPlates, map_node_inks, stop_inks}; use vectorcraft_doc::overprint::{DiscardWhite, darken_overprints}; -use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, Shared}; +use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, NodeKind, Shared}; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -392,6 +392,8 @@ impl Fit { /// one of them while they are kept. pub(crate) struct Prepared { inputs: Inputs, + /// The swatches `inputs.discard_white` was read from, while Discard White Overprint is on. + spots: Option, layers: (Vec>, Vec>), art: (Vec>, Vec>), } @@ -407,6 +409,14 @@ struct Inputs { plates: Option, } +/// The document's swatches and swatch groups, which name its spot inks ([`DiscardWhite`]): while +/// they are unchanged, the spot ink names are not read again. +#[derive(PartialEq)] +struct SpotSwatches { + swatches: Shared>, + groups: Shared>, +} + /// A hash of `images`' keys and the address of each one's bytes and whether they are a preview /// ([`ImageBlob::is_proxy`]): it changes when an image is added, removed or given other bytes, /// without reading any pixels. @@ -445,7 +455,7 @@ impl PartialEq for Plates { /// print it ([`plate_color`]). struct How<'a> { doc: &'a Document, - discard_white: DiscardWhite, + discard_white: &'a DiscardWhite, /// Separations Preview: the color settings, the proof setup and the visible plates. plates: Option<(&'a Cms, &'a ProofSetup, &'a [String])>, } @@ -454,12 +464,33 @@ impl How<'_> { /// Whether [`Self::apply`] can change `n`: with Separations Preview any node, else a node with /// an overprinting fill or stroke, or a colorized image whose color overprints. fn changes(&self, n: &Node) -> bool { - self.plates.is_some() || n.appearance.items.iter().any(|i| i.overprint()) || n.colorize_overprints() + self.plates.is_some() || n.appearance.items.iter().any(|i| i.overprint()) || n.colorize_overprints() || self.white_characters(n) } - /// Change the fills, strokes and other colors of node `a`, which holds no members. + /// Whether type `n` has an overprinting character fill or stroke that Discard White Overprint + /// knocks out ([`DiscardWhite::discards`]). + fn white_characters(&self, n: &Node) -> bool { + let white = |r: &vectorcraft_doc::TextRun| { + (r.style.overprint_fill && self.discard_white.discards(&r.style.fill)) + || (r.style.overprint_stroke && self.discard_white.discards(&r.style.stroke)) + }; + matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(white)) + } + + /// Change the fills, strokes and other colors of node `a`, which holds no members. Character + /// fills and strokes that Discard White Overprint knocks out stop overprinting, judged on + /// their own colors before Separations Preview maps them to the visible plates; the renderer + /// darkens the others. fn apply(&self, a: &mut Arc) { - darken_overprints(a, &self.discard_white, &self.doc.images); + darken_overprints(a, self.discard_white, &self.doc.images); + if self.white_characters(a) + && let NodeKind::Text(t) = &mut Arc::make_mut(a).kind + { + for r in &mut t.runs { + r.style.overprint_fill &= !self.discard_white.discards(&r.style.fill); + r.style.overprint_stroke &= !self.discard_white.discards(&r.style.stroke); + } + } if let Some((c, proof, visible)) = self.plates { map_node_inks(Arc::make_mut(a), &mut |col, sw, plates| plate_color(self.doc, c, proof, visible, col, sw, plates)); } @@ -477,8 +508,10 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op } let seps = opts.proof.as_ref().and_then(|p| p.separations.as_ref().map(|s| (p, s))); let c = cms::active(); + let spots = doc.setup.discard_white_overprint.then(|| SpotSwatches { swatches: doc.swatches.clone(), groups: doc.swatch_groups.clone() }); + let read = kept.as_ref().filter(|k| k.spots == spots).map(|k| k.inputs.discard_white.clone()); let inputs = Inputs { - discard_white: DiscardWhite::of(doc), + discard_white: read.unwrap_or_else(|| DiscardWhite::of(doc)), images: images_state(&doc.images), plates: seps.map(|(proof, _)| Plates { proof: proof.clone(), @@ -490,7 +523,7 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op }), }; let earlier = kept.take().filter(|k| k.inputs == inputs); - let how = How { doc, discard_white: inputs.discard_white.clone(), plates: seps.map(|(proof, visible)| (&*c, proof, visible.as_slice())) }; + let how = How { doc, discard_white: &inputs.discard_white, plates: seps.map(|(proof, visible)| (&*c, proof, visible.as_slice())) }; let none = (vec![], vec![]); let (layers, art) = earlier.as_ref().map_or((&none, &none), |k| (&k.layers, &k.art)); let made_layers = prepare_list(&doc.layers, &layers.0, &layers.1, &how); @@ -507,7 +540,7 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op } Cow::Owned(d) }; - *kept = Some(Prepared { inputs, layers: (doc.layers.clone(), made_layers), art: (symbol_art, made_art) }); + *kept = Some(Prepared { inputs, spots, layers: (doc.layers.clone(), made_layers), art: (symbol_art, made_art) }); out } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 2cdc41df3c..1b734b4522 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2205,6 +2205,74 @@ fn rasters_follow_the_view_options() { draws_as_new(&mut d, &isolated, &on_white, unchanged); } +/// Overprinting white characters over red in Overprint Preview: paper white knocks out while +/// Discard White Overprint is on and vanishes into the red when it is turned off; a white spot ink +/// overprints with it on. In Separations Preview paper white characters knock the plate out too. +#[test] +fn overprinting_white_characters_follow_discard_white_overprint() { + let _fonts = fonts_steady(); + use vectorcraft_doc::text::{CharStyle, TextObject}; + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let typed = || { + let mut d = Document::new(200.0, 100.0); + d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + let red = + filled(&mut d, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), vec![]); + let style = CharStyle { size: 50.0, fill: Paint::solid(white), overprint_fill: true, ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Hamburg", style)))); + with_art(d, vec![red, text]) + }; + let overprints = RenderOptions { overprint_preview: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + draws_as_new(&mut typed(), &overprints, &overprints, |d| d.setup.discard_white_overprint = false); + draws_as_new(&mut typed(), &overprints, &overprints, |d| { + let text = d.layers[0].children().unwrap()[1].id; + if let Some(NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) { + t.runs.iter_mut().for_each(|r| r.style.fill = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }); + } + }); + // Knocking out shows the white of the characters; overprinting leaves only the red. + let whites = |d: &Document, opts: &RenderOptions| { + Renderer::new().render(d, 200, 100, Affine::IDENTITY, opts).pixels.chunks(4).filter(|p| p[0] > 250 && p[1] > 250 && p[2] > 250).count() + }; + let mut d = typed(); + assert!(whites(&d, &overprints) > 0, "paper white knocks out"); + d.setup.discard_white_overprint = false; + assert_eq!(whites(&d, &overprints), 0, "with the option off it overprints"); + let mut d = typed(); + let text = d.layers[0].children().unwrap()[1].id; + if let Some(NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) { + t.runs.iter_mut().for_each(|r| r.style.fill = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }); + } + assert_eq!(whites(&d, &overprints), 0, "a white spot ink overprints"); + // Separations Preview: paper white characters over cyan knock the Cyan plate out. + let mut d = Document::new(200.0, 100.0); + let cyan = + filled(&mut d, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), vec![]); + let style = CharStyle { size: 50.0, fill: Paint::solid(white), overprint_fill: true, ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Hamburg", style)))); + let mut d = with_art(d, vec![cyan, text]); + let seps = RenderOptions { background: Some([255, 255, 255, 255]), ..proof_views(&["Cyan"]).1 }; + assert!(whites(&d, &seps) > 0, "paper white knocks the Cyan plate out"); + d.setup.discard_white_overprint = false; + assert_eq!(whites(&d, &seps), 0, "with the option off the cyan shows through"); + // Magenta characters over cyan, with only the Cyan plate shown: they put none of it down, so + // the cyan shows through them, as if they were not there. + let magenta = |with_text: bool| { + let mut d = Document::new(200.0, 100.0); + let cyan = filled( + &mut d, + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), + Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), + vec![], + ); + let style = CharStyle { size: 50.0, fill: Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), overprint_fill: true, ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Hamburg", style)))); + let d = with_art(d, if with_text { vec![cyan, text] } else { vec![cyan] }); + Renderer::new().render(&d, 200, 100, Affine::IDENTITY, &proof_views(&["Cyan"]).1).pixels + }; + assert!(magenta(true) == magenta(false), "the characters leave the cyan plate as it is"); +} + /// A document for the proof previews: a cyan square, a magenta circle over it whose black stroke /// overprints, a white square over the cyan one that overprints, a blurred rectangle in spot color /// `Spot`, and an instance of symbol `S`, a group holding a yellow square. @@ -2273,8 +2341,8 @@ fn proof_previews_keep_their_art_between_frames() { /// With Overprint Preview or Separations Preview on, a renderer draws what a new renderer draws /// after a change to the art or to what the previews read: an object recolored, Discard White -/// Overprint turned off, a symbol's art recolored (its instance shows the plates of the new art), -/// the spot color redefined, a spot color in a color group redefined, the Spot Colors option set +/// Overprint turned off, an overprinting white's swatch made a spot color, a symbol's art +/// recolored (its instance shows the plates of the new art), the spot color redefined, a spot color in a color group redefined, the Spot Colors option set /// to CMYK values, a plate hidden, Simulate Paper Color, another proof profile, and one preview /// after the other. #[test] @@ -2296,6 +2364,19 @@ fn proof_previews_draw_changes_as_a_new_renderer_does() { for opts in [&overprint, &separations] { draws_as_new(&mut proof_doc(), opts, opts, recolor_square); draws_as_new(&mut proof_doc(), opts, opts, |d| d.setup.discard_white_overprint = false); + // The overprinting white square's swatch becomes a spot color, a white ink. + let mut linked = proof_doc(); + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + linked.swatches.push(vectorcraft_color::Swatch { name: "White".into(), paint: Paint::solid(white), global: true, spot: false }); + let square = linked.layers[0].children().unwrap()[2].id; + if let Some(f) = linked.node_mut(square).unwrap().appearance.fill_mut() { + f.paint = Paint::Solid { color: white, swatch: Some("White".into()), tint: 1.0 }; + } + draws_as_new(&mut linked, opts, opts, |d| { + if let Some(s) = d.swatch_mut("White") { + s.spot = true; + } + }); } draws_as_new(&mut proof_doc(), &separations, &separations, recolor_symbol); draws_as_new(&mut proof_doc(), &separations, &separations, |d| { diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c0223aedb9..66eb645369 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -29,9 +29,9 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" }, ToolInfo { id: measure_inspect::ID, label: "Measure & Inspect Tool", shortcut: None, icon: "ruler" }, ToolInfo { id: parametric_shape::ID, label: "Parametric Shape Tool", shortcut: None, icon: "hexagon" }, - ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-rounded-rect" }, - ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-anchor" }, - ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-join" }, + ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-corner-tool" }, + ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-slide-anchor" }, + ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-shared-edge" }, ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "circle" }, ]; @@ -40,9 +40,10 @@ pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; -pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; +pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "dc-cube" }]; -pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }]; +pub const POLYGONAL_LASSO: &[ToolInfo] = + &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "dc-lasso-polygonal" }]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). @@ -128,7 +129,7 @@ mod tests { let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); assert_eq!(ids, ["lasso", id]); let info = crate::tool_info(id).expect("catalogued"); - assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso")); + assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso-enclosing")); assert_eq!(crate::tool_info("lasso").and_then(|t| t.shortcut), Some("Q"), "the Lasso keeps its shortcut"); assert_eq!(create(id).map(|tool| tool.id()), Some(id)); assert!(heading(id).is_none(), "not listed again under the add-on"); diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 2dc0774aa2..54b50f0aa6 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -27,7 +27,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[ t("lasso", "Lasso Tool", Some("Q"), "tool-lasso"), // Enclosing Lasso's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. - t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso"), + t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso-enclosing"), ], &[ t("pen", "Pen Tool", Some("P"), "tool-pen"), @@ -117,29 +117,29 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[t("dimension", "Dimension Tool", None, "tool-dimension")], &[ t("symbolSprayer", "Symbol Sprayer Tool", Some("Shift+S"), "tool-symbol"), - t("symbolShifter", "Symbol Shifter Tool", None, "tool-symbol"), - t("symbolScruncher", "Symbol Scruncher Tool", None, "tool-symbol"), - t("symbolSizer", "Symbol Sizer Tool", None, "tool-symbol"), - t("symbolSpinner", "Symbol Spinner Tool", None, "tool-symbol"), - t("symbolStainer", "Symbol Stainer Tool", None, "tool-symbol"), - t("symbolScreener", "Symbol Screener Tool", None, "tool-symbol"), - t("symbolStyler", "Symbol Styler Tool", None, "tool-symbol"), + t("symbolShifter", "Symbol Shifter Tool", None, "tool-symbol-shifter"), + t("symbolScruncher", "Symbol Scruncher Tool", None, "tool-symbol-scruncher"), + t("symbolSizer", "Symbol Sizer Tool", None, "tool-symbol-sizer"), + t("symbolSpinner", "Symbol Spinner Tool", None, "tool-symbol-spinner"), + t("symbolStainer", "Symbol Stainer Tool", None, "tool-symbol-stainer"), + t("symbolScreener", "Symbol Screener Tool", None, "tool-symbol-screener"), + t("symbolStyler", "Symbol Styler Tool", None, "tool-symbol-styler"), ], &[ t("columnGraph", "Column Graph Tool", Some("J"), "tool-graph"), - t("stackedColumnGraph", "Stacked Column Graph Tool", None, "tool-graph"), - t("barGraph", "Bar Graph Tool", None, "tool-graph"), - t("stackedBarGraph", "Stacked Bar Graph Tool", None, "tool-graph"), - t("lineGraph", "Line Graph Tool", None, "tool-graph"), - t("areaGraph", "Area Graph Tool", None, "tool-graph"), - t("scatterGraph", "Scatter Graph Tool", None, "tool-graph"), - t("pieGraph", "Pie Graph Tool", None, "tool-graph"), - t("radarGraph", "Radar Graph Tool", None, "tool-graph"), + t("stackedColumnGraph", "Stacked Column Graph Tool", None, "tool-graph-stacked-column"), + t("barGraph", "Bar Graph Tool", None, "tool-graph-bar"), + t("stackedBarGraph", "Stacked Bar Graph Tool", None, "tool-graph-stacked-bar"), + t("lineGraph", "Line Graph Tool", None, "tool-graph-line"), + t("areaGraph", "Area Graph Tool", None, "tool-graph-area"), + t("scatterGraph", "Scatter Graph Tool", None, "tool-graph-scatter"), + t("pieGraph", "Pie Graph Tool", None, "tool-graph-pie"), + t("radarGraph", "Radar Graph Tool", None, "tool-graph-radar"), ], &[ t("artboard", "Artboard Tool", Some("Shift+O"), "tool-artboard"), t("slice", "Slice Tool", Some("Shift+K"), "tool-slice"), - t("sliceSelection", "Slice Selection Tool", None, "tool-slice"), + t("sliceSelection", "Slice Selection Tool", None, "tool-slice-select"), ], &[ t("hand", "Hand Tool", Some("H"), "tool-hand"), diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c4481d6034..b3efac86bb 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -385,23 +385,26 @@ pub(crate) fn in_scope(doc: &vectorcraft_doc::Document, scope: Option, i /// shapes, its first child, are left out unless they are the isolated object (Construction mode), /// as clicks leave them out. fn walk_pickable<'a>(doc: &'a vectorcraft_doc::Document, scope: Option, mut f: impl FnMut(&'a Node)) { - fn walk<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { - f(n); - for c in n.children().into_iter().flatten().skip(usize::from(n.extras().shaper.is_some())) { - walk(c, f); - } - } if let Some(id) = scope && let Some(n) = doc.node(id) { - walk(n, &mut f); + walk_pickable_from(n, &mut f); } else if scope.is_none() { for l in &doc.layers { - walk(l, &mut f); + walk_pickable_from(l, &mut f); } } } +/// Visit `n` and the nodes inside it that Direct Selection may pick: a Shaper Group's original +/// shapes are left out ([`walk_pickable`]). +fn walk_pickable_from<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { + f(n); + for c in n.children().into_iter().flatten().skip(usize::from(n.extras().shaper.is_some())) { + walk_pickable_from(c, f); + } +} + /// The spines of the editable blends, topmost first: (blend, spine). pub(crate) fn spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { let mut v = vec![]; @@ -441,7 +444,12 @@ fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usiz /// The segment of a selected blend's spine passing within `tol` of `p`: (blend, segment, t, whether /// it is straight). pub(crate) fn hit_spine_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { - selected_spines(cx).into_iter().find_map(|(id, path)| { + spine_segment_in(&selected_spines(cx), p, tol) +} + +/// [`hit_spine_segment`] over spines already built. +fn spine_segment_in(spines: &[(NodeId, PathData)], p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { + spines.iter().find_map(|&(id, ref path)| { let (si, seg, t, _, dist) = path.nearest(p)?; (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) }) @@ -594,6 +602,57 @@ fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, us }) } +/// Is `p` on a point of a selected object that Direct Selection edits: a gradient mesh point, a +/// blend's spine point or segment, an anchor or the end of a direction handle, within the +/// selection tolerance? A selected group or compound path counts through the editable paths +/// inside it. A path's segments do not count: a Cmd press there with Select Behind on selects +/// the object behind, which a stroke-only path can only be pressed on. +pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { + if cx.selection.objects.is_empty() { + return false; + } + let tol = cx.point_tol(); + let seg_tol = cx.pick_tol(); + if hit_handle(cx, p, tol).is_some() || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() { + return true; + } + // The selected blends' spines are built once for both of their checks. + let spines = selected_spines(cx); + if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() { + return true; + } + // The editable paths' control bounds are listed once per document state and selection; a + // hover measures only the paths whose bounds it is near. + let boxes = crate::select::selected_part_boxes(cx, || { + let editable = cx.doc.editable(); + let mut v = vec![]; + for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + walk_pickable_from(root, &mut |n| { + if editable(n.id) + && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) + { + v.push((n.id, b)); + } + }); + } + v.into() + }); + boxes.iter().any(|&(id, b)| { + b.inflate(tol, tol).contains(p) + && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { + #[cfg(test)] + MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); + nearest_anchor(&pd, p, tol, None).is_some() + }) + }) +} + +#[cfg(test)] +thread_local! { + /// How many paths [`over_selected_part`] has measured on this thread. + static MEASURED_PARTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Is `p` within a press's reach of an anchor of type on a path's path? The anchor wins over a /// bracket standing on it (the end bracket on the last anchor, #3980); the bracket's stem above it /// still drags the bracket. diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 87dc281405..8b0983ba52 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2795,3 +2795,57 @@ fn a_marquee_skips_the_anchors_and_segments_of_guides_that_cannot_be_picked() { assert!(!crossed(&marquee(false, (140.0, 80.0), (160.0, 120.0))), "locked or hidden: no segment"); assert!(crossed(&marquee(true, (140.0, 80.0), (160.0, 120.0))), "shown and unlocked"); } + +/// A hover over a large selected group measures only the paths near the pointer when it asks +/// whether a Cmd press there lands on a part Direct Selection edits. +#[test] +fn over_selected_part_measures_only_the_paths_near_the_pointer() { + use vectorcraft_doc::{Appearance, Node}; + let mut d = vectorcraft_doc::Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let squares: Vec> = (0..400) + .map(|i| { + let (x, y) = (f64::from(i % 20) * 50.0, f64::from(i / 20) * 50.0); + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)); + std::sync::Arc::new(Node::path(d.alloc_id(), r, Appearance::default_art())) + }) + .collect(); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::group(g, squares)).unwrap(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(g); + let c = cx(&d, &picked, &p); + let before = MEASURED_PARTS.get(); + assert!(over_selected_part(&c, Point::new(520.0, 520.0)), "on a square's corner"); + assert!(!over_selected_part(&c, Point::new(535.0, 535.0)), "between the squares"); + let measured = MEASURED_PARTS.get() - before; + assert!(measured < 10, "{measured} of 400 paths measured"); +} + +/// The cursor, the canvas marks and a press each ask whether a Cmd press at the pointer selects +/// behind: while the document and the selection stay as they are, the selection's paths are +/// measured once for a point. +#[test] +fn select_behind_is_measured_once_for_a_point() { + use vectorcraft_doc::{Appearance, Node}; + let mut d = vectorcraft_doc::Document::new(400.0, 400.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)); + d.insert(Some(l), 0, Node::path(id, square, Appearance::default_art())).unwrap(); + // Below it, an object to select behind. + let back = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0)); + let back_id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(back_id, back, Appearance::default_art())).unwrap(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(id); + let memo = crate::select::PreviewMemo::default(); + let c = ToolContext { preview_memo: Some(&memo), select_behind: true, ..cx(&d, &picked, &p) }; + let at = Point::new(150.0, 150.0); + let before = MEASURED_PARTS.get(); + assert!(crate::select::selects_behind_at(&c, at), "inside the selected square, away from its anchors"); + assert!(crate::select::selects_behind_at(&c, at)); + assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only"); +} diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 2e5eb61491..abae4bc5ea 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -13,6 +13,13 @@ //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. //! +//! A handle stands beyond each end of the path being drawn, or, while none is, of the selected +//! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc +//! longer or shorter, as one undo step (`path.quickPenLength`): a line keeps its direction, and +//! an arc keeps its circle. The dragged end stays on its line or circle and does not snap to Smart +//! Guides. A click on a handle that does not drag is an ordinary click: it adds a point, closes the +//! path or starts one. +//! //! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a //! protractor around the arc's center: a tick across its circle every 15° from where the arc //! starts, a longer one every 90°, and one where it ends, with a small cross at the center. The @@ -31,12 +38,13 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, BezPath, PathData, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use length::EndPiece; /// The tool's id. pub const ID: &str = "quickPen"; @@ -49,6 +57,8 @@ pub const TURN_STEP: f64 = 15.0; /// The smallest and largest arc size (degrees). pub const MIN_TURN: f64 = 1.0; pub const MAX_TURN: f64 = 359.0; +/// The command that makes the line or arc at an end of a path longer or shorter. +pub const LENGTH_COMMAND: &str = "path.quickPenLength"; /// Degrees between the protractor's ticks, and the steps a continuous arc's sweep snaps to. pub const TICK_STEP: f64 = 15.0; /// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. @@ -57,6 +67,8 @@ const TICK_PX: f64 = 4.0; const CROSS_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; +/// Screen points a length handle stands beyond the end of the path, along the way it leaves the end. +pub const LENGTH_HANDLE_PX: f64 = 20.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight /// behind, is drawn as a line: no circle runs there in the path's direction. const STRAIGHT: f64 = 1e-6; @@ -361,6 +373,31 @@ impl Drawing { self.pieces.pop(); self.kept.pop(); } + + /// The last piece as `sp`, the subpath being drawn, holds it: the points from where it starts to + /// the end of the path. + fn last_tail(&self, sp: &SubPath) -> Option { + let from = self.kept.last()?.checked_sub(1)?; + Some(SubPath::new(sp.anchors.get_range(from..)?, false)) + } + + /// After the start of the path changed to a different number of points (`delta` more): keeps + /// the pieces that start at or after point `fixed` (counted before the change), which now start + /// `delta` points later, and forgets the others. + fn after_start_change(&mut self, fixed: usize, delta: isize) { + let first = self.kept.iter().position(|k| k.saturating_sub(1) >= fixed).unwrap_or(self.kept.len()); + self.pieces.drain(..first); + self.kept.drain(..first); + for k in &mut self.kept { + *k = k.saturating_add_signed(delta).max(1); + } + } + + /// Forgets every piece: the path as the document holds it is all the drawing goes on from. + fn clear_pieces(&mut self) { + self.pieces.clear(); + self.kept.clear(); + } } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo @@ -374,11 +411,45 @@ struct Press { end: Option<(Point, Point)>, } +/// A length handle: the line or arc at one end of subpath `si` of `id`, and where its handle is. +#[derive(Clone, Copy, Debug, PartialEq)] +struct LengthHandle { + id: NodeId, + si: usize, + at_start: bool, + piece: EndPiece, + at: Point, +} + +/// A length handle being dragged: the handle as the press found it, the length the drag has set, +/// whether the press has moved far enough to drag, and whether the drag began an undo step. +#[derive(Clone, Debug, PartialEq)] +struct LengthDrag { + handle: LengthHandle, + press: Point, + length: f64, + dragged: bool, + begun: bool, + /// The last piece of the path being drawn as it was before the drag, when the handle is at the + /// end of that piece: the drag changes the piece, so C and [ ] still shape it afterwards. + last: Option, + /// The subpath as the press found it, and its last piece as that subpath held it. + before: SubPath, + tail: Option, + /// The document's revision ([`ToolContext::revision`]) after the drag's last edit. A press + /// previews from the path as it found it, so once the revision differs, an edit was made + /// outside the tool and the drag previews no more. + revision: (u64, u64), + /// An edit made outside the tool ended the drag. + stale: bool, +} + pub struct QuickPenTool { action: Stroke, turn: f64, drawing: Option, press: Option, + length: Option, hover: Option, snap: DrawSnap, /// The pointer while it hovers, whether it lies on a Smart Guide target ([`Self::landed`]), and @@ -390,7 +461,16 @@ pub struct QuickPenTool { impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default(), pointer: None } + Self { + action: Stroke::Line, + turn: DEFAULT_TURN, + drawing: None, + press: None, + length: None, + hover: None, + snap: DrawSnap::default(), + pointer: None, + } } } @@ -400,6 +480,14 @@ fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { sel == [id] || cx.doc.parent_of(id).is_some_and(|p| sel == [p] && cx.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) } +/// Whether `sp` lies on the canvas: every point and handle does, or else the curve itself (its +/// extrema, not its handles) does. +pub fn on_canvas(sp: &SubPath) -> bool { + let within = |v: f64| v.abs() <= MAX_COORD; + sp.anchors.iter().all(|a| [a.p, a.h_in, a.h_out].iter().all(|q| within(q.x) && within(q.y))) + || PathData::new(vec![sp.clone()]).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].into_iter().all(within)) +} + fn point_tol(cx: &ToolContext) -> f64 { cx.tol(5.0).max(cx.point_tol()) } @@ -574,6 +662,38 @@ impl QuickPenTool { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } + // A press on a length handle waits to see whether it drags; one let go without dragging is + // the click `click` makes. + if let Some(handle) = self.length_handle_at(cx, p) + && let Some(before) = cx.doc.node(handle.id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(handle.si)).cloned() + { + let last = self.drawn_last_piece(cx, &handle); + let tail = last.and(self.drawing.as_ref()).and_then(|dr| dr.last_tail(&before)); + if let Some(dr) = self.drawing.as_mut().filter(|dr| dr.id == Some(handle.id)) { + dr.before_press = shared_node(cx.doc, handle.id).cloned(); + } + let drag = LengthDrag { + handle, + press: p, + length: handle.piece.length, + dragged: false, + begun: false, + last, + before, + tail, + revision: cx.revision, + stale: false, + }; + // The hover's Smart Guides do not follow a length drag. + self.snap.clear(); + self.length = Some(drag); + return vec![]; + } + self.click(cx, p) + } + + /// What a press away from a length handle, or a click on one, draws. + fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -645,6 +765,211 @@ impl QuickPenTool { SubPath::new(added, false).to_bezpath_into(&mut bp); Some(bp) } + + /// The length handles: at both ends of the path being drawn, or, while none is, of each open + /// subpath of the one editable path selected, wherever the end is a line or an arc. + fn length_handles(&self, cx: &ToolContext) -> Vec { + // At the end of the path being drawn, the handle changes the last piece drawn alone, even + // where the piece before it goes on around the same circle. + let mut tail = None; + let subpaths: Vec<(NodeId, usize, &SubPath)> = if let Some((id, sp)) = self.active(cx) { + tail = self.drawing.as_ref().and_then(|dr| dr.last_tail(sp)); + self.drawing.as_ref().map(|dr| (id, dr.si, sp)).into_iter().collect() + } else if let [id] = cx.selection.objects.as_slice() + && cx.doc.is_editable(*id) + && let Some(node) = cx.doc.node(*id) + { + // A compound path shows the handles of the paths it holds. + let members: Vec<&Node> = if matches!(node.kind, NodeKind::Compound { .. }) { + let editable = cx.doc.editable(); + node.editing_children().iter().map(|c| c.as_ref()).filter(|c| editable(c.id)).collect() + } else { + vec![node] + }; + members + .into_iter() + .filter_map(|n| Some((n.id, n.path_data()?))) + .flat_map(|(id, pd)| pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed).map(move |(si, sp)| (id, si, sp))) + .collect() + } else { + vec![] + }; + let off = cx.tol(LENGTH_HANDLE_PX); + let mut out = vec![]; + for (id, si, sp) in subpaths { + for at_start in [false, true] { + let piece = match &tail { + Some(t) if !at_start => length::end_piece(t, false), + _ => length::end_piece(sp, at_start), + }; + if let Some(piece) = piece { + out.push(LengthHandle { id, si, at_start, piece, at: piece.end + piece.out * off }); + } + } + } + out + } + + /// The length handle under `p`, the nearest when several are. + fn length_handle_at(&self, cx: &ToolContext, p: Point) -> Option { + let tol = point_tol(cx); + self.length_handles(cx).into_iter().filter(|h| h.at.distance(p) <= tol).min_by(|a, b| a.at.distance(p).total_cmp(&b.at.distance(p))) + } + + /// The last piece of the path being drawn, when `handle` is at its end and the piece is the + /// line or arc there. + fn drawn_last_piece(&self, cx: &ToolContext, handle: &LengthHandle) -> Option { + let (id, sp) = self.active(cx)?; + let dr = self.drawing.as_ref()?; + if handle.at_start || id != handle.id || dr.si != handle.si { + return None; + } + let last = dr.pieces.last()?; + let from = sp.anchors.get(dr.kept.last()?.checked_sub(1)?)?.p; + let same = match handle.piece.shape { + length::EndShape::Line => last.stroke == Stroke::Line, + length::EndShape::Arc { .. } => last.stroke != Stroke::Line, + }; + (same && from.distance(handle.piece.fixed) <= 1e-9).then_some(*last) + } + + /// Puts back the last piece a length drag changed, when the drag is taken back. + fn restore_last_piece(&mut self, drag: &LengthDrag) { + if let (Some(last), Some(l)) = (drag.last, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *l = last; + } + } + + /// `path.quickPenLength`'s params for the length drag. + fn length_params(drag: &LengthDrag) -> Value { + let h = &drag.handle; + json!({"id": h.id.0, "subpath": h.si, "end": if h.at_start { "start" } else { "end" }, "length": drag.length}) + } + + /// Moves the end of the line or arc a length drag changes to follow the pointer at `p` and + /// previews it. An edit made outside the tool since the last preview ends the drag instead: the + /// press then commits the document as it is. + fn length_drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec { + let Some(mut drag) = self.length.clone() else { return vec![] }; + if drag.stale { + return vec![]; + } + if drag.revision != cx.revision { + drag.stale = true; + self.length = Some(drag); + return vec![]; + } + if !drag.dragged && p.distance(drag.press) < cx.tol(DRAG_PX) { + return vec![]; + } + drag.dragged = true; + self.length = Some(drag.clone()); + // The end follows the pointer, as far behind it as the press was. + let piece = drag.handle.piece; + let mut length = piece.length_dragged(drag.press, p, drag.length); + // The last piece drawn goes on being a piece of the drawing, drawn again to its new + // end; an arc piece keeps an arc size of at least 1°. + let mut redrawn = None; + let changed = if let (Some(last), Some(tail)) = (drag.last, drag.tail.as_ref()) { + if let length::EndShape::Arc { radius, .. } = piece.shape { + length = length.max(MIN_TURN.to_radians() * radius); + } + let changed = length::with_length(tail, false, length); + redrawn = changed.as_ref().and_then(|sp| sp.anchors.last().map(|a| a.p)).map(|to| { + let turn = match piece.shape { + length::EndShape::Arc { radius, .. } => (length / radius).to_degrees().clamp(MIN_TURN, MAX_TURN), + length::EndShape::Line => last.turn, + }; + Piece { to, turn, ..last } + }); + changed + } else { + length::with_length(&drag.before, drag.handle.at_start, length) + }; + // A length that would take the path past the canvas is not taken: the end stays + // where the drag last put it. + if !changed.is_some_and(|sp| on_canvas(&sp)) { + return vec![]; + } + // A length the end already has changes nothing: no preview, and no undo step before the + // first change. + if (length - drag.length).abs() <= 1e-12 * length.max(1.0) { + return vec![]; + } + let mut out = vec![]; + if !drag.begun { + drag.begun = true; + out.push(Action::Begin("Quick Pen".into())); + } + drag.length = length; + match redrawn { + Some(pc) => { + if let Some(l) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + *l = pc; + } + out.push(Action::Preview(COMMAND.into(), self.params(false))); + } + None => out.push(Action::Preview(LENGTH_COMMAND.into(), Self::length_params(&drag))), + } + // The drawing sees the path as the preview left it. + out.push(drawn()); + self.length = Some(drag); + out + } + + /// A length drag let go: once it changed the path being drawn, the drawing goes on from the + /// changed path, which `path.quickPenLength` made from the same points. A press on a handle let + /// go without dragging is a click there. After an edit made outside the tool, the path being + /// drawn ends and the document stays as that edit left it. + fn end_length_drag(&mut self, cx: &ToolContext) -> Vec { + let Some(drag) = self.length.take() else { return vec![] }; + if drag.stale || drag.revision != cx.revision { + self.drawing = None; + self.snap.clear(); + return if drag.begun { vec![Action::Commit] } else { vec![] }; + } + if !drag.dragged { + let mut out = self.click(cx, drag.press); + if self.press.take().is_some_and(|pr| pr.begun) { + out.extend([Action::Commit, Action::Notify(PLACED.into())]); + } + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; + } + self.snap.clear(); + return out; + } + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; + } + if !drag.begun { + return vec![]; + } + // A drag that ends at the length the piece started with is taken back, as Escape takes it + // back: it records no undo step. + let changed = (drag.length - drag.handle.piece.length).abs() > 1e-9 * drag.length.max(1.0); + if !changed { + self.restore_last_piece(&drag); + return vec![Action::Cancel, drawn()]; + } + // A drag that drew the last piece again has already changed the drawing. + if drag.last.is_none() + && let Some(dr) = self.drawing.as_mut() + && dr.id == Some(drag.handle.id) + && dr.si == drag.handle.si + { + // The pieces that start at or after the fixed end of a changed start still draw as they + // did, on the points the document holds before them; every other piece is forgotten. + let new_len = length::with_length(&drag.before, drag.handle.at_start, drag.length).map(|sp| sp.anchors.len()); + let fixed = drag.before.anchors.iter().position(|a| a.p.distance(drag.handle.piece.fixed) <= 1e-9); + match (drag.handle.at_start, new_len, fixed) { + (true, Some(new_len), Some(fixed)) => dr.after_start_change(fixed, new_len as isize - drag.before.anchors.len() as isize), + (_, None, _) => self.drawing = None, + _ => dr.clear_pieces(), + } + } + vec![Action::Commit, drawn()] + } } impl Tool for QuickPenTool { @@ -653,7 +978,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() + self.press.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -667,7 +992,7 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() { + if self.press.is_some() || self.length.is_some() { return vec![]; } // The hover shows again when the pointer moves after the press: the point the press @@ -680,6 +1005,7 @@ impl Tool for QuickPenTool { self.pointer = None; self.press_down(cx, p) } + PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { @@ -693,6 +1019,13 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if self.length.is_some() { + self.snap.clear(); + // The end goes where the press is let go, also past the last drag. + let mut out = self.length_drag_to(cx, p); + out.extend(self.end_length_drag(cx)); + return out; + } let out = match self.press { // The piece ends where the press is let go, also past the last drag. Some(pr) if pr.begun => { @@ -721,6 +1054,11 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == DRAWN + && let Some(drag) = self.length.as_mut() + { + drag.revision = cx.revision; + } let Some(dr) = self.drawing.as_mut() else { return }; if what == "created" && let [id] = cx.selection.objects.as_slice() @@ -757,7 +1095,7 @@ impl Tool for QuickPenTool { fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { match key { - ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(), + ToolKey::Letter('c') => self.length.is_some() || self.last_sharp_arc(cx).is_some(), ToolKey::BracketLeft | ToolKey::BracketRight | ToolKey::AltTap => true, ToolKey::Enter => self.active(cx).is_some(), _ => false, @@ -768,6 +1106,18 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + if let Some(drag) = self.length.take() { + self.restore_last_piece(&drag); + if let Some(dr) = self.drawing.as_mut() { + let before = dr.before_press.take(); + if drag.begun { + match (dr.id.and_then(|id| cx.doc.node(id)), before) { + (Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before), + _ => self.drawing = None, + } + } + } + } if self.press.take().is_some_and(|pr| pr.begun) && let Some(dr) = self.drawing.as_mut() { @@ -783,6 +1133,31 @@ impl Tool for QuickPenTool { fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { + // Escape during a length drag takes the drag back and leaves the path being drawn; Enter + // does nothing until the drag ends. + ToolKey::Escape if self.length.is_some() => match self.length.take() { + Some(drag) => { + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; + } + if !drag.begun { + return vec![]; + } + // An edit made outside the tool since the last preview stays: the cancel would + // take it back with the drag. + if drag.stale || drag.revision != cx.revision { + self.drawing = None; + return vec![Action::Commit]; + } + self.restore_last_piece(&drag); + // The drawing sees the path as the cancel leaves it. + vec![Action::Cancel, drawn()] + } + None => vec![], + }, + ToolKey::Enter if self.length.is_some() => vec![], + // C and [ ] change the last piece once the drag has ended. + ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], ToolKey::Escape | ToolKey::Enter => self.end(), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { @@ -834,6 +1209,9 @@ impl Tool for QuickPenTool { fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + if self.length.take().is_some_and(|drag| drag.begun) { + return vec![Action::Commit]; + } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], _ => vec![], @@ -841,7 +1219,7 @@ impl Tool for QuickPenTool { } fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { - if self.press.is_none() { + if self.press.is_none() && self.length.is_none() { self.drawing = None; } vec![] @@ -860,6 +1238,22 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { // A stale hover's Smart Guides go with its preview. let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; + // The length handles: a line from each end to a handle circle beyond it; during a drag, the + // one being dragged, where the changed end is. + let handles: Vec<(Point, Point)> = match &self.length { + Some(drag) => { + let h = &drag.handle; + let sp = cx.doc.node(h.id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(h.si)); + let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); + piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() + } + None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None => vec![], + }; + for &(a, b) in &handles { + o.push(Overlay::Line { a, b, color: FEEDBACK, dashed: false }); + o.push(Overlay::Handle { p: b, color: FEEDBACK }); + } let Some((id, sp)) = self.active(cx) else { return o }; let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; // The arc being drawn: the piece a press drags, or the piece the next click adds while the @@ -877,7 +1271,10 @@ impl Tool for QuickPenTool { o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: FEEDBACK, dashed: false }); o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: FEEDBACK, dashed: false }); } + let on_handle = self.hover.is_some_and(|h| handles.iter().any(|&(_, at)| at.distance(h) <= point_tol(cx))); if self.press.is_none() + && self.length.is_none() + && !on_handle && !self.hover_stale(cx) && let Some(h) = end.or(self.hover) { @@ -902,6 +1299,9 @@ impl Tool for QuickPenTool { fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { let tol = point_tol(cx); + if self.length.is_some() || self.length_handle_at(cx, p).is_some() { + return Cursor::Move; + } if let Some((_, sp)) = self.active(cx) { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; @@ -938,5 +1338,7 @@ impl Tool for QuickPenTool { } } +pub mod length; + #[cfg(test)] mod tests; diff --git a/crates/tools/src/quickpen/length.rs b/crates/tools/src/quickpen/length.rs new file mode 100644 index 0000000000..a32751d120 --- /dev/null +++ b/crates/tools/src/quickpen/length.rs @@ -0,0 +1,246 @@ +//! The line or arc at an end of an open path, and that line or arc made longer or shorter: what the +//! Quick Pen's length handles drag and `path.quickPenLength` sets. +//! +//! The piece at an end is the path's last segment when it is straight, or the run of segments +//! before the end that lie on one circle and turn the same way (an arc drawn as several cubic +//! segments of at most 90° each). A line keeps its other point and its direction; an arc keeps its +//! other point, its circle and the way it turns, and its sweep grows or shrinks. + +use std::f64::consts::{FRAC_PI_2, PI}; + +use vectorcraft_geom::{Anchor, Point, SubPath, Vec2}; + +use super::{MAX_TURN, rot, unit}; + +/// The shortest length a line or arc can be set to (points). +pub const MIN_LENGTH: f64 = 0.001; +/// The longest a line can be set to (points). +pub const MAX_LINE_LENGTH: f64 = 1e6; +/// How close, relative to the radius, the points and handles of a segment must be to a circular +/// arc's for the segment to count as one. +const ARC_TOL: f64 = 1e-6; +/// How far, relative to the segment's length, a straight segment's handles may lie off its line. +const LINE_TOL: f64 = 1e-9; + +/// What the piece at an end is. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum EndShape { + Line, + /// An arc around `center` of `radius`, turning through `sweep` radians from the piece's other + /// point to the end (positive as [`rot`] turns). + Arc { + center: Point, + radius: f64, + sweep: f64, + }, +} + +/// The line or arc at one end of an open subpath. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EndPiece { + pub shape: EndShape, + /// The point the piece leaves from, which stays where it is. + pub fixed: Point, + /// The end of the path. + pub end: Point, + /// The direction the path leaves the end in, away from the rest of the path. + pub out: Vec2, + /// The piece's length along the line or the arc. + pub length: f64, +} + +impl EndPiece { + /// The longest length the piece can be set to: for an arc, a sweep of 359°. + pub fn max_length(&self) -> f64 { + match self.shape { + EndShape::Line => MAX_LINE_LENGTH, + EndShape::Arc { radius, .. } => MAX_TURN.to_radians() * radius, + } + } + + /// The length the piece takes when its end is dragged to `p`: for a line, how far along its + /// direction `p` lies; for an arc, the arc to the angle `p` lies at around its center, taken + /// nearest to `near` (the length before), so a drag goes on past a full half turn. Kept within + /// [`MIN_LENGTH`] and [`Self::max_length`]. + pub fn length_toward(&self, p: Point, near: f64) -> f64 { + let l = match self.shape { + EndShape::Line => { + let Some(u) = unit(self.end - self.fixed) else { return self.length }; + u.dot(p - self.fixed) + } + EndShape::Arc { center, radius, sweep } => { + let (a, b) = (self.fixed - center, p - center); + if b.hypot() <= 1e-12 || radius <= 0.0 { + return near; + } + // The angle from the fixed point to `p`, in the way the arc turns, 0 to 2π. + let phi = a.cross(b).atan2(a.dot(b)) * sweep.signum(); + let phi = if phi < 0.0 { phi + 2.0 * PI } else { phi }; + let at = near / radius; + let turns = ((at - phi) / (2.0 * PI)).round(); + (phi + turns * 2.0 * PI) * radius + } + }; + l.clamp(MIN_LENGTH, self.max_length()) + } + + /// The length the piece takes when its handle, pressed at `press`, is dragged to `p`: the end + /// moves with the pointer and stays where it was relative to it. On a line the end keeps the + /// offset the press had from it; on an arc the offset turns with the pointer around the center, + /// so the end stays the same angle behind the pointer at any radius and zoom. + pub fn length_dragged(&self, press: Point, p: Point, near: f64) -> f64 { + let to = match self.shape { + EndShape::Line => p - (press - self.end), + EndShape::Arc { center, .. } => { + let (a, b) = (press - center, self.end - center); + center + rot(p - center, a.cross(b).atan2(a.dot(b))) + } + }; + self.length_toward(to, near) + } +} + +/// `sp`, or a copy reversed when `at_start`, so the end in question is the last point. +fn oriented(sp: &SubPath, at_start: bool) -> SubPath { + let mut o = sp.clone(); + if at_start { + o.reverse(); + } + o +} + +/// The anchor `i` places from the end in question of `sp` (0 is that end), as it would be in `sp` +/// reversed when `at_start`, read without copying the subpath. +fn from_end(sp: &SubPath, at_start: bool, i: usize) -> Option { + if at_start { sp.anchors.get(i).map(Anchor::reversed) } else { sp.anchors.get(sp.anchors.len().checked_sub(i + 1)?).copied() } +} + +/// Does the cubic from `a` to `b` run straight along its chord? +fn straight(a: &Anchor, b: &Anchor) -> bool { + let c = b.p - a.p; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return false; + } + let u = c / l; + let (h1, h2) = (a.h_out - a.p, b.p - b.h_in); + let along = |h: Vec2| u.cross(h).abs() <= LINE_TOL * l && (-LINE_TOL * l..=l * (1.0 + LINE_TOL)).contains(&u.dot(h)); + along(h1) && along(h2) +} + +/// The circle and signed turn of the cubic from `a` to `b` when it is a circular arc as the Quick +/// Pen draws one (handles along the tangents, each 4/3·tan(turn/4) of the radius long). +fn arc_of(a: &Anchor, b: &Anchor) -> Option<(Point, f64, f64)> { + let (d0, d1) = (a.h_out - a.p, b.p - b.h_in); + let (t0, t1) = (unit(d0)?, unit(d1)?); + let turn = t0.cross(t1).atan2(t0.dot(t1)); + if turn.abs() <= 1e-9 || turn.abs() > FRAC_PI_2 + 1e-6 { + return None; + } + let chord = (b.p - a.p).hypot(); + let r = chord / (2.0 * (turn.abs() / 2.0).sin()); + // An arc whose 359° is shorter than the shortest length has no length to set. + if !r.is_finite() || MAX_TURN.to_radians() * r < MIN_LENGTH { + return None; + } + let center = a.p + rot(t0, FRAC_PI_2 * turn.signum()) * r; + let k = 4.0 / 3.0 * (turn.abs() / 4.0).tan() * r; + let tol = ARC_TOL * r.max(1.0); + // The end lies where the turn takes the start around the circle, not only at the right distance. + let on = + (center + rot(a.p - center, turn)).distance(b.p) <= tol && (d0.hypot() - k).abs() <= tol * 100.0 && (d1.hypot() - k).abs() <= tol * 100.0; + on.then_some((center, r, turn)) +} + +/// The line or arc at the end (`at_start`: the start) of the open subpath `sp`, or none for a +/// closed subpath, one of fewer than two points, or an end whose last segment is neither straight +/// nor a circular arc. +pub fn end_piece(sp: &SubPath, at_start: bool) -> Option { + if sp.closed { + return None; + } + last_piece(sp, at_start).map(|(piece, _)| piece) +} + +/// The line or arc that ends at the end (`at_start`: the start) of `sp`, with how many points back +/// from that end the point it leaves from is. It reads only the points of the piece. +fn last_piece(sp: &SubPath, at_start: bool) -> Option<(EndPiece, usize)> { + let at = |i: usize| from_end(sp, at_start, i); + let last = at(0)?; + let prev = at(1)?; + if straight(&prev, &last) { + let out = unit(last.p - prev.p)?; + return Some((EndPiece { shape: EndShape::Line, fixed: prev.p, end: last.p, out, length: prev.p.distance(last.p) }, 1)); + } + let (center, radius, mut sweep) = arc_of(&prev, &last)?; + let mut back = 1; + while let (Some(a), Some(b)) = (at(back + 1), at(back)) { + let Some((c, r, t)) = arc_of(&a, &b) else { break }; + let tol = ARC_TOL * radius.max(1.0); + if c.distance(center) > tol || (r - radius).abs() > tol || t.signum() != sweep.signum() || (sweep + t).abs() >= 2.0 * PI - 1e-9 { + break; + } + sweep += t; + back += 1; + } + let fixed = at(back)?.p; + let out = unit(last.p - last.h_in)?; + Some((EndPiece { shape: EndShape::Arc { center, radius, sweep }, fixed, end: last.p, out, length: sweep.abs() * radius }, back)) +} + +/// `sp` with the line or arc at the end (`at_start`: the start) made `length` long, or none when +/// that end is not a line or an arc ([`end_piece`]) or `length` is outside [`MIN_LENGTH`] to the +/// piece's [`EndPiece::max_length`]. A line keeps its other point and its direction, and its handles +/// scale with it. An arc keeps its other point, its circle and the way it turns, drawn again as +/// segments of at most 90° each; the point it leaves from keeps its kind and incoming handle. +pub fn with_length(sp: &SubPath, at_start: bool, length: f64) -> Option { + if sp.closed { + return None; + } + let (piece, back) = last_piece(sp, at_start)?; + if !(MIN_LENGTH..=piece.max_length()).contains(&length) { + return None; + } + let mut o = oriented(sp, at_start); + let n = o.anchors.len(); + let from = n.checked_sub(back + 1)?; + let last = *o.anchors.get(n - 1)?; + match piece.shape { + EndShape::Line => { + let ratio = length / piece.length; + let to = piece.fixed + piece.out * length; + let prev = o.anchors.get_mut(n - 2)?; + prev.h_out = prev.p + (prev.h_out - prev.p) * ratio; + let end = o.anchors.get_mut(n - 1)?; + *end = Anchor { p: to, h_in: to + (last.h_in - last.p) * ratio, h_out: to + (last.h_out - last.p), kind: last.kind }; + } + EndShape::Arc { center, radius, sweep } => { + let s = length / radius * sweep.signum(); + let start = *o.anchors.get(from)?; + let t0 = unit(start.h_out - start.p)?; + let segs = ((s.abs() / FRAC_PI_2) - 1e-9).ceil().max(1.0) as usize; + let step = s / segs as f64; + let k = 4.0 / 3.0 * (step.abs() / 4.0).tan() * radius; + o.anchors.truncate(from + 1); + if let Some(a) = o.anchors.last_mut() { + a.h_out = a.p + t0 * k; + } + let r0 = start.p - center; + for i in 1..=segs { + let turned = step * i as f64; + let q = center + rot(r0, turned); + let t = rot(t0, turned); + let mut an = Anchor::with_handles(q, q - t * k, q + t * k); + if i == segs { + an.h_out = q + rot(last.h_out - last.p, s - sweep); + an.kind = last.kind; + } + o.anchors.push(an); + } + } + } + if at_start { + o.reverse(); + } + Some(o) +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 1319948423..ce6fd5ec4b 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -315,3 +315,128 @@ fn the_rubber_band_is_the_next_piece() { } } } + +/// A straight end is a line: at the end it keeps its other point and direction, at the start it +/// keeps the end; the points between stay. +#[test] +fn a_line_end_takes_a_new_length_along_its_direction() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(100.0, 50.0, Stroke::Line)], false); + let end = length::end_piece(&sp, false).unwrap(); + assert_eq!(end.shape, length::EndShape::Line); + assert_eq!((end.fixed, end.end, end.length), (pt(100.0, 0.0), pt(100.0, 50.0), 50.0)); + assert!((end.out - Vec2::new(0.0, 1.0)).hypot() < 1e-12); + let longer = length::with_length(&sp, false, 80.0).unwrap(); + let pts: Vec = longer.anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [pt(0.0, 0.0), pt(100.0, 0.0), pt(100.0, 80.0)]); + let shorter = length::with_length(&sp, true, 40.0).unwrap(); + let pts: Vec = shorter.anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [pt(60.0, 0.0), pt(100.0, 0.0), pt(100.0, 50.0)]); + assert_eq!(length::with_length(&sp, false, 0.0), None, "too short"); + assert_eq!(length::with_length(&sp, false, length::MAX_LINE_LENGTH * 2.0), None, "too long"); + // Dragged, the length is how far along the line the pointer is, at least the shortest. + assert_eq!(end.length_toward(pt(130.0, 70.0), 50.0), 70.0); + assert_eq!(end.length_toward(pt(100.0, -30.0), 50.0), length::MIN_LENGTH); +} + +/// A half circle drawn as two quarter segments is one arc: a longer one goes around the same circle +/// from the same start, in three segments for 270°, and a shorter one is one segment. +#[test] +fn an_arc_end_keeps_its_circle() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(200.0, 0.0, Stroke::SharpArc)], false); + let end = length::end_piece(&sp, false).unwrap(); + let length::EndShape::Arc { center, radius, sweep } = end.shape else { panic!("an arc: {end:?}") }; + assert!(center.distance(pt(150.0, 0.0)) < 1e-9 && (radius - 50.0).abs() < 1e-9); + assert!((sweep.abs() - PI).abs() < 1e-9); + assert_eq!(end.fixed, pt(100.0, 0.0), "the arc starts where the line ends"); + let three_quarters = length::with_length(&sp, false, 1.5 * PI * 50.0).unwrap(); + assert_eq!(three_quarters.anchors.len(), 5); + assert!(on_circle(&three_quarters, 1, pt(150.0, 0.0), 50.0)); + assert!(three_quarters.anchors.last().unwrap().p.distance(pt(150.0, 50.0)) < 1e-9, "a quarter more, below the center"); + assert_eq!(three_quarters.anchors.get(1).unwrap().p, pt(100.0, 0.0)); + let quarter = length::with_length(&sp, false, 0.5 * PI * 50.0).unwrap(); + assert_eq!(quarter.anchors.len(), 3); + assert!(quarter.anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + // Set back to its own length, the arc is the same. + let same = length::with_length(&sp, false, end.length).unwrap(); + assert!(same.anchors.iter().zip(sp.anchors.iter()).all(|(a, b)| a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9)); + assert_eq!(length::with_length(&sp, false, 360.0_f64.to_radians() * 50.0), None, "past 359°"); + // 359° is the longest: set to it, the arc ends 1° short of where it starts. + let max = end.max_length(); + assert!((max - 359f64.to_radians() * 50.0).abs() < 1e-9); + let longest = length::with_length(&sp, false, max).unwrap(); + assert!(on_circle(&longest, 1, pt(150.0, 0.0), 50.0)); + let short_of_start = pt(150.0, 0.0) + rot(pt(100.0, 0.0) - pt(150.0, 0.0), 359f64.to_radians() * sweep.signum()); + assert!(longest.anchors.last().unwrap().p.distance(short_of_start) < 1e-6, "{:?}", longest.anchors.last()); + // Dragged around past the start of the half circle, the arc grows on instead of starting again. + let near = 1.5 * PI * 50.0; + let l = end.length_toward(pt(150.0, 80.0), near); + assert!((l - near).abs() < 1e-9, "{l}"); + // Dragged on past 359°, just past its start (above it, since the half circle bulges up), the arc + // stops there. + assert_eq!(end.length_toward(pt(100.0, -1.0), max - 0.01), max); +} + +/// On a small arc, a handle dragged a quarter turn around the circle takes the end a quarter turn +/// around too: the offset of the handle from the end turns with the pointer. +#[test] +fn a_small_arc_end_follows_its_handle_around_the_circle() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(10.0, 0.0, Stroke::SharpArc)], false); + let end = length::end_piece(&sp, false).unwrap(); + let length::EndShape::Arc { center, radius, sweep } = end.shape else { panic!("an arc: {end:?}") }; + assert!((radius - 5.0).abs() < 1e-9); + let press = end.end + end.out * 20.0; + let quarter = end.length + FRAC_PI_2 * radius; + let turned = |p: Point, a: f64| center + rot(p - center, a); + let l = end.length_dragged(press, turned(press, FRAC_PI_2 * sweep.signum()), end.length); + assert!((l - quarter).abs() < 1e-9, "{l} against {quarter}"); + // A handle pressed where it stands and not moved leaves the length as it is. + assert!((end.length_dragged(press, press, end.length) - end.length).abs() < 1e-9); +} + +/// An end that is neither straight nor circular has no length to set, and neither does a closed path. +#[test] +fn other_ends_have_no_piece() { + let mut sp = start(pt(0.0, 0.0)); + sp.anchors.push(Anchor::with_handles(pt(100.0, 0.0), pt(90.0, 40.0), pt(100.0, 0.0))); + if let Some(a) = sp.anchors.first_mut() { + a.h_out = pt(10.0, 5.0); + } + assert_eq!(length::end_piece(&sp, false), None); + assert_eq!(length::with_length(&sp, false, 10.0), None); + // A cubic with a quarter circle's handles whose end is on that circle, but not a quarter turn + // around it, is not an arc. + let k = 4.0 / 3.0 * (FRAC_PI_2 / 4.0).tan() * 100.0; + let mut off = start(pt(0.0, 0.0)); + off.anchors.push(Anchor::with_handles(pt(-100.0, 100.0), pt(-100.0, 100.0 - k), pt(-100.0, 100.0))); + if let Some(a) = off.anchors.first_mut() { + a.h_out = pt(k, 0.0); + } + assert_eq!(length::end_piece(&off, false), None); + // An arc too small to be 0.001 pt long even at 359° has no length to set either. + let tiny = build(&start(pt(0.0, 0.0)), &[piece(0.0001, 0.0, Stroke::SharpArc)], false); + assert_eq!(tiny.anchors.len(), 3); + assert_eq!(length::end_piece(&tiny, false), None); + let mut closed = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(100.0, 100.0, Stroke::Line)], false); + closed.closed = true; + assert_eq!(length::end_piece(&closed, false), None); +} + +/// A control point may lie past the canvas while the curve stays on it; a curve that reaches past +/// the canvas is refused. +#[test] +fn the_canvas_check_measures_the_curve_not_its_control_points() { + let m = MAX_COORD; + let cubic = |out_x: f64| { + let mut a = Anchor::corner(pt(m - 100.0, 0.0)); + a.h_out = pt(out_x, 0.0); + let mut b = Anchor::corner(pt(m - 100.0, 100.0)); + b.h_in = b.p; + SubPath::new(vec![a, b], false) + }; + assert!(on_canvas(&cubic(m - 100.0))); + assert!(on_canvas(&cubic(m + 100.0))); + assert!(!on_canvas(&cubic(m + 1000.0))); + let mut far = start(pt(m + 1.0, 0.0)); + far.anchors.push(Anchor::corner(pt(0.0, 0.0))); + assert!(!on_canvas(&far)); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 8ec14c5b6c..ea677ec654 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -214,6 +214,11 @@ pub struct SelectionTool { /// Where the pointer was at the last press or drag: a widget drag released anywhere else is /// dragged there before it ends. held_at: Option, + /// Where the last press that selected the object behind (Cmd/Ctrl-click) was released: a + /// double-click there that follows it is that press clicked again, not a double-click that + /// isolates or edits. It holds the document's revision at the release too (None until then), + /// and an edit or a selection change after it ends it. + pressed_behind: Option<(Point, Option<(u64, u64)>)>, } /// What Distance Guides measure the selection to. @@ -503,16 +508,67 @@ struct MemoState { /// The measurements for one key; a slot holds `None` until it is measured. struct Measured { revision: (u64, u64), + /// The fonts, hyphenation exceptions and plug-ins live art is drawn and hit with + /// ([`vectorcraft_doc::hit::live_inputs`]). + live: u64, objects: Vec, measure: vectorcraft_effects::preview::Measure, bounds: Option>, oriented: Option>, by_object: HashMap>>, + /// [`painted_bounds`] in Preview and in Outline view. + painted: [Option>; 2], + /// [`selected_part_boxes`]. + part_boxes: Option>, + /// [`selection_holders`]. + holders: Option>>, + /// [`selects_behind_at`]'s last answer, with the point and settings it was for. + behind: Option<(BehindKey, bool)>, +} + +/// What [`selects_behind_at`] answers for besides the document and the selection: the point, the +/// tolerances (the zoom and the preferences) and the hit-test settings. +#[derive(Clone, Copy, PartialEq)] +struct BehindKey { + at: Point, + pick_tol: f64, + point_tol: f64, + scope: Option, + outline: bool, + path_only: bool, + type_path_only: bool, + skip_guides: bool, + handles_multiple: bool, + /// The zoom, which sets the mesh points' and the box handles' reach. + zoom: f64, + show_bbox: bool, +} + +impl BehindKey { + fn of(cx: &ToolContext, at: Point) -> Self { + let opt = cx.selection_hit_options(); + Self { + at, + pick_tol: cx.pick_tol(), + point_tol: cx.point_tol(), + scope: cx.isolation, + outline: opt.outline, + path_only: opt.path_only, + type_path_only: opt.type_path_only, + skip_guides: opt.skip_guides, + handles_multiple: cx.handles_multiple, + zoom: cx.zoom, + show_bbox: cx.show_bbox, + } + } } impl Measured { fn is_for(&self, cx: &ToolContext) -> bool { - self.revision == cx.revision && self.measure == cx.bounds_measure() && self.objects == cx.selection.objects + self.revision == cx.revision + && self.live == vectorcraft_doc::hit::live_inputs() + && self.measure == cx.bounds_measure() + && self.objects == cx.selection.objects } } @@ -534,11 +590,16 @@ impl PreviewMemo { st.checks += 1; let fresh = || Measured { revision: cx.revision, + live: vectorcraft_doc::hit::live_inputs(), objects: cx.selection.objects.clone(), measure: cx.bounds_measure(), bounds: None, oriented: None, by_object: HashMap::new(), + painted: [None, None], + part_boxes: None, + holders: None, + behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { st.entry = Some(fresh()); @@ -553,10 +614,16 @@ impl PreviewMemo { { return v; } + let live = vectorcraft_doc::hit::live_inputs(); let v = measure(); + // Live inputs that changed while it measured leave the value unkept: only the entry for the + // inputs it was measured with takes it. if let Ok(mut st) = self.0.try_borrow_mut() { st.measurements += 1; - *slot(Self::current(&mut st, cx)) = Some(v.clone()); + let m = Self::current(&mut st, cx); + if m.live == live { + *slot(m) = Some(v.clone()); + } } v } @@ -584,6 +651,48 @@ pub fn selection_box(cx: &ToolContext) -> Option { remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } +/// The bounds a hit test can find the objects in that a click selects for the selected art +/// ([`top_holder`]): their reach (a blend's spine included), their visual bounds as drawn +/// (strokes and effects included, whatever Use Preview Bounds says) and their geometric bounds +/// (where Outline view hits the paths), together, kept for each view mode. +fn painted_bounds(cx: &ToolContext) -> Option { + let outline = cx.selection_hit_options().outline; + remembered( + cx, + |m| &mut m.painted[usize::from(outline)], + || { + let mut seen = std::collections::HashSet::new(); + let tops: Vec = cx.selection.objects.iter().map(|&id| top_holder(cx, id)).filter(|id| seen.insert(*id)).collect(); + // A layer or group above them with visible effects of its own that draw art (not raster + // effects, which a hit test leaves out, nor color adjustments) can draw (and hit) them + // anywhere. Outline view hits the paths where they are. + let moves_art = |e: &vectorcraft_doc::Effect| { + e.visible && !outline && !vectorcraft_effects::is_raster(&e.id) && !vectorcraft_effects::is_adjustment(&e.id) + }; + let above_has_effects = tops.iter().any(|id| { + cx.doc.ancestry(*id).is_some_and(|a| { + a.iter().take_while(|n| *n != id).any(|n| cx.doc.node(*n).is_some_and(|n| n.appearance.effects.iter().any(moves_art))) + }) + }); + if above_has_effects { + return Some(Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY)); + } + let symbols = cx.doc.symbol_boxes(); + let reach = tops.iter().filter_map(|id| cx.doc.node(*id)).filter_map(|n| n.reach_bounds_with(&symbols)); + let drawn = vectorcraft_effects::preview::bounds_of(cx.doc, &tops, true); + let geometric = vectorcraft_effects::preview::bounds_of(cx.doc, &tops, false); + reach.chain(drawn).chain(geometric).reduce(|a, b| a.union(b)) + }, + ) +} + +/// `measure`'s list of the selected objects' editable paths with their control bounds, kept in the +/// session's [`PreviewMemo`] while the document and the selection stay as they are +/// ([`crate::direct::over_selected_part`]). +pub(crate) fn selected_part_boxes(cx: &ToolContext, measure: impl FnOnce() -> std::sync::Arc<[(NodeId, Rect)]>) -> std::sync::Arc<[(NodeId, Rect)]> { + remembered(cx, |m| &mut m.part_boxes, measure) +} + /// [`selection_box`] while the canvas shows it (View › Show Bounding Box, and no anchors selected /// on their own): its handles take a press only then. A path the Pen is drawing keeps its end /// anchor selected, so Cmd/Ctrl lending the Selection tool doesn't scale it by hidden handles (#4980). @@ -804,6 +913,25 @@ impl SelectionTool { } } + /// Each press, whatever takes it, starts with no Select Behind of its own, and the double-click + /// that follows one comes where that press is released, with the document as the release left + /// it, before the pointer moves away; a press that drags or is released away is not a click + /// ([`Self::pressed_behind`]). + fn note_pressed_behind(&mut self, cx: &ToolContext, ev: &PointerEvent) { + match ev.kind { + PointerKind::Down => self.pressed_behind = None, + PointerKind::Move | PointerKind::Drag => { + if self.pressed_behind.is_some_and(|(at, _)| at.distance(ev.pos) > cx.tol(1.0)) { + self.pressed_behind = None; + } + } + PointerKind::Up => { + self.pressed_behind = self.pressed_behind.filter(|(at, _)| at.distance(ev.pos) <= cx.tol(1.0)).map(|_| (ev.pos, Some(cx.revision))); + } + _ => {} + } + } + /// Notes where a press or a drag last held the pointer, and says whether a release lands /// somewhere else. fn note_held_at(&mut self, ev: &PointerEvent) -> bool { @@ -1031,10 +1159,16 @@ impl Tool for SelectionTool { } } + /// A press lent to another tool is not a Select Behind press of this tool. + fn press_elsewhere(&mut self) { + self.pressed_behind = None; + } + /// A press takes the selection's widgets, a ruler guide, a selected object's centre point or /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); + self.note_pressed_behind(cx, ev); let released_away = self.note_held_at(ev); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); @@ -1088,6 +1222,7 @@ impl Tool for SelectionTool { { self.state = State::Moving { start: p, press: p, hold: p, grip: Grip::Point, began: false, deselect: None, key: None, exclude: None }; + self.pressed_behind = Some((p, None)); return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -1434,11 +1569,103 @@ impl Tool for SelectionTool { } } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest selected -/// one, back to the topmost after the bottom one; the topmost when none is selected. +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an +/// object under the pointer selected or holding selected art (a group with a selected member), +/// with another object under the pointer too, away from the anchors, handles, mesh points and +/// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the +/// press to Direct Selection or Group Selection. +pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { + if !cx.select_behind { + return false; + } + let tol = cx.pick_tol(); + // The answer is kept for the document and the selection as they are: the cursor, the canvas + // marks and a press at the same point ask again without walking the document again. + let key = BehindKey::of(cx, p); + if let Some(memo) = cx.preview_memo + && let Ok(mut st) = memo.0.try_borrow_mut() + && let Some((k, v)) = PreviewMemo::current(&mut st, cx).behind + && k == key + { + return v; + } + // The painted bounds of the objects holding the selection come first: away from them, no + // document walk is needed. They take in a wide stroke's outer half, which the bounding box + // leaves out without Use Preview Bounds, and a group's members that are not selected. With no + // other object under the pointer there is nothing to select behind: the press is lent. + // A shown bounding box's handles and rotate zones are not passed to Select Behind: the press + // there is lent. + let live = vectorcraft_doc::hit::live_inputs(); + let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) + && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) + && { + let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); + stack.len() > 1 && holds_selection(cx, &stack).is_some() + } + && !crate::direct::over_selected_part(cx, p); + if let Some(memo) = cx.preview_memo + && let Ok(mut st) = memo.0.try_borrow_mut() + { + st.measurements += 1; + // Only the entry for the live inputs it was found with keeps the answer. + let m = PreviewMemo::current(&mut st, cx); + if m.live == live { + m.behind = Some((key, behind)); + } + } + behind +} + +/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is +/// selected or holds selected art, such as a group with a member picked by Direct Selection or +/// Group Selection. +fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { + let holders = selection_holders(cx); + stack.iter().rposition(|id| holders.contains(id)) +} + +/// The selected objects and every object that holds one (their groups and layers), kept in the +/// session's [`PreviewMemo`] while the document and the selection stay as they are. +fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { + remembered( + cx, + |m| &mut m.holders, + || { + let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); + std::sync::Arc::new(set) + }, + ) +} + +/// The selected object `id` and the objects holding it, outermost first, from the object a click +/// with the Selection tool selects for it ([`Hit::top_object`]): below its layers, the isolated +/// object and an envelope whose contents are edited. +fn holder_chain(cx: &ToolContext, id: NodeId) -> Vec { + let Some(a) = cx.doc.ancestry(id) else { return vec![id] }; + let isolated = cx.isolation.and_then(|s| a.iter().position(|n| *n == s)); + let contents = + a.iter().rposition(|n| cx.doc.node(*n).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Envelope { editing: true, .. }))); + // Below the isolated object or the envelope, the child holding `id` is the top object, a + // sublayer included; elsewhere layers and sublayers are skipped. + let chain: Vec = match isolated.max(contents) { + Some(i) => a.iter().skip(i + 1).copied().collect(), + None => a.iter().copied().skip_while(|n| cx.doc.node(*n).is_some_and(|n| n.is_layer())).collect(), + }; + if chain.is_empty() { vec![id] } else { chain } +} + +/// The object a click with the Selection tool selects for the selected object `id` +/// ([`holder_chain`]). +fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { + holder_chain(cx, id).first().copied().unwrap_or(id) +} + +/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is +/// selected or holds selected art, back to the topmost after the bottom one; the topmost when +/// none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = stack.iter().rposition(|id| cx.selection.contains(*id)).map_or(0, |i| i + 1); + let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); stack.get(next).or(stack.first()).copied() } @@ -1624,6 +1851,14 @@ impl SelectionTool { fn double_click(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Vec { self.state = State::Idle; + // Quick Cmd-clicks that select behind keep what the last one selected, before the widgets + // of that object answer, also when Cmd is let go before the release. Cmd+Shift on a guide + // still releases it. A double-click elsewhere, or after an edit or a selection change, is a + // double-click of its own. A press whose release has not come yet (both in one frame) + // still counts. + if self.pressed_behind.take().is_some_and(|(at, rev)| at.distance(p) <= cx.tol(1.0) && rev.is_none_or(|r| r == cx.revision)) { + return release_guide_at(cx, p, m).into_iter().collect(); + } // A threaded port: the thread breaks there. Any other port takes the double-click // too, so it neither edits the type nor isolates. if let Some((id, port)) = crate::text::port_at(cx, p) { diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index fe68a96d79..8ce1aa6812 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -10,6 +10,7 @@ use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; +use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::sections::Section; use egui::Ui; @@ -304,8 +305,8 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option) { if !r.status.is_empty() { Text::new(r.status.clone()).show(ui); } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let picked = r.picked_kinds(); let show = push(ui, tl!("Show"), picked.len() == 1, None).is_some(); if show && let [kind] = picked.as_slice() { diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index ec86efd95c..aca41a2620 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -14,6 +14,7 @@ use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::form::{Field, FieldGroup}; +use craft::ui::layout_components::Row; use craft::ui::pickers::Select; use egui::Ui; use serde_json::{Map, Value, json}; @@ -178,18 +179,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } let (id, params) = st.params(); - let mut command = None; - ui.horizontal(|ui| { + let (mut command, mut reset) = (None, false); + Row::new().show(ui, |ui, _| { if Button::new(tl!("Add as Effect").to_string()).show(ui).clicked() { command = Some("effect.apply"); } if Button::new(tl!("Apply as Filter").to_string()).show(ui).clicked() { command = Some("addon.color.filter"); } - if Button::new(tl!("Reset").to_string()).show(ui).clicked() { - st.values.remove(id); - } + reset = Button::new(tl!("Reset").to_string()).show(ui).clicked(); }); + if reset { + st.values.remove(id); + } // Inks: Duotone's and Print Ink Fixes' dialogs, as their menu items open them. let mut ink = None; crate::panels::section(tl!("Inks").to_string()).show(ui, |ui, _| { diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 1310bb3ca2..307d4a3e29 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle… and Add Bounding Circle…; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and @@ -49,6 +49,8 @@ pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "exter /// dialog (Offset, One per Object) with a Preview. pub const BOUNDING_RECTANGLE: &str = "addon.pathtools.boundingRectangle"; pub const BOUNDING_CIRCLE: &str = "addon.pathtools.boundingCircle"; +/// Add Inscribed Circle's command, whose menu item runs it with no dialog. +pub const INSCRIBED_CIRCLE: &str = "addon.pathtools.inscribedCircle"; /// The close modes, as `addon.pathtools.close` names them, and their labels. const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; /// The Anchor Inspector's anchor edits: X and Y, and each handle's length and angle, label and field side by side. @@ -135,6 +137,7 @@ pub fn menu() -> Vec { cp("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), cp("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), cp("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), + cp("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 52afdeef41..464ce72f42 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -4,9 +4,9 @@ use vectorcraft_engine::Session; use vectorcraft_tools::addons::parametric_shape::ShapeKind; use super::{ID, KIND, readout}; -use crate::VectorcraftApp; use crate::addons::dialogs::tests as host; use crate::tests::panel_harness::Panel; +use crate::{VectorcraftApp, menus}; fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -319,3 +319,41 @@ fn a_bare_number_in_a_panels_picas_field_follows_numbers_without_units_are_point assert!((points - 12.0).abs() < 1e-6, "on: {points} pt"); assert!((picas - 144.0).abs() < 1e-6, "off: {picas} pt"); } + +#[test] +fn add_inscribed_circle_draws_its_circles_without_a_dialog() { + let mut app = app_with_window(); + let find = |app: &VectorcraftApp| { + let entries = menus::menu_entries(app); + entries + .into_iter() + .find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Add Inscribed Circle") + .expect("Add Inscribed Circle") + }; + let item = find(&app); + assert_eq!((item.command.as_deref(), &item.params), (Some(super::INSCRIBED_CIRCLE), &json!({}))); + assert!(!item.enabled, "with nothing selected"); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 100, "y": 20, "width": 20, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let (steps, nodes) = (app.session.doc().unwrap().history.undo.len(), app.session.doc().unwrap().doc.node_count()); + let item = find(&app); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert!(held(&app, |d| d.is_none()), "no dialog opens"); + let st = app.session.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.doc.node_count()), (steps + 1, nodes + 2), "a circle in each rectangle, one undo step"); + let made = &st.selection.objects; + assert_eq!(made.len(), 2, "the two circles are selected: {made:?}"); + for (id, inside) in made.iter().zip([[10.0, 20.0, 40.0, 60.0], [100.0, 20.0, 120.0, 60.0]]) { + assert!(id.0 != a && id.0 != b, "{id:?} is a new object"); + let live = match &st.doc.node(*id).unwrap().kind { + vectorcraft_doc::NodeKind::Path { live, .. } => live.as_deref(), + _ => None, + }; + assert!(matches!(live, Some(vectorcraft_doc::LiveShape::Ellipse { w, h, .. }) if w == h), "{id:?} is a live circle"); + let r = st.doc.bounds_of(&[*id], false).unwrap(); + assert!(r.x0 >= inside[0] && r.y0 >= inside[1] && r.x1 <= inside[2] && r.y1 <= inside[3], "{r:?} inside {inside:?}"); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 225be05ca7..fdf92146d2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -308,6 +308,15 @@ impl VectorcraftApp { /// eframe isn't a dependency of this crate (the host owns the event loop); these entry points are /// called from the host's `eframe::App` impl through `embed`'s hooks. impl VectorcraftApp { + /// Seconds on the app's clock: the monotonic clock, or the time a test set in `now_override`. + pub(crate) fn now(&self) -> f64 { + #[cfg(test)] + if let Some(now) = self.now_override { + return now; + } + now_secs() + } + /// Applies the work that finished off the UI thread. It stays pending while a script runs, since /// every change to the documents ends in a busy error until the script ends. pub(crate) fn poll_finished_work(&mut self) { @@ -415,10 +424,7 @@ impl VectorcraftApp { // Monotonic host time, never egui's `InputState::time`: a hidden window's `logic` replays // the last shown pass's time, freezing recovery, clipboard polling and deadlines. Tests // inject a clock to drive idle scheduling deterministically. - #[cfg(test)] - let now = self.now_override.unwrap_or_else(now_secs); - #[cfg(not(test))] - let now = now_secs(); + let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); self.refresh_replace_font_warning(false); diff --git a/crates/ui-egui/src/background.rs b/crates/ui-egui/src/background.rs index 779f6dc59c..57a9bf1086 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -263,6 +263,7 @@ fn start( let id = app.background.next_id; let jobs = app.jobs(); let (sets, status) = (app.ui.status_sets, if label.is_empty() { String::new() } else { format!("{label}…") }); + let started = export_progress::now(app); let bg = &mut app.background; bg.next_id += 1; let tx = bg.results.get_or_insert_with(channel).0.clone(); @@ -280,18 +281,7 @@ fn start( }), ); let line = status.clone(); - bg.jobs.push(Job { - id, - kind, - label: label.clone(), - doc, - progress, - hidden: false, - started: export_progress::now(), - sets, - line, - then: Box::new(then), - }); + bg.jobs.push(Job { id, kind, label: label.clone(), doc, progress, hidden: false, started, sets, line, then: Box::new(then) }); if label.is_empty() { return Ok(json!({ "background": true })); } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index dbf79f25a4..987de9a8da 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -159,7 +159,7 @@ pub struct CanvasCache { /// The Navigator's view region, for (document uid, revision, View Artboard Contents Only). pub nav_region: Option<((u64, u64, bool), vectorcraft_geom::Rect)>, /// The Document Info panel's values, for (document uid, revision, selection only, options). - pub doc_info: Option<((u64, u64, bool, Value), Value)>, + pub doc_info: Option, /// The Variables panel's rows, for the panel's key. pub(crate) variable_rows: Option<(crate::panels::variables::RowsKey, Rc)>, /// The Map Art surfaces of the 3D dialog's object. @@ -168,6 +168,10 @@ pub struct CanvasCache { pub(crate) palette: Option<(crate::palette::BuildKey, Arc)>, } +/// [`CanvasCache::doc_info`]: (document uid, revision, selection only, the Artboard tool's options) +/// and the `document.info` result fetched for them. +pub type DocInfoCache = ((u64, u64, bool, Value), Arc); + /// [`CanvasCache::map_surfaces`]: the surfaces and what they were computed for. pub type MapSurfacesCache = (MapSurfacesKey, Arc>); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d4d2c3628e..b097971511 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -243,6 +243,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O let presenting = app.ui.screen_mode == 3; let mut out = Body { context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), ..Body::default() }; grids(app, ui, space, win); + if live { + find_shown_tool(app, ui.ctx(), space); + } marks::show(app, ui, space, win, kind); if !presenting { crate::panels::tabs::stop_guide(app, ui, space); @@ -291,6 +294,38 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O out } +/// The keys held now, as the engine's tools read them, with `space` set while Space is down. +pub(crate) fn held_mods(ctx: &egui::Context) -> vectorcraft_tools::Mods { + let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space))); + mods(m, space) +} + +/// The tool whose marks and widgets the canvas draws with the keys held now: while Cmd is held, the selection tool +/// a press at the pointer borrows ([`find_shown_tool`]), else the active tool. +pub(crate) fn shown_tool(app: &VectorcraftApp, ctx: &egui::Context) -> &'static str { + app.session.hover_tool_id(&held_mods(ctx)) +} + +/// Finds the tool whose marks and widgets the canvas draws this frame for the pointer where it is now +/// ([`vectorcraft_engine::Session::hover_tool_at`]), which [`shown_tool`] then answers. While the view moves, the art +/// under the pointer is not hit-tested again (#2452), and the last answer stays. +fn find_shown_tool(app: &mut VectorcraftApp, ctx: &egui::Context, space: &CanvasSpace) { + let wait = cursor::hover_wait(&mut app.canvas.view_moved, ViewKey::of(&space.view), craft::ui::runtime::frame::clock(ctx)); + if wait.is_some() { + return; + } + let held = held_mods(ctx); + let named = app.session.shown_tool_id(&held); + let at = ctx.input(|i| i.pointer.hover_pos()).filter(|p| space.view.rect.contains(*p)).map(|p| space.view.to_doc(p)); + let view = app.view_info(); + app.session.hover_tool_at(at, &held, view); + // The status bar and the help bar are drawn before the canvas: when the tool they name changes with this + // frame's pointer, they are drawn again. + if app.session.shown_tool_id(&held) != named { + ctx.request_repaint(); + } +} + /// The document grid, in the picture slot under the art when Grids In Back is on and over it /// otherwise, and the pixel grid over the art. fn grids(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, win: Win) { diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index bc6189861d..33d17fc6fd 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -251,10 +251,9 @@ fn grid_path(key: u64, points: impl Iterator, color: Color32) -> E /// The anchors and handles of the selection. An object selected whole has every anchor selected, and so do the /// paths inside a group, compound path or clip group selected whole; with Direct Selection's partial selection only /// the chosen anchors are, and a selected segment hollows the others. `tool_points` is whether the tool draws its own -/// points (the Curvature tool while it draws), which leaves nothing here. Nothing too big to outline, and nothing -/// during Halftone Preview. -pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool_points: bool) -> Anchors { - let tool = app.session.tool_id(); +/// points (the Curvature tool while it draws), which leaves nothing here. `tool` is the tool whose marks show +/// ([`super::shown_tool`]). Nothing too big to outline, and nothing during Halftone Preview. +pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> Anchors { let curvature = tool == "curvature"; let prefs = &app.session.prefs; let mut out = Anchors { @@ -326,13 +325,13 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool_points: bool) -> /// The outline of the object under the pointer at document point `at`, at view `zoom`, for Smart Guides › Object /// Highlighting: the object a click of the selection tools would pick, unless it is selected or has too many points. /// None while the view moves (`still` false), under Snap to Grid or Pixel Preview, with a tool that is busy or is not -/// a selection tool, and with the preference off. -pub(super) fn hover(app: &VectorcraftApp, st: &DocState, at: Point, zoom: f64, still: bool) -> Option { +/// a selection tool, and with the preference off. `tool` is the tool whose marks show ([`super::shown_tool`]): while +/// Cmd is held, the selection tool a press borrows. +pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, zoom: f64, still: bool) -> Option { let (view, prefs) = (&app.ui.view, &app.session.prefs); if !still || !view.smart_guides || !prefs.object_highlighting || view.snap_to_grid || view.pixel_preview { return None; } - let tool = app.session.tool_id(); if app.session.tool_busy() || !matches!(tool, "selection" | "directSelection" | "groupSelection") { return None; } @@ -467,10 +466,12 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } wait.is_none() }; + // While Cmd is held, the marks of the selection tool a press borrows. + let tool = super::shown_tool(app, ui.ctx()); let Some(st) = app.session.active() else { return }; let hovered = match (kind, app.hover_doc) { (BodyKind::Pane, _) | (_, None) => None, - (_, Some(at)) => hover(app, st, at, space.view.zoom, still), + (_, Some(at)) => hover(app, st, tool, at, space.view.zoom, still), }; if let Some(h) = hovered { HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect); @@ -482,7 +483,7 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } outline.show_at(ui, rect); } - let marks = anchors(app, st, tool_points); + let marks = anchors(app, st, tool, tool_points); if !marks.paths.is_empty() { let mut paths = marks.paths; // The marks only show the selection: the tools make the edits. diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index addeedee4c..ed590c2df6 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -47,7 +47,7 @@ fn revisions(seen: &Seen) -> Vec { } fn marks(app: &VectorcraftApp) -> Anchors { - anchors(app, app.session.active().unwrap(), false) + anchors(app, app.session.active().unwrap(), app.session.tool_id(), false) } fn all_selected(selection: &PathSelection) -> usize { @@ -290,12 +290,12 @@ fn point_type_hover_shows_baseline_only_and_selection_shows_both_box_and_baselin app.select_tool("selection"); let over = Point::new(220.0, 140.0); let st = app.session.active().unwrap(); - let hovered = hover(&app, st, over, 1.0, true).expect("the type under the pointer is outlined"); + let hovered = hover(&app, st, app.session.tool_id(), over, 1.0, true).expect("the type under the pointer is outlined"); let line = hovered.path.bounding_box(); assert!((line.y0 - 150.0).abs() < 0.5 && line.height() < 0.5, "the baseline only, not the box: {line:?}"); app.run("select.set", json!({"ids": [id.0]})).unwrap(); let st = app.session.active().unwrap(); - assert!(hover(&app, st, over, 1.0, true).is_none(), "a selected object has no hover outline"); + assert!(hover(&app, st, app.session.tool_id(), over, 1.0, true).is_none(), "a selected object has no hover outline"); assert_eq!(outlines(&app, st)[0].paths.len(), 1, "the selection outlines the baseline; the box is the bounding box's"); } @@ -308,7 +308,7 @@ fn hover_scene() -> VectorcraftApp { } fn hovered(app: &VectorcraftApp, still: bool) -> bool { - hover(app, app.session.active().unwrap(), Point::new(150.0, 150.0), 1.0, still).is_some() + hover(app, app.session.active().unwrap(), app.session.tool_id(), Point::new(150.0, 150.0), 1.0, still).is_some() } #[test] @@ -340,7 +340,7 @@ fn a_group_of_too_many_paths_has_no_hover_outline_and_a_key_outline_of_its_bound app.run("select.none", json!({})).unwrap(); app.select_tool("selection"); let st = app.session.active().unwrap(); - assert!(hover(&app, st, Point::new(20.0, 20.0), 1.0, true).is_none(), "no hover outline for what is too big"); + assert!(hover(&app, st, app.session.tool_id(), Point::new(20.0, 20.0), 1.0, true).is_none(), "no hover outline for what is too big"); // A key object stays while another selected object lies outside it. let other = id_of(&app.run("shape.rectangle", json!({"x": 300, "y": 20, "width": 20, "height": 20})).unwrap()); app.run("select.set", json!({"ids": [huge.0, other.0]})).unwrap(); @@ -356,9 +356,9 @@ fn curvature_marks_existing_paths_as_circles_and_leaves_a_drafts_points_to_the_t app.run("select.set", json!({"ids": [curve.0]})).unwrap(); app.select_tool("curvature"); let st = app.session.active().unwrap(); - let existing = anchors(&app, st, false); + let existing = anchors(&app, st, app.session.tool_id(), false); assert_eq!((existing.shown, existing.paths.len()), (AnchorsShown::Curvature, 1), "one circle per point of the existing path"); - assert!(anchors(&app, st, true).paths.is_empty(), "while the tool draws its own points, none are drawn twice"); + assert!(anchors(&app, st, app.session.tool_id(), true).paths.is_empty(), "while the tool draws its own points, none are drawn twice"); app.select_tool("directSelection"); assert_eq!(marks(&app).shown, AnchorsShown::All); assert!(!marks(&app).paths.is_empty(), "other tools keep their anchors whatever `tool_points` says"); diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs index 45eea5319b..84f0813818 100644 --- a/crates/ui-egui/src/canvas/selection_widgets.rs +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -531,24 +531,32 @@ pub(super) fn end_hidden(app: &mut VectorcraftApp, held: &mut Option, layo } } -/// Which widgets the app's tool and view show. -pub(super) fn shown(app: &VectorcraftApp) -> Show { - let tool = app.session.tool_id(); +/// Which widgets `tool` and the app's view show. `tool` is the tool whose widgets the canvas shows +/// ([`super::shown_tool`]): while Cmd is held, the selection tool a press borrows. +pub(super) fn shown(app: &VectorcraftApp, tool: &str) -> Show { let revolve_edit = super::revolve_editing(app); let selecting = tool == "selection" && app.ui.view.edges && !revolve_edit; Show { nine: true, selecting, shaper: matches!(tool, "shaper" | "selection") && !revolve_edit, trace: selecting && !app.outline_view() } } /// Shows the widgets over the document and runs the presses on them. Runs before the tool host, so a press on a part -/// never reaches the tool. +/// never reaches the tool. While Cmd lends the Selection tool, its widgets show and take a press as that tool's, +/// without Cmd, and a press on one keeps them until the release. pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, win: super::Win, kind: BodyKind) { if kind != BodyKind::Live || app.ui.screen_mode == 3 { return; } - let (visible, info) = (shown(app), app.view_info()); - let layout = app.session.with_tool_context(info, |cx| Layout::of(cx, &space.view, visible)); let id = super::canvas_id(win).with("selection_widget_drag"); + let tool_id = id.with("tool"); let mut held: Option = ui.data(|d| d.get_temp::>(id)).flatten(); + let tool = match held { + Some(_) => ui.data(|d| d.get_temp::<&'static str>(tool_id)), + None => None, + } + .unwrap_or_else(|| super::shown_tool(app, ui.ctx())); + let lent = tool != app.session.tool_id(); + let (visible, info) = (shown(app, tool), app.view_info()); + let layout = app.session.with_tool_context(info, |cx| Layout::of(cx, &space.view, visible)); end_hidden(app, &mut held, &layout); let out = SelectionWidgets::new(layout).show(ui); for (widget, press) in out.presses { @@ -563,7 +571,13 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp PressPhase::Cancel { .. } => Gesture::Cancel, _ => continue, }; - advance(app, &mut held, widget, g, super::tool_adapter::tool_mods(press.mods, false)); + let mut mods = super::tool_adapter::tool_mods(press.mods, false); + // The lent tool takes the press as a plain one, as the session lends it. + mods.cmd &= !lent; + advance(app, &mut held, widget, g, mods); } - ui.data_mut(|d| d.insert_temp(id, held)); + ui.data_mut(|d| { + d.insert_temp(id, held); + d.insert_temp(tool_id, tool); + }); } diff --git a/crates/ui-egui/src/canvas/selection_widgets/tests.rs b/crates/ui-egui/src/canvas/selection_widgets/tests.rs index 357b5c1208..ad2ecdf2c0 100644 --- a/crates/ui-egui/src/canvas/selection_widgets/tests.rs +++ b/crates/ui-egui/src/canvas/selection_widgets/tests.rs @@ -73,7 +73,7 @@ fn check_tool_switch_cancels(app: &mut VectorcraftApp, widget: Widget, at: Pos2, advance(app, &mut held, widget, Gesture::Move(v.to_doc(q)), Mods::default()); assert_ne!(*app.session.active().unwrap().doc, *before, "the drag previews"); app.select_tool("directSelection"); - let visible = shown(app); + let visible = shown(app, app.session.tool_id()); let l = layout(app, visible); end_hidden(app, &mut held, &l); assert!(held.is_none(), "a tool switch cancels the drag"); @@ -354,3 +354,52 @@ fn app_with_radial() -> VectorcraftApp { app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); app } + +/// The widgets only the Selection tool presses (a Shaper Group's mode widget, a mirror repeat's axis, a grid or radial +/// repeat's handles) hide while Cmd lends Direct Selection, and come back when the key is let go. +#[test] +fn selection_tool_widgets_hide_while_cmd_lends_direct_selection() { + let count = |app: &mut VectorcraftApp, held: egui::Modifiers, widget: Widget| { + let tool = app.session.hover_tool_id(&crate::canvas::mods(held, false)); + let visible = shown(app, tool); + widgets(&layout(app, visible), widget) + }; + // Each widget that does not show, hide or come back as it should. + let mut wrong = vec![]; + let mut check = |app: &mut VectorcraftApp, widget: Widget| { + app.select_tool("selection"); + let plain = count(app, egui::Modifiers::NONE, widget); + let cmd = count(app, egui::Modifiers::COMMAND, widget); + let back = count(app, egui::Modifiers::NONE, widget); + if plain == 0 || cmd != 0 || back != plain { + wrong.push(format!("{widget:?}: {plain} shown, {cmd} with Cmd held, {back} after")); + } + }; + let mut shaper = app(); + for x in [0, 50] { + shaper.run("shape.rectangle", json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + shaper.run("shaper.scribble", json!({"points": [[25, 20], [75, 35], [30, 50], [125, 65]]})).unwrap(); + check(&mut shaper, Widget::Shaper); + check(&mut mirror_app().0, Widget::Mirror); + let mut grid = app(); + grid.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 40, "height": 40})).unwrap(); + grid.run("object.repeat.grid", json!({"hSpacing": 10, "vSpacing": 10})).unwrap(); + check(&mut grid, Widget::Grid); + check(&mut app_with_radial(), Widget::Radial); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + +/// With Direct Selection, Cmd held lends the Selection tool, and its widgets show. +#[test] +fn cmd_held_with_direct_selection_shows_the_selection_tools_widgets() { + let (mut app, _) = mirror_app(); + app.select_tool("directSelection"); + let tool = |app: &VectorcraftApp, held| app.session.hover_tool_id(&crate::canvas::mods(held, false)); + let own = shown(&app, tool(&app, egui::Modifiers::NONE)); + assert_eq!(widgets(&layout(&mut app, own), Widget::Mirror), 0, "Direct Selection's own"); + let lent = tool(&app, egui::Modifiers::COMMAND); + assert_eq!(lent, "selection"); + let visible = shown(&app, lent); + assert!(widgets(&layout(&mut app, visible), Widget::Mirror) > 0, "the Selection tool's, lent by Cmd"); +} diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 5ec9e92382..b3917613b8 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -185,8 +185,8 @@ fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// What the Contextual Task Bar offers for the tool and selection in use, without the place it hangs at. The /// per-tool rules: -/// With the Artboard tool it offers Resize (Artboard Options), Duplicate, Rearrange All (with two or more -/// artboards) and Export (Export for Screens). +/// With the Artboard tool it offers Resize (Artboard Options), Duplicate, Rearrange (the selected artboards) +/// and Export (Export for Screens). /// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. /// While a basic shape tool (Rectangle, Rounded Rectangle, Ellipse, Polygon or Star) has one closed /// path selected, as after it draws one, the bar offers Edit Path, Fill and Stroke, and Shape @@ -255,7 +255,7 @@ fn offer(app: &VectorcraftApp, images_memo: &mut Memo, smooth_memo: &mut Memo) - // 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"})); if on_artboards { - artboard_items(&mut items, st.doc.artboards.len()); + artboard_items(&mut items); } else if blank { // Draw (Pencil) switches to the Pencil tool; Place Image picks files for the Place dialog. items.push((tl!("Draw (Pencil)"), "pencil", "tool.select", json!({"tool": "pencil"}))); @@ -552,10 +552,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac // Properties or the Control bar, it leaves the Image Trace panel as it was. Some((TASK_BAR_IMAGE_TRACE, _)) => crate::menus::invoke(app, "imageTrace.make", json!({"preset": "Default"})), // The Artboard tool's buttons: Artboard Options for the active artboard, as Properties' - // icon opens it; Duplicate for every selected artboard; Rearrange All Artboards. + // icon opens it; Duplicate and Rearrange for every selected artboard. Some((TASK_BAR_ARTBOARD_OPTIONS, _)) => crate::menus::invoke(app, "tool.options", json!({"tool": "artboard"})), Some((TASK_BAR_DUPLICATE_ARTBOARDS, _)) => crate::panels::artboards::duplicate_picked(app), - Some((TASK_BAR_REARRANGE_ARTBOARDS, _)) => crate::panels::artboards::open_rearrange(app), + Some((TASK_BAR_REARRANGE_ARTBOARDS, _)) => crate::panels::artboards::open_rearrange_selected(app), // The convert buttons convert the direct-selected anchors, as the Control bar's buttons do. Some((TASK_BAR_TO_CORNER, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "corner"})), Some((TASK_BAR_TO_SMOOTH, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "smooth"})), @@ -697,17 +697,15 @@ pub(crate) fn chip_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (vectorc (fill, stroke, fill_mixed, stroke_mixed) } -/// The Contextual Task Bar's items with the Artboard tool in a document of `artboards` artboards: -/// Resize, Duplicate, Rearrange All (with two or more) and Export. -fn artboard_items(items: &mut Vec, artboards: usize) { +/// The Contextual Task Bar's items with the Artboard tool: Resize, Duplicate, Rearrange (the +/// selected artboards) and Export. +fn artboard_items(items: &mut Vec) { // As in the reference app, the Artboard tool offers to resize, duplicate and export the // artboards (), // and to rearrange them (). items.push((tl!("Resize"), "move-diagonal-2", TASK_BAR_ARTBOARD_OPTIONS, json!({}))); items.push((tl!("Duplicate"), "copy", TASK_BAR_DUPLICATE_ARTBOARDS, json!({}))); - if artboards > 1 { - items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, json!({}))); - } + items.push((tl!("Rearrange"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, json!({}))); items.push((tl!("Export"), "share-2", "file.exportForScreens", json!({}))); } @@ -735,7 +733,7 @@ const TASK_BAR_ARTBOARD_OPTIONS: &str = "taskBar.artboardOptions"; /// The Contextual Task Bar's Duplicate button with the Artboard tool. const TASK_BAR_DUPLICATE_ARTBOARDS: &str = "taskBar.duplicateArtboards"; -/// The Contextual Task Bar's Rearrange All button with the Artboard tool. +/// The Contextual Task Bar's Rearrange button with the Artboard tool. const TASK_BAR_REARRANGE_ARTBOARDS: &str = "taskBar.rearrangeArtboards"; /// Whether the task bar shows the action `cmd` as its icon alone (its label names it and is its tooltip). diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6116b95e91..5ee219e73c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -138,6 +138,34 @@ fn a_release_ends_the_image_trace_hold_without_the_panel() { frame(&mut app, &ctx, vec![press(false)]); } +/// The canvas decides which tool's marks and widgets to show for the pointer where it is in the same frame: over the +/// selected blend a Cmd press selects behind, so the Selection tool's stay; moved away in the next frame, where Cmd +/// lends Direct Selection, they are Direct Selection's in that frame. +#[test] +fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + // Behind the blend, an object to select behind. + app.session.execute("shape.rectangle", &json!({"x": 20, "y": 120, "width": 360, "height": 160})).unwrap(); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 60, "y": 160, "width": 80, "height": 80})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 260, "y": 160, "width": 80, "height": 80})).unwrap()); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let blend = id(app.session.execute("object.blend.make", &json!({})).unwrap()); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let cmd_frame = |app: &mut VectorcraftApp, at: Point| { + frame(app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::COMMAND), egui::Event::PointerMoved(xf.to_screen(at))]); + app.session.hover_tool_id(&Mods { cmd: true, ..Default::default() }) + }; + // Inside the first key object, away from its anchors and the spine. + assert_eq!(cmd_frame(&mut app, Point::new(80.0, 175.0)), "selection", "over the selected blend, the press selects behind"); + assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] @@ -520,7 +548,8 @@ fn halftone_preview_hides_dot_outlines_and_keeps_selection_bounds() { app.ui_ctx = Some(ctx.clone()); // Whether the selection shows its objects' outlines; the box around it shows throughout. let outlined = |app: &mut VectorcraftApp| { - assert!(super::widgets::bounding_box(app, egui::Modifiers::NONE).is_some(), "the selection box is still drawn"); + let tool = app.session.tool_id(); + assert!(super::widgets::bounding_box(app, tool).is_some(), "the selection box is still drawn"); let app = &*app; let st = app.session.active().unwrap(); !super::selection::outlines(app, st).is_empty() @@ -4227,9 +4256,9 @@ fn task_bar_actions(app: &mut VectorcraftApp) -> Vec<&'static str> { } /// The Artboard tool's Contextual Task Bar buttons act on its selected artboards: Resize opens -/// Artboard Options for the active one, Rearrange All opens Rearrange All Artboards, Export opens -/// Export for Screens with the selected artboards checked, and Duplicate copies each selected -/// artboard in one undo step and selects the copies. +/// Artboard Options for the active one, Rearrange opens Rearrange for the selected artboards, +/// Export opens Export for Screens with the selected artboards checked, and Duplicate copies each +/// selected artboard in one undo step and selects the copies. #[test] fn the_artboard_tools_task_bar_buttons_act_on_the_selected_artboards() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -4245,8 +4274,8 @@ fn the_artboard_tools_task_bar_buttons_act_on_the_selected_artboards() { } click(&mut app, "Resize"); assert_eq!(fields_then_cancel::(&mut app)["index"], json!(2), "Artboard Options"); - click(&mut app, "Rearrange All"); - fields_then_cancel::(&mut app); + click(&mut app, "Rearrange"); + assert_eq!(fields_then_cancel::(&mut app)["indices"], json!([0, 2]), "Rearrange"); click(&mut app, "Export"); assert_eq!(fields_then_cancel::(&mut app)["boards"], json!([true, false, true]), "Export for Screens"); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 9ea52ed030..3a8f20f69c 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -183,6 +183,19 @@ impl<'a> SessionTool<'a> { tool_enter(&mut self.app(), mods, self.view) } + /// Enter places Rearrange waiting for its click: at the pointer over the canvas, else at the first selected + /// artboard's top-left → whether one was waiting. The Enter that confirmed its dialog is not taken. + fn place_rearrange(&self) -> bool { + use crate::dialogs::rearrange_artboards as rearrange; + let mut app = self.app(); + if !rearrange::refresh_placement(&mut app) || !rearrange::armed(&app) { + return false; + } + let at = app.hover_doc; + rearrange::place(&mut app, at); + true + } + /// A key the tool does not claim while its gesture runs: arrows and digits still reach it, with no modifier (a /// grid's rows and columns, the Perspective Selection tool's planes) → whether it took the key; other keys are /// [`Self::again`]'s. @@ -259,6 +272,13 @@ impl CanvasTool for SessionTool<'_> { app.canvas.last_drag = None; return ToolAction::Claimed; } + // Rearrange waiting for its click takes the press whole: the grid's top-left goes where it was pressed, and the + // tool gets no press, drag or release. + if crate::dialogs::rearrange_artboards::refresh_placement(&mut app) && !app.any_dialog_open() { + let at = pointer_event(PointerKind::Down, pointer, cx).pos; + crate::dialogs::rearrange_artboards::place(&mut app, Some(at)); + return ToolAction::Done; + } // Text typed into a panel's field (its preview) goes to the object it edits before the press can select another. if app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) { if let Err(e) = app.session.commit_interaction() { @@ -353,8 +373,12 @@ impl CanvasTool for SessionTool<'_> { let switched = follow == PointerKind::DoubleClick && before != "type" && self.app().session.tool_id() == "type"; if switched { self.app().session.set_tool_option("prevTool", &json!(before)); - self.send(PointerKind::Down, pointer, cx); - self.send(PointerKind::Up, pointer, cx); + for kind in [PointerKind::Down, PointerKind::Up] { + // Without Cmd, so the Type tool takes the click instead of lending a selection tool. + let mut ev = pointer_event(kind, pointer, cx); + ev.mods.cmd = false; + dispatch(&mut self.app(), &ev, self.view); + } } } @@ -458,6 +482,9 @@ impl CanvasTool for SessionTool<'_> { ToolKey::Submit => { // In Presentation Mode Enter opens no dialog: the tool takes none. let presenting = self.app().ui.screen_mode == 3; + if !presenting && self.place_rearrange() { + return true; + } !presenting && (self.send_key(EngineKey::Enter, held) || self.enter(held)) } ToolKey::Cancel => { @@ -465,6 +492,13 @@ impl CanvasTool for SessionTool<'_> { if self.app().ui.screen_mode == 3 { return false; } + // Escape drops Rearrange waiting for its click. + let mut app = self.app(); + if crate::dialogs::rearrange_artboards::refresh_placement(&mut app) { + crate::dialogs::rearrange_artboards::cancel_placement(&mut app); + return true; + } + drop(app); let ends = self.app().session.tool_ends_on_escape(self.view); if self.send_key(EngineKey::Escape, held) { return true; @@ -607,6 +641,10 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too (PressPhase::Idle, _) | (_, None) => None, (_, Some(view)) => ui.input(|i| i.pointer.hover_pos()).map(|p| view.to_doc(p)), }; + // Rearrange waiting for its click: dropped with its document or tool, and from the next pass Enter places it. + if crate::dialogs::rearrange_artboards::refresh_placement(app) { + crate::dialogs::rearrange_artboards::arm(app); + } show_overlays(app, ui, pass, view_info); response } @@ -636,6 +674,8 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in } // Gap Options' Preview shows the gaps it finds. let mut extra = crate::dialogs::live_paint_gaps::overlays(app); + // Rearrange waiting for its click shows where its artboards go. + extra.extend(crate::dialogs::rearrange_artboards::placement_overlays(app)); if app.ui.view.edges && !revolve { if app.ui.view.text_threads { extra.extend(super::marks::thread_overlays(app, space.view.zoom)); @@ -664,7 +704,7 @@ pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: ViewInfo) { return; } // A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key. - if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() { + if ev.kind == PointerKind::Down && !app.session.press_lends_tool(ev, view) { crate::shortcuts::note_tool_use(app); } let r = app.session.pointer(ev, view); diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 2a1b7bb4c7..204853bd98 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -40,34 +40,34 @@ fn doc_point(p: vectorcraft_geom::Point) -> Point { Point::new(p.x, p.y) } -/// Is the active tool a shape tool that is not drawing a shape? While it draws it shows none of its widgets; -/// adjusting a widget, it shows them. -fn shape_tool_idle(app: &VectorcraftApp) -> bool { - vectorcraft_tools::shape::shows_shape_widgets(app.session.tool_id()) && !(app.session.tool_busy() && !app.session.tool_transforming()) +/// Is the active tool a shape tool that is not drawing a shape, and `tool`, the tool whose widgets the canvas shows, +/// is that tool (Cmd lends no other)? While it draws it shows none of its widgets; adjusting a widget, it shows them. +fn shape_tool_idle(app: &VectorcraftApp, tool: &str) -> bool { + tool == app.session.tool_id() + && vectorcraft_tools::shape::shows_shape_widgets(tool) + && !(app.session.tool_busy() && !app.session.tool_transforming()) } /// The bounding box to draw, if any: the Selection tool's (rotated with the objects after a rotation), also -/// shown by the shape tools that keep a shape just drawn ready to adjust, and by Cmd held over another tool, -/// which lends the Selection tool to a press. It hides while a drag moves, rotates or resizes the selection, so +/// shown by the shape tools that keep a shape just drawn ready to adjust, and by Cmd held over another tool +/// where it lends the Selection tool to a press. It hides while a drag moves, rotates or resizes the selection, so /// only the art is seen going with the pointer; a handle resize keeps it at the changing bounds. With General › /// Show Bounding Box While Moving and Drawing on, a move draws it where the drag has moved the selection and a /// shape tool draws it around the shape being drawn. With Real-time Drawing off the document stays at the /// drag's snapshot, so a resize or a shape being drawn measures the box from the pending preview; a shape being -/// drawn shows no box until a preview has made it. `held` is the modifiers held now; a second pass of a frame -/// reads the same held state, which is not an event. +/// drawn shows no box until a preview has made it. `tool` is the tool whose marks the canvas shows +/// ([`super::shown_tool`]): while Cmd is held, the selection tool a press borrows, so the box shows only when that +/// is the Selection tool, whose handles take the press. // PLAN: the sheet's `(app, st)` cannot work: `selection_box` and `deferred_transform_box` need `&mut app`, so the // active document is read inside. -pub(super) fn bounding_box(app: &mut VectorcraftApp, held: egui::Modifiers) -> Option { +pub(super) fn bounding_box(app: &mut VectorcraftApp, tool: &str) -> Option { let resizing = app.session.tool_resizing(); let move_box = app.session.move_drag_box(); let drawing_boxed = app.session.draws_new_shape_box(); let follows = resizing || move_box.is_some() || drawing_boxed; - let selection_tool = app.session.tool_id() == "selection"; - let shape_tool = vectorcraft_tools::shape::shows_shape_widgets(app.session.tool_id()); - // PLAN: assumed `super::mods(egui::Modifiers, bool) -> Mods` stays at `canvas` (sheet w20). - let held = super::mods(held, false); - let lends_selection = !app.session.tool_busy() && app.session.lent_tool_id(&held) == Some("selection"); - let show_box = (selection_tool || lends_selection || (shape_tool && (!app.session.tool_busy() || follows))) + let own = tool == app.session.tool_id(); + let shape_tool = own && vectorcraft_tools::shape::shows_shape_widgets(tool); + let show_box = (tool == "selection" || (shape_tool && (!app.session.tool_busy() || follows))) && (follows || !app.session.tool_transforming()) && app.ui.view.bounding_box; if !show_box { @@ -114,13 +114,13 @@ fn corner_target(doc: &Document, id: NodeId, indices: &[usize]) -> Option Option)>> { - let tool = app.session.tool_id(); +pub(super) fn corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option)>> { let direct = tool == "directSelection"; - if !(matches!(tool, "selection" | "directSelection") || shape_tool_idle(app)) { + if !(matches!(tool, "selection" | "directSelection") || shape_tool_idle(app, tool)) { return None; } let st = app.session.active()?; @@ -222,11 +222,11 @@ impl ShapeWidgets { /// The widgets of the active document at `zoom` (screen points per document unit) under a view turned by /// `rotation`. `edges` is View › Show Edges: the type, side and pie widgets go with it, the blend and Objects /// on Path widgets are controls and stay. `shown` is the bounding box on show, which the type and side - /// widgets sit beside; a shape being drawn has neither. - fn of(app: &VectorcraftApp, edges: bool, shown: Option<&ShownBox>, zoom: f64, rotation: f64) -> Self { + /// widgets sit beside; a shape being drawn has neither. `tool` is the tool whose widgets the canvas shows + /// ([`super::shown_tool`]): while Cmd is held, the selection tool a press borrows. + fn of(app: &VectorcraftApp, tool: &str, edges: bool, shown: Option<&ShownBox>, zoom: f64, rotation: f64) -> Self { let mut marks = vec![]; let Some(st) = app.session.active() else { return Self::new(marks) }; - let tool = app.session.tool_id(); let layer = |id| data_color(st.doc.layer_color(id)); let shape_widgets = app.ui.view.shape_widgets; if edges { @@ -240,7 +240,7 @@ impl ShapeWidgets { } } // Pie widgets stay while one is dragged, each joined to the outline's point at its angle. - if app.ui.view.bounding_box && shape_widgets && (tool == "selection" || shape_tool_idle(app)) { + if app.ui.view.bounding_box && shape_widgets && (tool == "selection" || shape_tool_idle(app, tool)) { for w in pie::PieWidget::of(&st.doc, &st.selection, zoom) { marks.push(Mark::new(Form::Disc, Filling::Hollow, w.at, pie::RADIUS_PX, layer(w.id)).joined(w.on)); } @@ -353,16 +353,18 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &craft::u // PLAN: assumed the body's rect is the canvas rect the controls are shown at. let rect = ui.max_rect(); let edges = app.ui.view.edges; - let shown = if edges { bounding_box(app, ui.input(|i| i.modifiers)) } else { None }; + // While Cmd is held, the widgets of the selection tool a press borrows. + let tool = super::shown_tool(app, ui.ctx()); + let shown = if edges { bounding_box(app, tool) } else { None }; if edges { - for (at, (color, targets)) in corners(app, space.view.zoom).into_iter().flatten().enumerate() { + for (at, (color, targets)) in corners(app, tool, space.view.zoom).into_iter().flatten().enumerate() { CornerWidgets::new("Live Corners", Bind::given(targets)).id_salt(at).reach(TransformReach::Shown).color(color).show_at(ui, rect); } if let Some(b) = &shown { show_box(ui, rect, b); } } - let widgets = ShapeWidgets::of(app, edges, shown.as_ref(), space.view.zoom, space.view.rotation); + let widgets = ShapeWidgets::of(app, tool, edges, shown.as_ref(), space.view.zoom, space.view.rotation); if !widgets.marks.is_empty() { widgets.show_at(ui, rect); } diff --git a/crates/ui-egui/src/canvas/widgets/tests.rs b/crates/ui-egui/src/canvas/widgets/tests.rs index bb16e33652..c8670f7be9 100644 --- a/crates/ui-egui/src/canvas/widgets/tests.rs +++ b/crates/ui-egui/src/canvas/widgets/tests.rs @@ -37,10 +37,28 @@ fn layer(app: &VectorcraftApp, id: u64) -> DataColor { data_color(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))) } -fn marks(app: &mut VectorcraftApp) -> Vec { - let shown = bounding_box(app, NONE); +/// The tool whose widgets show with `held` and the pointer off the canvas: while Cmd is held, the selection tool it +/// lends. +fn shown(app: &VectorcraftApp, held: egui::Modifiers) -> &'static str { + app.session.hover_tool_id(&super::super::mods(held, false)) +} + +/// The bounding box on show with `held`. +fn boxed(app: &mut VectorcraftApp, held: egui::Modifiers) -> Option { + let tool = shown(app, held); + bounding_box(app, tool) +} + +/// The shape widgets on show with `held`. +fn marks_with(app: &mut VectorcraftApp, held: egui::Modifiers) -> Vec { + let tool = shown(app, held); + let shown = bounding_box(app, tool); let zoom = app.view_info().zoom; - ShapeWidgets::of(app, true, shown.as_ref(), zoom, 0.0).marks + ShapeWidgets::of(app, tool, true, shown.as_ref(), zoom, 0.0).marks +} + +fn marks(app: &mut VectorcraftApp) -> Vec { + marks_with(app, NONE) } fn count(marks: &[Mark], form: Form, radius: f32) -> usize { @@ -49,7 +67,7 @@ fn count(marks: &[Mark], form: Form, radius: f32) -> usize { fn corner_count(app: &VectorcraftApp) -> usize { let zoom = app.view_info().zoom; - corners(app, zoom).map_or(0, |groups| groups.iter().flat_map(|(_, targets)| targets).map(|t| t.corners.len()).sum()) + corners(app, app.session.tool_id(), zoom).map_or(0, |groups| groups.iter().flat_map(|(_, targets)| targets).map(|t| t.corners.len()).sum()) } #[test] @@ -59,9 +77,9 @@ fn real_time_drawing_off_moves_the_bounding_box_with_a_move_drag() { let mut app = new_app(&[("realTimeDrawing", json!(real_time)), ("boundingBoxWhileMovingAndDrawing", json!(while_moving))]); make(&mut app, "shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 60})); app.select_tool("selection"); - assert!(bounding_box(&mut app, NONE).is_some(), "{what}: at rest"); + assert!(boxed(&mut app, NONE).is_some(), "{what}: at rest"); drag(&mut app, (150.0, 130.0), (250.0, 230.0)); - let during = bounding_box(&mut app, NONE); + let during = boxed(&mut app, NONE); if real_time && !while_moving { assert!(during.is_none(), "{what}: hidden while the art moves"); } else { @@ -69,7 +87,7 @@ fn real_time_drawing_off_moves_the_bounding_box_with_a_move_drag() { assert_eq!((rect.x0, rect.y0), (200.0, 200.0), "{what}: where the drag carries the selection"); } pointer(&mut app, PointerKind::Up, (250.0, 230.0)); - assert_eq!(bounding_box(&mut app, NONE).unwrap().obox.rect.x0, 200.0, "{what}: at rest after the release"); + assert_eq!(boxed(&mut app, NONE).unwrap().obox.rect.x0, 200.0, "{what}: at rest after the release"); } } @@ -80,7 +98,7 @@ fn corner_widgets_hide_above_the_preference_angle() { app.select_tool("selection"); assert_eq!(corner_count(&app), 4); app.session.execute("prefs.set", &json!({"key": "hideCornerWidgetAbove", "value": 80})).unwrap(); - assert!(corners(&app, app.view_info().zoom).is_none()); + assert!(corners(&app, app.session.tool_id(), app.view_info().zoom).is_none()); } #[test] @@ -89,12 +107,12 @@ fn a_resize_drag_keeps_the_bounding_box_at_the_new_bounds() { let mut app = new_app(&[("realTimeDrawing", json!(real_time))]); make(&mut app, "shape.ellipse", json!({"x": 100, "y": 100, "width": 100, "height": 60})); app.select_tool("selection"); - let before = bounding_box(&mut app, NONE).unwrap(); + let before = boxed(&mut app, NONE).unwrap(); drag(&mut app, (200.0, 160.0), (263.0, 211.0)); assert!(app.session.tool_resizing(), "real time {real_time}: the handle was hit"); - let during = bounding_box(&mut app, NONE).unwrap(); + let during = boxed(&mut app, NONE).unwrap(); pointer(&mut app, PointerKind::Up, (263.0, 211.0)); - let after = bounding_box(&mut app, NONE).unwrap(); + let after = boxed(&mut app, NONE).unwrap(); assert_ne!(after.obox.rect, before.obox.rect, "real time {real_time}: the drag resized the ellipse"); assert_eq!(during.obox.rect, after.obox.rect, "real time {real_time}: the box followed the drag"); } @@ -106,13 +124,13 @@ fn a_move_drag_keeps_the_bounding_box_where_the_drag_carries_the_selection() { make(&mut app, "shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})); app.select_tool("selection"); drag(&mut app, (150.0, 150.0), (170.0, 160.0)); - let rect = bounding_box(&mut app, NONE).unwrap().obox.rect; + let rect = boxed(&mut app, NONE).unwrap().obox.rect; assert_eq!((rect.x0, rect.y0), (120.0, 110.0)); app.ui.view.bounding_box = false; - assert!(bounding_box(&mut app, NONE).is_none(), "View › Hide Bounding Box"); + assert!(boxed(&mut app, NONE).is_none(), "View › Hide Bounding Box"); app.ui.view.bounding_box = true; app.session.execute("prefs.set", &json!({"key": "boundingBoxWhileMovingAndDrawing", "value": false})).unwrap(); - assert!(bounding_box(&mut app, NONE).is_none(), "off: hidden while the selection moves"); + assert!(boxed(&mut app, NONE).is_none(), "off: hidden while the selection moves"); } #[test] @@ -124,12 +142,12 @@ fn a_shape_being_drawn_shows_its_bounding_box() { app.select_tool(tool); drag(&mut app, (150.0, 120.0), (180.0, 140.0)); assert!(app.session.draws_new_shape_box(), "{what}"); - let first = bounding_box(&mut app, NONE).unwrap_or_else(|| panic!("{what}: no box")).obox; + let first = boxed(&mut app, NONE).unwrap_or_else(|| panic!("{what}: no box")).obox; pointer(&mut app, PointerKind::Drag, (210.0, 170.0)); - let during = bounding_box(&mut app, NONE).unwrap().obox; + let during = boxed(&mut app, NONE).unwrap().obox; assert_ne!(first.rect, during.rect, "{what}: the box follows the drag"); app.session.execute("prefs.set", &json!({"key": "boundingBoxWhileMovingAndDrawing", "value": false})).unwrap(); - assert!(bounding_box(&mut app, NONE).is_none(), "{what}: off, no box while drawing"); + assert!(boxed(&mut app, NONE).is_none(), "{what}: off, no box while drawing"); } } } @@ -141,12 +159,12 @@ fn a_failed_preview_of_a_shape_being_drawn_shows_no_bounding_box() { make(&mut app, "shape.rectangle", json!({"x": 20, "y": 20, "width": 30, "height": 30})); app.select_tool("rectangle"); drag(&mut app, (150.0, 120.0), (180.0, 140.0)); - assert!(bounding_box(&mut app, NONE).is_some(), "real time {real_time}: the box of the shape being drawn"); + assert!(boxed(&mut app, NONE).is_some(), "real time {real_time}: the box of the shape being drawn"); assert!(app.session.preview("shape.rectangle", &json!({"x": "left"})).is_err()); assert!(app.session.draws_new_shape_box() && app.session.interaction_unapplied()); - assert!(bounding_box(&mut app, NONE).is_none(), "real time {real_time}: not the old selection's box"); + assert!(boxed(&mut app, NONE).is_none(), "real time {real_time}: not the old selection's box"); pointer(&mut app, PointerKind::Drag, (210.0, 170.0)); - assert!(bounding_box(&mut app, NONE).is_some(), "real time {real_time}: the next preview shows it again"); + assert!(boxed(&mut app, NONE).is_some(), "real time {real_time}: the next preview shows it again"); } } @@ -161,7 +179,7 @@ fn a_shape_being_drawn_has_its_box_in_its_own_layers_color() { assert_ne!(old_color, new_color); app.select_tool("rectangle"); drag(&mut app, (150.0, 120.0), (180.0, 140.0)); - assert_eq!(bounding_box(&mut app, NONE).unwrap().color, new_color, "real time {real_time}"); + assert_eq!(boxed(&mut app, NONE).unwrap().color, new_color, "real time {real_time}"); } } @@ -174,7 +192,7 @@ fn a_shape_being_drawn_has_no_type_widget() { assert_eq!(count(&marks(&mut app), Form::Disc, typewidget::RADIUS_PX), 1, "the selected type's widget"); app.select_tool("rectangle"); drag(&mut app, (150.0, 120.0), (210.0, 170.0)); - assert!(bounding_box(&mut app, NONE).is_some(), "the box of the shape being drawn"); + assert!(boxed(&mut app, NONE).is_some(), "the box of the shape being drawn"); assert_eq!(count(&marks(&mut app), Form::Disc, typewidget::RADIUS_PX), 0, "no type widget beside it"); } @@ -189,7 +207,7 @@ fn freehand_and_pen_drawing_show_no_bounding_box() { pointer(&mut app, PointerKind::Drag, at); } assert!(!app.session.draws_new_shape_box(), "{tool}"); - assert!(bounding_box(&mut app, NONE).is_none(), "{tool}: no box while it draws"); + assert!(boxed(&mut app, NONE).is_none(), "{tool}: no box while it draws"); pointer(&mut app, PointerKind::Up, (210.0, 170.0)); } } @@ -216,10 +234,10 @@ fn a_move_rotate_or_corner_radius_drag_hides_the_bounding_box() { ((corner.x, corner.y), (corner.x + 10.0, corner.y + 10.0)) } }; - assert!(bounding_box(&mut app, NONE).is_some(), "{what}: at rest"); + assert!(boxed(&mut app, NONE).is_some(), "{what}: at rest"); drag(&mut app, from, to); assert!(app.session.tool_transforming(), "{what}"); - assert!(bounding_box(&mut app, NONE).is_none(), "{what}: hidden during the drag"); + assert!(boxed(&mut app, NONE).is_none(), "{what}: hidden during the drag"); pointer(&mut app, PointerKind::Up, to); } } @@ -229,9 +247,9 @@ fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { let mut app = new_app(&[]); make(&mut app, "shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})); app.select_tool("directSelection"); - assert!(bounding_box(&mut app, NONE).is_none(), "Direct Selection alone shows no box"); - assert!(bounding_box(&mut app, egui::Modifiers::COMMAND).is_some(), "Cmd held shows the Selection tool's box"); - assert!(bounding_box(&mut app, NONE).is_none(), "gone once Cmd is released"); + assert!(boxed(&mut app, NONE).is_none(), "Direct Selection alone shows no box"); + assert!(boxed(&mut app, egui::Modifiers::COMMAND).is_some(), "Cmd held shows the Selection tool's box"); + assert!(boxed(&mut app, NONE).is_none(), "gone once Cmd is released"); assert!(app.ui.view.bounding_box, "View › Show Bounding Box is unchanged"); } @@ -279,6 +297,39 @@ fn a_selected_ellipse_shows_its_pie_widgets() { assert_eq!(count(&marks(&mut app), Form::Disc, pie::RADIUS_PX), 0, "no bounding box, no widgets"); } +/// With a shape tool, Cmd held lends the selection tool chosen last; when that is Direct Selection, which does not +/// press them, a selected live ellipse's pie widgets hide while the key is down. +#[test] +fn pie_widgets_hide_while_cmd_lends_direct_selection() { + let mut app = new_app(&[]); + make(&mut app, "shape.ellipse", json!({"x": 100, "y": 100, "width": 200, "height": 100})); + app.session.execute("object.setLiveShape", &json!({"pieStart": 0, "pieEnd": 90})).unwrap(); + app.select_tool("directSelection"); + app.select_tool("ellipse"); + let pies = |app: &mut VectorcraftApp, held| count(&marks_with(app, held), Form::Disc, pie::RADIUS_PX); + assert_eq!(pies(&mut app, NONE), 2, "the Ellipse tool shows them"); + assert_eq!(pies(&mut app, egui::Modifiers::COMMAND), 0, "hidden while Cmd lends Direct Selection"); + assert_eq!(pies(&mut app, NONE), 2, "back when the key is let go"); +} + +/// With the Selection tool, Cmd held lends Direct Selection away from the selection, and a selected blend's widgets, +/// which only the Selection and Blend tools press, hide while the key is down. +#[test] +fn blend_widgets_hide_while_cmd_lends_direct_selection() { + let mut app = new_app(&[]); + let a = make(&mut app, "shape.rectangle", json!({"x": 90, "y": 190, "width": 20, "height": 20})); + let b = make(&mut app, "shape.rectangle", json!({"x": 290, "y": 190, "width": 20, "height": 20})); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let blend = make(&mut app, "object.blend.make", json!({})); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); + let widgets = |app: &mut VectorcraftApp, held| count(&marks_with(app, held), Form::Disc, blendwidget::RADIUS_PX); + let plain = widgets(&mut app, NONE); + assert!(plain >= 1, "the Appearance widget: {plain}"); + assert_eq!(widgets(&mut app, egui::Modifiers::COMMAND), 0, "hidden while Cmd lends Direct Selection"); + assert_eq!(widgets(&mut app, NONE), plain, "back when the key is let go"); +} + #[test] fn a_selected_polygon_shows_its_side_widget() { let mut app = new_app(&[]); @@ -310,7 +361,7 @@ fn hidden_shape_widgets_leave_the_bounding_box() { let drawn = |app: &mut VectorcraftApp, id: u64| { app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); let m = marks(app); - (corner_count(app), count(&m, Form::Diamond, sidewidget::RADIUS_PX), count(&m, Form::Disc, pie::RADIUS_PX), bounding_box(app, NONE).is_some()) + (corner_count(app), count(&m, Form::Diamond, sidewidget::RADIUS_PX), count(&m, Form::Disc, pie::RADIUS_PX), boxed(app, NONE).is_some()) }; for tool in ["selection", "polygon", "rectangle"] { app.select_tool(tool); @@ -363,7 +414,7 @@ fn a_selected_objects_on_path_group_shows_its_rotate_all_widget() { app.run("select.set", json!({"ids": [group]})).unwrap(); let zoom = app.view_info().zoom; app.select_tool("selection"); - assert_eq!(count(&ShapeWidgets::of(&app, false, None, zoom, 0.0).marks, Form::Disc, r), 1); + assert_eq!(count(&ShapeWidgets::of(&app, "selection", false, None, zoom, 0.0).marks, Form::Disc, r), 1); } #[test] diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 2088bfa1b4..ab90d71dc2 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -23,14 +23,18 @@ pub(crate) mod rank { pub const SELECT_SIMILAR: u8 = 1; /// The inline X/Y/W/H fields and the Snapping menu. pub const FIELDS: u8 = 2; + /// The type groups (Character, Paragraph and area type's vertical alignment) and the Align buttons after them: + /// they leave after Select Similar, Snapping and the X/Y/W/H fields and before every other member, so Opacity, + /// the Style picker and Recolor Artwork show while type is selected. + pub const TYPE: u8 = 3; /// The parts of a group that its other members work without: the width profile, Recolor Artwork, Global Edit /// Options, Document Setup, an image's Edit Original. - pub const DETAIL: u8 = 3; + pub const DETAIL: u8 = 4; /// The Opacity link and field: they leave before the groups, so the narrower Style link and picker after them /// can show without them. - pub const OPACITY: u8 = 4; + pub const OPACITY: u8 = 5; /// Every other member of the bar. - pub const GROUP: u8 = 5; + pub const GROUP: u8 = 6; } /// An anchor button: icon, tooltip, command and the convert command's `to`. @@ -597,14 +601,21 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { if group_on(app, "graphicStyle") && count > 0 { style_group(app, ui); } - if group_on(app, "character") { - crate::panels::character::control_bar(app, ui); + let (character, paragraph) = (group_on(app, "character"), group_on(app, "paragraph")); + let typed = (character || paragraph) && crate::panels::character::text_style(app).is_some(); + if typed && character { + ranked(ui, rank::TYPE, |ui| { + crate::panels::character::control_bar(app, ui); + }); } - if group_on(app, "paragraph") { - crate::panels::paragraph::control_bar(app, ui); + if typed && paragraph { + ranked(ui, rank::TYPE, |ui| { + crate::panels::paragraph::control_bar(app, ui); + }); } - if group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some() { - group(ui, rank::GROUP, |ui| { + let vertical = group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some(); + if vertical { + group(ui, rank::TYPE, |ui| { crate::panels::properties::vertical_align::buttons(app, ui); }); } @@ -615,7 +626,9 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { return; } if group_on(app, "alignDistribute") { - group(ui, rank::GROUP, |ui| crate::panels::align::control_bar_strip(app, ui)); + // After the type groups, the Align buttons take their rank and, coming last, leave first. + let rank = if typed || vertical { rank::TYPE } else { rank::GROUP }; + group(ui, rank, |ui| crate::panels::align::control_bar_strip(app, ui)); } if transform { // The Transform link opens the whole Transform panel in a popover; X/Y/W/H follow inline while the diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index e1d1fa7636..11cd8753a0 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -40,6 +40,14 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { ("Shift+Click", true), (" to add", false), ], + "groupSelection" => &[ + ("Click", true), + (" an object in a group to select it | ", false), + ("Click again", true), + (" to add the group it is in | ", false), + ("Shift+Click", true), + (" to add", false), + ], "pen" => &[ ("Click", true), (" to add a corner point | ", false), @@ -254,7 +262,9 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let segments: Vec<(Cow<'static, str>, bool)> = match crate::dialogs::three_d::hint(app) { Some(hint) => vec![(Cow::Borrowed(hint), false)], None => { - let tool = app.session.tool_id(); + // While Cmd is held, the hints of the selection tool it lends. + let held = crate::canvas::held_mods(ui.ctx()); + let tool = app.session.shown_tool_id(&held); let hint = if tool == "zoom" && crate::canvas::animated_zoom(&app.session.prefs) { ANIMATED_ZOOM_HINT } else { tool }; hint_segments(app, hint) } diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index c3fb782f18..b706d9875b 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -15,7 +15,8 @@ use craft::ui::text::ZoomField; /// Shows the status bar: zoom, rotation, artboard navigator, the info field with its Show menu, the readouts, Stop, /// the background-work progress and last the message, so a narrow bar elides the message before anything else. pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { - let (info, next) = info_text(app); + let held = crate::canvas::held_mods(ui.ctx()); + let (info, next) = info_text(app, &held); if let Some(secs) = next { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } @@ -228,12 +229,13 @@ pub fn set_status_bar_show(app: &mut VectorcraftApp, p: &serde_json::Value) -> R } /// The info field's text for the choice in the Show menu, and for Date and Time the seconds until -/// the minute it shows ends (when the bar draws again). -pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option) { +/// the minute it shows ends (when the bar draws again). Current Tool names the selection tool Cmd +/// lends while it is held (`held`). +pub(super) fn info_text(app: &VectorcraftApp, held: &vectorcraft_tools::Mods) -> (String, Option) { let st = app.session.active(); match app.ui.status_bar_show { StatusBarShow::CurrentTool => { - let tool = vectorcraft_tools::tool_info(app.session.tool_id()) + let tool = vectorcraft_tools::tool_info(app.session.shown_tool_id(held)) .map(|t| { // The catalog keys carry the full label ("Selection Tool"); only English drops the suffix. let shown = tl!(t.label); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index acc0ecf522..5192f53df0 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -528,6 +528,18 @@ fn combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility() { assert!(!described.as_deref().is_some_and(|d| d.contains("• ")) && shown.is_empty(), "a later message lists nothing: {described:?} {shown:?}"); } +/// While Cmd/Ctrl is held, Current Tool names the selection tool a press would borrow: Direct +/// Selection with the Selection tool chosen, and the Selection tool again once the key is let go. +#[test] +fn current_tool_names_the_selection_tool_cmd_lends() { + let bar = status_readout_app(); + let app = bar.app(); + let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() }; + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(super::status_bar::info_text(&app, &cmd).0, "Direct Selection"); + assert_eq!(super::status_bar::info_text(&app, &Default::default()).0, "Selection"); +} + /// The status bar's info field shows the readout `view.statusBarShow` chooses: the navigator's /// artboard name, the tool in use, the date and time, the undo and redo counts, or the document's /// color profile. @@ -564,7 +576,7 @@ fn the_status_bar_info_field_shows_the_chosen_readout() { // The labels take the UI language's colon (#7991). let fr = crate::i18n::Lang::from_code("fr").unwrap(); crate::i18n::set_current(fr); - let (french, _) = super::status_bar::info_text(&bar.app()); + let (french, _) = super::status_bar::info_text(&bar.app(), &Default::default()); crate::i18n::set_current(crate::i18n::Lang::EN); assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos"))); @@ -2431,6 +2443,58 @@ fn the_control_bar_leaves_members_out_in_its_priority_order() { assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Align buttons without the fields"); } +/// With type selected, the Character and Paragraph groups leave the Control bar before Opacity and the Style group: at +/// every width that shows the Character group, Opacity, Recolor Artwork and the Style picker show too, the Paragraph +/// group leaves before the Character group, the Align buttons leave before the Paragraph group, and some width shows +/// Opacity without them. +#[test] +fn the_type_groups_leave_the_control_bar_before_opacity_and_style() { + 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 text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Character:", "Paragraph:", "Opacity:", "Recolor Artwork", "Style:", "Horizontal Align Left"]; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s.iter().all(|shown| *shown)), "a wide bar shows {names:?}"); + for s in &seen { + assert!(!s[0] || s[2..5].iter().all(|shown| *shown), "the Character group shows only with {:?}: {s:?}", &names[2..5]); + assert!(!s[1] || s[0], "the Paragraph group shows only with the Character group: {s:?}"); + assert!(!s[5] || s[1], "the Align buttons show only with the Paragraph group: {s:?}"); + } + assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group"); +} + +/// With area type selected, its vertical alignment buttons leave the Control bar before Opacity and the Style group, +/// and after the Align buttons that follow them, with the Character and Paragraph groups shown and with both off. +#[test] +fn the_vertical_alignment_buttons_leave_the_control_bar_before_opacity_and_style() { + 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 area = json!({"x": 10, "y": 10, "text": "Hi", "area": {"width": 100, "height": 120}}); + let text = app.run("text.create", area).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Align Top", "Opacity:", "Recolor Artwork", "Style:", "Horizontal Align Left", "Paragraph:"]; + for type_groups in [true, false] { + for group in ["character", "paragraph"] { + bar.app().run("window.control.options", json!({ "group": group, "visible": type_groups })).unwrap(); + } + let case = if type_groups { "with the type groups" } else { "without the type groups" }; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s[..5].iter().all(|shown| *shown)), "{case}: a wide bar shows {:?}", &names[..5]); + for s in &seen { + assert!(!s[0] || s[1..4].iter().all(|shown| *shown), "{case}: Align Top shows only with {:?}: {s:?}", &names[1..4]); + assert!(!s[4] || s[0], "{case}: the Align buttons show only with Align Top: {s:?}"); + assert!(type_groups || !s[5], "{case}: the Paragraph group is off: {s:?}"); + assert!(!type_groups || !s[0] || s[5], "{case}: Align Top shows only with the Paragraph group: {s:?}"); + } + assert!(seen.iter().any(|s| s[1] && !s[0]), "{case}: some width shows Opacity without Align Top"); + } +} + /// The names of the bar's X, Y, W and H fields, in their order. const BAR_FIELDS: [&str; 4] = ["X position", "Y position", "Width", "Height"]; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1aae334de1..7ce5c83baa 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -213,6 +213,8 @@ mod tests_raster_formats; #[cfg(test)] mod tests_raster_supplied_options; +#[cfg(test)] +mod tests_custom_rows; #[cfg(test)] mod tests_dxf; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 19cf5a251a..4d66df8ecb 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -34,7 +34,7 @@ use craft::ui::layout_components::Row; use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::pickers::Select; -use craft::ui::primitives::ContentPainterCx; +use craft::ui::primitives::{ContentPainterCx, StrokeWidth}; use craft::ui::runtime::env::{Label, UnitKind}; use craft::ui::text::NumberField; use egui::{Color32, Rect, Stroke, pos2, vec2}; @@ -612,14 +612,26 @@ pub(super) fn stroke_preview(cx: &ContentPainterCx, rect: Rect, doc: Option<&Doc crate::panels::brushes::paint_definition(cx, rect, doc, &Value::Object(def)); } +/// The nib preview's paper, white like the brush previews'. +const NIB_PAPER: Color32 = Color32::WHITE; +/// The nib at the brush's values, black on the paper. +const NIB_INK: Color32 = Color32::BLACK; +/// The nib preview's center lines, a light gray on its white paper. +const NIB_GUIDE: Color32 = Color32::from_gray(220); +/// The nib preview's lightest and heaviest nibs, in a gray behind the black nib at the brush's values. +const NIB_RANGE: Color32 = Color32::from_gray(200); +/// The room the nib preview keeps between its largest nib and each edge, in points. +const NIB_MARGIN: f32 = 6.0; + /// The nib of `c` at its values (black), and — for values that vary — at their lightest and /// heaviest (grey), on white like the brush previews, its largest nib filling the box. fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { - let p = &cx.painter; - p.rect_filled(r, 0.0, Color32::WHITE); - let guide = Stroke::new(1.0, Color32::from_gray(220)); - p.line_segment([pos2(r.left(), r.center().y), pos2(r.right(), r.center().y)], guide); - p.line_segment([pos2(r.center().x, r.top()), pos2(r.center().x, r.bottom())], guide); + let guide = Stroke::new(cx.stroke_width(StrokeWidth::Thin), NIB_GUIDE); + cx.data_shapes([ + egui::Shape::rect_filled(r, 0.0, NIB_PAPER), + egui::Shape::line_segment([pos2(r.left(), r.center().y), pos2(r.right(), r.center().y)], guide), + egui::Shape::line_segment([pos2(r.center().x, r.top()), pos2(r.center().x, r.bottom())], guide), + ]); let values = [c.angle, c.roundness, c.size]; let at = |sign: f64| -> [f64; 3] { let mut v = values; @@ -633,9 +645,10 @@ fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { }; let nibs = [at(-1.0), at(1.0), values]; let largest = nibs.iter().map(|n| n[2]).fold(0.0, f64::max).max(1e-6); - let scale = (r.height().min(r.width()) - 12.0) / largest as f32; + let scale = (r.height().min(r.width()) - 2.0 * NIB_MARGIN) / largest as f32; + let mut shapes = Vec::with_capacity(nibs.len()); for (k, [angle, round, size]) in nibs.into_iter().enumerate() { - let fill = if k < 2 { Color32::from_gray(200) } else { Color32::BLACK }; + let fill = if k < 2 { NIB_RANGE } else { NIB_INK }; let (a, b) = ((size as f32 * scale / 2.0).max(0.5), (size * round.clamp(1.0, 100.0) / 100.0) as f32 * scale / 2.0); let th = (angle as f32).to_radians(); let (u, v) = (vec2(th.cos(), -th.sin()), vec2(th.sin(), th.cos())); @@ -645,8 +658,9 @@ fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { r.center() + u * (a * s.cos()) + v * (b.max(0.5) * s.sin()) }) .collect(); - p.add(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); + shapes.push(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); } + cx.data_shapes(shapes); } /// OK: edit the brush (and rename it). A name another brush has, or a new bristle brush name that diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 9fcb532c33..25c7891020 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -8,8 +8,9 @@ use std::sync::Arc; use craft::behavior::Mixed; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogResult, FieldRefusal}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, TabLayout, }; @@ -843,7 +844,9 @@ fn sets_row() -> Param { .and_then(|v| v.as_array().map(|tags| tags.iter().filter_map(Value::as_str).map(str::to_string).collect())) .unwrap_or_default(); let mut clicked = None; - let line = ui.horizontal_wrapped(|ui| { + let line = Row::new().wrap(true).show(ui, |ui, _| { + // The row's body may run more than once in a pass: the last run's click applies. + clicked = None; for set in &vectorcraft_text::EXTRA_FEATURES[..20] { let current = listed.iter().find(|t| bare(t) == *set).map(|t| !t.starts_with('-')); if let (_, Some(next)) = tri_box(ui, current, Some(Label::from(set.to_string())), set) { @@ -864,7 +867,7 @@ fn sets_row() -> Param { fields.set("ot_sets", FieldValue::Json(json!(listed))); } } - line.response + line.output }) } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 5dfeb4e018..c82918426b 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -199,12 +199,11 @@ fn track(key: &str, x: f32) -> Srgba { /// The channel rows of the current mode. fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response { - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { for (key, label) in mode(fields).channels { percent_row(ui, fields, key, label, |x| track(key, x)); } }) - .response } fn rows() -> Vec { diff --git a/crates/ui-egui/src/dialogs/color_guide_options.rs b/crates/ui-egui/src/dialogs/color_guide_options.rs index 37836565e4..721064005b 100644 --- a/crates/ui-egui/src/dialogs/color_guide_options.rs +++ b/crates/ui-egui/src/dialogs/color_guide_options.rs @@ -32,12 +32,11 @@ pub fn open(app: &mut VectorcraftApp) { fields.set("steps", f64::from(current.steps)); fields.set("amount", f64::from(current.amount)); let steps = Param::custom("steps", field_label(tl!("Steps:")), |ui, fields, _| { - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { slider(ui, fields, "steps", tl!("Steps:"), 1.0..=f64::from(GuideOptions::MAX_STEPS), None); let ends = [(0.0, tl!("Less").to_owned()), (100.0, tl!("More").to_owned())]; slider(ui, fields, "amount", tl!("Variation:"), 0.0..=100.0, Some(ends)); }) - .response }) .companions(["amount"]); let variations = Param::custom("variations", field_label(tl!("Variations:")), move |ui, fields, _| { diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 17c3b500a6..913d04ca3e 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -20,9 +20,10 @@ use craft::color_ui::display::DisplayTransform; use craft::theme::{Rgba, Srgba}; use craft::ui::buttons::Button; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show as _, clicked}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _, clicked}; use craft::ui::dialog::dialog_id; use craft::ui::display::Picture; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{ CustomContext, DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, @@ -382,27 +383,32 @@ fn grid_colors_row(setup: DocSetup) -> Param { let resolved = grid_colors(&json_map(fields), &setup); let menu: Vec> = GRID_COLOR_PRESETS.iter().map(|(n, _)| *n).chain(["Custom"]).map(|n| Entry::new(n.to_string(), n.to_string())).collect(); - ui.vertical(|ui| { - let picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); - if let Some((_, pair)) = picked.and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| *p == n)) { - fields.set("gridColors", entries_value(*pair)); - } - ui.horizontal(|ui| { + let mut picked = None; + let (mut wells, mut edits) = ([None; 2], [None; 2]); + let shown = Stack::new().show(ui, |ui, _| { + picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); + Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let [r, g, b, _] = color.to_rgba8(1.0); let srgb = Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0); - if Swatch::new(name.clone(), srgb).well().show(ui).clicked { - cx.pick_color(GRID_KEYS[i], srgb); - } - let edited = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); - if let Some(Rgba([r, g, b, _])) = edited { - set_grid_entry(fields, &setup, i, &Color::rgb8(r, g, b)); - } + wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); + edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); } }); - }) - .response + }); + if let Some((_, pair)) = picked.and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| *p == n)) { + fields.set("gridColors", entries_value(*pair)); + } + for (i, (well, edit)) in wells.into_iter().zip(edits).enumerate() { + if let Some(srgb) = well { + cx.pick_color(GRID_KEYS[i], srgb); + } + if let Some(Rgba([r, g, b, _])) = edit { + set_grid_entry(fields, &setup, i, &Color::rgb8(r, g, b)); + } + } + shown.output }) } diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index 4f8218172c..d1a66945ff 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -8,7 +8,8 @@ //! options of `document.exportDxf`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; use craft::ui::text::NumberField; @@ -142,15 +143,15 @@ pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { let mut unit = fields.text("unit").map_or_else(|| Unit::Millimeters.label().to_string(), str::to_string); let mut scale = Some(fields.number("scale").unwrap_or(1.0)); let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); - let shown = ui - .horizontal(|ui| { + let shown = Row::new() + .show(ui, |ui, _| { ui.label("1"); Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); ui.label("="); NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); ui.label(tl!("Units")); }) - .response; + .output; let scale = scale.unwrap_or(1.0); if fields.text("unit") != Some(unit.as_str()) { fields.set("unit", unit); diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index f4e27e317b..580036d430 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -6,7 +6,8 @@ use std::ops::RangeInclusive; use craft::behavior::Mixed; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; @@ -198,19 +199,20 @@ pub(super) fn textured(cx: &EffectCx, fields: &DialogFields) -> Vec { let entries: Vec> = table.iter().map(|(label, value)| Entry::new((*value).to_owned(), data_label(label))).collect(); let current = fields.text("texture").unwrap_or_default(); let current = table.iter().find(|(_, value)| value.eq_ignore_ascii_case(current)).map_or("", |(_, value)| *value).to_owned(); - ui.horizontal(|ui| { - let picked = Select::new(lbl!("Texture"), Bind::given(current), &entries).show(ui); - if let Some(id) = picked.value().cloned() { - fields.set("texture", id); - } - // The pick is an edit of the rows, which the Appearance panel's editor applies. - cx.gesture(&picked.events); + let mut picked = None; + let shown = Row::new().show(ui, |ui, _| { + picked = Some(Select::new(lbl!("Texture"), Bind::given(current.clone()), &entries).show(ui)); if let Some((w, h)) = size { craft::ui::display::Text::new(format!("{w} × {h} px")).show(ui); } - picked.response - }) - .inner + }); + let Some(picked) = picked else { return shown.output }; + if let Some(id) = picked.value().cloned() { + fields.set("texture", id); + } + // The pick is an edit of the rows, which the Appearance panel's editor applies. + cx.gesture(&picked.events); + picked.response }) .companions([TEXTURE_IMAGE]); let own = ["texture", "texturePath", TEXTURE_IMAGE]; @@ -270,7 +272,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec { let zoom = fields.text("method").is_some_and(|m| m.eq_ignore_ascii_case("zoom")); let mut next = c; let unit: RangeInclusive = 0.0..=1.0; - let row = ui.horizontal(|ui| { + let row = Row::new().show(ui, |ui, _| { let picker = PointPicker::new(Bind::given([Mixed::Same(c[0]), Mixed::Same(c[1])]), unit.clone(), unit.clone()) .label(lbl!("Blur Center")) .id_salt("point") @@ -279,7 +281,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec { if let Some([Mixed::Same(x), Mixed::Same(y)]) = picker.value().cloned() { next = [x, y]; } - ui.vertical(|ui| { + Stack::new().show(ui, |ui, _| { for (axis, label) in [lbl!("Horizontal"), lbl!("Vertical")].into_iter().enumerate() { let shown = NumberField::new(label, Bind::given(Some(c[axis] * 100.0))) .unit("%") @@ -297,7 +299,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec { fields.set("centerX", center_round(next[0].clamp(0.0, 1.0))); fields.set("centerY", center_round(next[1].clamp(0.0, 1.0))); } - row.response + row.output }) .companions(["centerX", "centerY"]); let rows = generic(cx, fields).into_iter().filter(|p| !matches!(p.key.as_str(), "centerX" | "centerY")); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 5c8a86007d..2a1ee5ec8b 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -15,8 +15,9 @@ use std::sync::Arc; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Show as _, TooltipSpec}; +use craft::ui::contract::{Bind, Show as _, ShowContainer as _, TooltipSpec}; use craft::ui::dialog::DialogId; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; @@ -76,14 +77,16 @@ fn rows(presets: &Arc<[(String, String)]>) -> Vec { Param::section(tl!("Transparency")), choice_param("overprints", tl!("Overprints:"), Overprint::ALL.iter().map(|o| (o.id(), o.label()))), Param::custom("flattenerPreset", tl!("Preset:"), move |ui, fields, cx| { - ui.horizontal(|ui| { - let custom = fields.contains("flattener"); + let custom = fields.contains("flattener"); + let mut pressed = false; + let shown = Row::new().show(ui, |ui, _| { flatten::preset_picker(ui, fields, "flattenerPreset", &presets, custom); - if Button::new(tl!("Custom…")).show(ui).clicks > 0 { - cx.request_action("custom"); - } - }) - .response + pressed = Button::new(tl!("Custom…")).show(ui).clicks > 0; + }); + if pressed { + cx.request_action("custom"); + } + shown.output }) .resets(["flattener"]), Param::section(tl!("Fonts")), diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index cd54515553..5e765e306c 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -43,7 +43,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleState}; use craft::ui::patterns::form_dialogs::{FormDialog, PathRow}; -use craft::ui::primitives::ContentPainterCx; +use craft::ui::primitives::{ContentPainterCx, fit_rect}; use craft::ui::runtime::env::Label; use craft::ui::tabs::{Tab, TabKind, TabStrip}; use craft::ui::text::TextField; @@ -601,8 +601,11 @@ impl ExportForScreensDialog { let items = Items(doc.artboards.iter().map(|a| (u64::from(a.id), a.name.clone())).collect()); let caption = |at: usize| format!("{} {}", at + 1, items.0.get(at).map_or("", |(_, name)| name.as_str())); let thumbs = &self.thumbs; + // The artboard keeps its proportions, centered in the tile or the row's thumbnail. let paint = |at: usize, cx: &ContentPainterCx, rect: egui::Rect| match thumbs.get(at).cloned().flatten() { - Some(tex) => cx.picture(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), 0.0), + Some(tex) => { + cx.picture(tex.id(), fit_rect(rect, tex.size_vec2()), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), 0.0) + } None => { cx.painter.rect_filled(rect, 0.0, egui::Color32::WHITE); } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 538141fc11..6d81d18214 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -4,9 +4,11 @@ use std::collections::HashMap; -use craft::ui::contract::{Bind, Show as _}; +use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Stack; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, encode}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use craft::ui::runtime::measure; use craft::ui::text::TextField; use craft::ui::value_drag::SliderScale; use serde_json::{Map, Value, json}; @@ -200,6 +202,25 @@ pub(crate) fn fields_of(params: &[Param], json: &Map) -> DialogFi fields } +/// Shows `body` in a `Stack` as rows of a custom dialog row that edit `fields`. The stack may run its body more than +/// once in a pass: every run edits a copy of the values as they stand here, and the copy of the run that is not a +/// measuring run replaces them after the stack. +pub(super) fn stacked(ui: &mut egui::Ui, fields: &mut DialogFields, mut body: impl FnMut(&mut egui::Ui, &mut DialogFields)) -> egui::Response { + let before = fields.clone(); + let mut edited = None; + let shown = Stack::new().show(ui, |ui, _| { + let mut run = before.clone(); + body(ui, &mut run); + if measure::effect(ui.ctx(), "dialog rows edit their values") { + edited = Some(run); + } + }); + if let Some(edited) = edited { + *fields = edited; + } + shown.output +} + /// The command or effect parameters of the dialog values `fields`: the UI-only keys (`__*`, `preview`) are dropped. pub(crate) fn json_of(params: &[Param], fields: &DialogFields) -> Map { fields diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 32d780bddb..d4b411dc90 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -21,10 +21,12 @@ // of the draw crate is where `TipEllipse` and `TipAngle` live. use craft::draw::ui::brush_settings::{TipAngle, TipEllipse}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::Row; +use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; -use craft::ui::runtime::env::{Env, UnitKind}; -use craft::ui::style::rgba_color; +use craft::ui::primitives::{ContentPainterCx, PaintShape}; +use craft::ui::runtime::env::UnitKind; use craft::ui::text::NumberField; use craft::ui::value_drag::{Slider, SliderScale}; use egui::{Response, Ui}; @@ -69,9 +71,6 @@ const KEYS: [&str; 18] = [ /// and the field takes up to 100. const FIDELITY_MAX: f64 = 20.0; -/// Half the length of a tip in its dabs, in points. -const DAB_LONG: f32 = 18.0; - /// Fidelity `v` stepped `n` steps by the slider's and the field's keys: an arrow steps hundredths up to 0.1, /// tenths up to 1 and whole units above, in the tool's unit (a step down from 0.1 or 1 takes the finer step below /// it); ten steps at once (Shift with an arrow, Page Up/Down) multiply or divide by ten, so they go @@ -175,27 +174,34 @@ fn tip_row(ui: &mut Ui, fields: &mut DialogFields, least: f64) -> Response { shown.output } -/// Three dabs of `tip`, as a stroke of it lays them down. -// PLAN: a `Picture::painter` replaces the plain allocation once its `ThumbAspect` is known to this set. +/// Three dabs of `tip`, as a stroke of it lays them down: a picture seven tip halves wide and two high, at the +/// small sample size, each dab as long as the picture is high. fn dabs(ui: &mut Ui, tip: TipAngle) { - let tokens = Env::of(ui).tokens.clone(); - let (dim, ink) = (rgba_color(tokens.color.text.muted), rgba_color(tokens.color.text.normal)); - let long = DAB_LONG; - let (response, painter) = ui.allocate_painter(egui::vec2(7.0 * long, 2.0 * long), egui::Sense::hover()); + // Decorative: the Tip control beside it is the row's accessible control. + Picture::painter("", ThumbAspect::new(7, 2), move |cx, rect| paint_dabs(cx, rect, tip)).extent(PictureSize::Sample(ThumbSize::Small)).show(ui); +} + +/// Paints three dabs of `tip` across `rect`, the middle one in the text color and the outer two in the muted one. +fn paint_dabs(cx: &ContentPainterCx<'_>, rect: egui::Rect, tip: TipAngle) { + let style = cx.style_cx(); + let (dim, ink) = (style.color(style.tokens.color.text.muted), style.color(style.tokens.color.text.normal)); + let long = rect.height() / 2.0; let a = tip.degrees.clamp(-180.0, 180.0).to_radians(); let u = egui::vec2(a.cos() as f32, -a.sin() as f32); let v = egui::vec2(-u.y, u.x); let short = long * (tip.roundness.clamp(0.0, 1.0) as f32).max(0.001); - for (i, color) in [dim, ink, dim].into_iter().enumerate() { - let center = egui::pos2(response.rect.min.x + long + i as f32 * 2.5 * long, response.rect.center().y); - let points = (0..32) - .map(|k| { - let s = std::f32::consts::TAU * k as f32 / 32.0; - center + u * (long * s.cos()) + v * (short * s.sin()) - }) - .collect(); - painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); - } + cx.with_draw(|draw| { + for (i, color) in [dim, ink, dim].into_iter().enumerate() { + let center = egui::pos2(rect.min.x + long + i as f32 * 2.5 * long, rect.center().y); + let points = (0..32) + .map(|k| { + let s = std::f32::consts::TAU * k as f32 / 32.0; + center + u * (long * s.cos()) + v * (short * s.sin()) + }) + .collect(); + draw.fill(&PaintShape::Polygon(points), color); + } + }); } /// The rows of tool `tool`'s dialog: those of `present` (the option keys the tool reports), in the order the diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 1cab75f7bd..d38eae5bb0 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -21,7 +21,7 @@ use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft::ui::form::Field; -use craft::ui::layout_components::Stack; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::notices::Notice; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Label, UnitKind}; @@ -264,7 +264,7 @@ impl StackDialog for GradientStopPopover { /// point: spread). What the user edits is filed in `filed`. fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) { Stack::new().show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let tabs = [ Entry::new(Tab::Color, tl!("Color").to_owned()).icon(IconId::new("palette")), Entry::new(Tab::Swatches, tl!("Swatches").to_owned()).icon(IconId::new("swatch-book")), @@ -288,7 +288,7 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi } Tab::Swatches => swatches(ui, feed, filed), } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { filed.fields.opacity = percent_field(ui, tl!("Opacity").to_owned(), feed.opacity).or(filed.fields.opacity); let (label, amount) = if feed.point { (tl!("Spread"), &mut filed.fields.spread) } else { (tl!("Location"), &mut filed.fields.location) }; *amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount); diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 3998523a57..50eab143f5 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -17,8 +17,8 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Swatch}; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; -use craft::ui::layout_components::Stack; -use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; use craft::ui::text::TextField; @@ -141,71 +141,110 @@ fn pen_key(i: usize) -> String { /// Pens: One Pen per Color (`pens` null) or Pen Table (`pens` the colors, pen 1's first), with a /// row per pen (its number, color and a Remove button) and Add. fn pens_param() -> Param { - Param::custom("pens", tl!("Pens:"), |ui, fields, cx| ui.vertical(|ui| pens_ui(ui, fields, cx)).response) - .companions([SET_ASIDE, PEN_ERROR]) - .full_width() + Param::custom("pens", tl!("Pens:"), |ui, fields, cx| { + take_picked_pens(fields); + // The stack's body may run more than once in a pass: every run draws from the values as they stand here, and + // what the last run asked for applies after the stack. + let mut asked = PensAsked::default(); + let shown = Stack::new().show(ui, |ui, _| asked = pens_ui(ui, fields)); + if let Some((i, color)) = asked.pick { + cx.pick_color(&pen_key(i), color); + } + match asked.table { + Some(true) => cx.request_action("penTable"), + Some(false) => { + let _ = set_pen_table(fields, false, || Ok(Vec::new())); + fields.remove(PEN_ERROR); + } + None => {} + } + if let Some(pens) = asked.pens { + fields.set("pens", FieldValue::Json(Value::Array(pens))); + } + shown.output + }) + .companions([SET_ASIDE, PEN_ERROR]) + .full_width() +} + +/// What the pens rows asked for in one run. +#[derive(Default)] +struct PensAsked { + /// Pen Table was turned on (`true`) or off. + table: Option, + /// The pen table after an edit of its rows. + pens: Option>, + /// The pen whose swatch was pressed, with its color: the picker opens on it. + pick: Option<(usize, Srgba)>, +} + +/// Writes the colors the picker answered into the pen table. +fn take_picked_pens(fields: &mut DialogFields) { + let Some(mut pens) = table(fields) else { return }; + let mut changed = false; + for (i, pen) in pens.iter_mut().enumerate() { + if let Some([r, g, b]) = fields.color(&pen_key(i)) { + let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); + fields.remove(&pen_key(i)); + changed = true; + } + } + if changed { + fields.set("pens", FieldValue::Json(Value::Array(pens))); + } } /// The pens row. Switching to Pen Table asks the host (`penTable`): the table starts from the document's pens, which /// this draw cannot reach. -fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) { - let mut list = table(fields); - let mut changed = false; - // Colours the picker answered. - if let Some(pens) = list.as_mut() { - for (i, pen) in pens.iter_mut().enumerate() { - if let Some([r, g, b]) = fields.color(&pen_key(i)) { - let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; - *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); - fields.remove(&pen_key(i)); - changed = true; - } - } - } +fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { + let mut asked = PensAsked::default(); + let list = table(fields); let mut on = list.is_some(); RadioGroup::new(tl!("Pens:"), Bind::bound(&mut on)).show(ui, |ui, _| { Radio::new(false).label(tl!("One Pen per Color")).show(ui); Radio::new(true).label(tl!("Pen Table")).show(ui); }); if on != list.is_some() { - if on { - cx.request_action("penTable"); - } else { - let _ = set_pen_table(fields, false, || Ok(Vec::new())); - fields.remove(PEN_ERROR); - list = None; - } + asked.table = Some(on); } - if let Some(e) = fields.text(PEN_ERROR) { + if let Some(e) = fields.text(PEN_ERROR).filter(|_| asked.table != Some(false)) { let error = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.fg); ui.colored_label(error, crate::i18n::message(crate::i18n::current(), e)); } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. - let Some(mut pens) = list.filter(|a| a.len() <= MAX_PENS) else { return }; + let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; + let mut changed = false; let n = pens.len(); + // What the rows asked for: a typed color per pen, the pen whose swatch or Remove was pressed. Each run of the + // stack's body starts them afresh from the same pens. + let mut typed: Vec> = vec![None; n]; let mut remove = None; Stack::new().scroll(Scroll::vertical()).room_height(180.0).show(ui, |ui, _| { - for (i, pen) in pens.iter_mut().enumerate() { - ui.horizontal(|ui| { + typed.iter_mut().for_each(|t| *t = None); + (remove, asked.pick) = (None, None); + for (i, pen) in pens.iter().enumerate() { + Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { ui.label((i + 1).to_string()); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { - cx.pick_color(&pen_key(i), Srgba::from(color)); + asked.pick = Some((i, Srgba::from(color))); } let before = color; TextField::hex(tl!("Pen color"), Bind::bound(&mut color)).id_salt(("hpgl-pen", i)).show(ui); - if color != before - && let Some(typed) = pen_color(&color.to_hex()) - { - *pen = json!(typed); - changed = true; - } + typed[i] = (color != before).then(|| pen_color(&color.to_hex())).flatten(); if IconButton::new(IconId::new("trash")).label(tl!("Remove")).enabled(n > 1).show(ui).clicks > 0 { remove = Some(i); } }); } }); + for (pen, typed) in pens.iter_mut().zip(typed) { + if let Some(typed) = typed { + *pen = json!(typed); + changed = true; + } + } if Button::new(tl!("Add")).enabled(n < MAX_PENS).show(ui).clicks > 0 { // A new pen starts as the last one's color, ready to be changed. pens.push(pens.last().cloned().unwrap_or_else(|| json!("#000000"))); @@ -216,8 +255,9 @@ fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) changed = true; } if changed { - fields.set("pens", FieldValue::Json(Value::Array(pens))); + asked.pens = Some(pens); } + asked } /// Starts Pen Table for dialog `id`: the table the export would give the art, or the reason it cannot. It runs from diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index d29d9742c4..e28bdbb021 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -580,12 +580,19 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool { offer(app, &name, &bytes, path, Some(p)) } +/// Whether the `file.place` params `p` give a password. `file.place` reads an empty or null +/// `password` as none; a value that isn't text counts as given, for `file.place` to refuse. +fn gives_password(p: &Value) -> bool { + p.get("password").is_some_and(|v| !v.is_null() && v.as_str() != Some("")) +} + /// [`offer_place`] when Show Import Options is off: asks (true) only for the password of an -/// encrypted PDF given no `password`, which nothing else opens, and places its first page (or -/// `page`) and crop box once it is unlocked; any other PDF is placed that way without asking. +/// encrypted PDF given no password (see [`gives_password`]), which nothing else opens, and places +/// its first page (or `page`) and crop box once it is unlocked; any other PDF is placed that way +/// without asking. pub fn offer_place_password(app: &mut VectorcraftApp, p: &Value) -> bool { // A `page` that isn't a page number is left for `file.place` to refuse. - if p.get("password").is_some() || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) { + if gives_password(p) || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) { return false; } let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "pdf" | "ai" | "ait")) else { return false }; @@ -626,12 +633,13 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ /// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a /// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no /// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it -/// says. +/// says. An empty `password` is none, so a place from a path with Link on and an empty +/// `password` stays linked. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); - let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !given("password"); + let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !gives_password(p); if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { return; } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 918ea16837..f45d77ab38 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -20,7 +20,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI}; -use craft::behavior::Mixed; +use craft::behavior::{IconId, Mixed}; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked}; @@ -299,7 +299,10 @@ impl DocumentSettings for VcNewDocument { Row::new().show(ui, |ui, _| { Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); Field::new(orientation.clone()).show(ui, |ui, _| { - let entries = [Entry::new(Orientation::Portrait, portrait.clone()), Entry::new(Orientation::Landscape, landscape.clone())]; + let entries = [ + Entry::new(Orientation::Portrait, portrait.clone()).icon(IconId::new("orientation_portrait")), + Entry::new(Orientation::Landscape, landscape.clone()).icon(IconId::new("orientation_landscape")), + ]; picked = Segmented::new(orientation.clone(), Bind::given(current), &entries).show(ui).value().cloned(); }); Field::new(artboards.clone()).show(ui, |ui, _| { @@ -783,6 +786,50 @@ mod tests { app.run("prefs.set", json!({"key": "unitsGeneral", "value": units, "documentUnits": false})).unwrap(); } + /// The window's frames with the dialog open, laid out; the last frame's output. + fn laid_out(app: &mut VectorcraftApp) -> egui::FullOutput { + let ctx = ctx(app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let mut frame = |i: u32| { + let input = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() }; + crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)) + }; + (0..3).for_each(|i| drop(frame(i))); + frame(3) + } + + /// Orientation shows a page icon for Portrait and for Landscape, named for screen readers, as production's buttons + /// did; before, it showed the words, and Landscape, cut short, ran into Artboards. + #[test] + fn orientation_shows_two_page_icons_beside_artboards() { + fn texts(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: &str, role: egui::accesskit::Role| { + let (_, n) = nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} {label}")); + n.bounds().expect("bounds") + }; + let landscape = bounds("Landscape", egui::accesskit::Role::RadioButton); + let artboards = bounds("Artboards", egui::accesskit::Role::SpinButton); + assert!(landscape.x1 <= artboards.x0, "Landscape {landscape:?} stays left of Artboards {artboards:?}"); + let group = bounds("Orientation", egui::accesskit::Role::RadioGroup); + let mut drawn = Vec::new(); + out.shapes.iter().for_each(|s| texts(&s.shape, &mut drawn)); + let inside: Vec<_> = drawn + .iter() + .filter(|(_, at)| (group.x0..=group.x1).contains(&f64::from(at.x)) && (group.y0..=group.y1).contains(&f64::from(at.y))) + .collect(); + assert!(inside.is_empty(), "the segments draw icons, not words: {inside:?}"); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and /// the built-in cards turn to the picked orientation (#2860). #[test] diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 6b6952a6ca..ff52df3db8 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -11,6 +11,7 @@ //! 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`]). +//! A command whose manifest names another menu is listed in that menu instead ([`place_commands`]). //! Exporters are formats of File › Export › Export As; one with parameters opens dialog //! `pluginExport` once the file is picked, and its Export button writes the file. Importers open the //! files File › Open finds no built-in format for, and File › Open With lists them; one with @@ -45,14 +46,14 @@ use vectorcraft_plugins::{Budget, Kind, Manifest, Plugin, permissions, registry} use super::form; use super::preview::LivePreview; use crate::VectorcraftApp; -use crate::menus::{Sep, c, cp, heading, sub}; +use crate::menus::{Sep, c, cp, placeholder, sub}; /// The key of the hosted dialog of plug-in filters. pub const KIND: &str = "plugin"; const CMD: &str = "plugin.run"; -/// Object › Plug-ins' header while no filter plug-in is installed. +/// Object › Plug-ins' disabled row while no filter plug-in is installed. pub const NO_FILTERS: &str = "No filter plug-ins installed"; /// A menu label for plug-in `name`: with an ellipsis when it opens a dialog. @@ -78,6 +79,117 @@ fn with_commands(plugin: &Plugin, own: Node) -> Node { sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items) } +/// Moves each plug-in command whose manifest's `menu` names another menu +/// ([`vectorcraft_plugins::MenuPlace`]) from its plug-in's submenu into that menu of `tree`: after +/// the built-in item its `after` names (with or without an ellipsis), or at the end of the menu. +/// Its label ends with the plug-in's name ([`vectorcraft_plugins::Command::menu_label`]). +/// Commands placed at the same spot are listed in plug-in id order and then in manifest order. A +/// plug-in's submenu left with its own item alone becomes that item. A command whose menu `tree` +/// doesn't have, or that [`vectorcraft_engine::cmd::plugin::placed_menu`] leaves in its plug-in's +/// submenu, stays there. +pub fn place_commands(tree: &mut [(&'static str, Vec)]) { + let mut spots: Vec<(&'static [&'static str], Option, Vec)> = Vec::new(); + for p in registry::list() { + let m = p.manifest(); + if !matches!(m.kind, Kind::Filter | Kind::Effect) { + continue; + } + for command in &m.commands { + let Some(place) = &command.place else { continue }; + if vectorcraft_engine::cmd::plugin::placed_menu(&p, command).is_none() { + continue; + } + // An `after` that names no built-in item of the menu means the end of it, as no `after` does. + // The spot is the item's own label, so both labels of an item that switches are one spot. + let after = place.after.as_deref().and_then(|a| { + let menu = menu_at(tree, place.path)?; + menu.iter().find(|it| is_anchor(it, anchor_key(a))).and_then(own_key).map(str::to_string) + }); + let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &command.id)); + let item = c(label(&command.menu_label(&m.name), !command.params.is_empty()), id); + match spots.iter_mut().find(|s| s.0 == place.path && s.1 == after) { + Some(s) => s.2.push(item), + None => spots.push((place.path, after, vec![item])), + } + } + } + spots.retain(|s| menu_at(tree, s.0).is_some()); + if spots.is_empty() { + return; + } + let placed: std::collections::HashSet = spots + .iter() + .flat_map(|s| s.2.iter()) + .filter_map(|it| match it { + Node::Item(i) => Some(i.command.id.clone()), + _ => None, + }) + .collect(); + // Plug-in submenus are under Object › Plug-ins and Effect › Plug-ins. + for (_, items) in tree.iter_mut().filter(|(title, _)| matches!(*title, "Object" | "Effect")) { + leave_out(items, &placed); + } + for (path, after, items) in spots { + let Some(menu) = menu_at(tree, path) else { continue }; + let at = after.and_then(|a| menu.iter().position(|it| own_key(it) == Some(a.as_str()))).map_or(menu.len(), |i| i + 1); + menu.splice(at..at, items); + } +} + +/// A label as `after` matches it: trimmed, without a closing ellipsis. +fn anchor_key(label: &str) -> &str { + label.trim().trim_end_matches('…').trim_end() +} + +/// Is `it` the built-in item or submenu labeled `key` ([`anchor_key`])? An item of +/// [`crate::menus::DYNAMIC_LABELS`] matches by the label of either of its states +/// ([`vectorcraft_engine::cmd::plugin::other_state`]). Items that list a plug-in are never an anchor. +fn is_anchor(it: &Node, key: &str) -> bool { + let other = |l: &str| crate::menus::DYNAMIC_LABELS.contains(&l) && vectorcraft_engine::cmd::plugin::other_state(l).is_some_and(|o| o == key); + own_key(it).is_some_and(|own| own == key || matches!(it, Node::Item(i) if other(&i.label))) +} + +/// The label of `it` as [`anchor_key`] reads it, when `it` is a built-in item or submenu that can be +/// an anchor; `None` for an item that lists a plug-in. +fn own_key(it: &Node) -> Option<&str> { + match it { + Node::Item(i) if !crate::menus::lists_plugin(&i.command.id, &i.command.params) => Some(anchor_key(&i.label)), + Node::Submenu { label, children, .. } if !crate::menus::holds_plugin_commands(children) => Some(anchor_key(label)), + _ => None, + } +} + +/// The built-in menu of `tree` at `path`: a top-level menu, then its submenus by label. +fn menu_at<'a>(tree: &'a mut [(&'static str, Vec)], path: &[&str]) -> Option<&'a mut Vec> { + let (first, rest) = path.split_first()?; + let mut menu = &mut tree.iter_mut().find(|(title, _)| title == first)?.1; + for segment in rest { + menu = menu.iter_mut().find_map(|it| match it { + Node::Submenu { label, children, .. } if label.as_str() == *segment && !crate::menus::holds_plugin_commands(children) => Some(children), + _ => None, + })?; + } + Some(menu) +} + +/// Takes the commands in `placed` out of the plug-in submenus under `items`; a submenu left with no +/// command becomes its plug-in's own item. +fn leave_out(items: &mut [Node], placed: &std::collections::HashSet) { + for it in items.iter_mut() { + let Node::Submenu { children, .. } = it else { continue }; + if !crate::menus::holds_plugin_commands(children) { + leave_out(children, placed); + continue; + } + children.retain(|c| !matches!(c, Node::Item(i) if placed.contains(&i.command.id))); + if !children.iter().any(|c| matches!(c, Node::Item(i) if vectorcraft_engine::cmd::plugin::is_command_id(&i.command.id))) + && let Some(own) = children.first().cloned() + { + *it = own; + } + } +} + /// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then /// Install Plug-in… and Reload Plug-ins. pub fn object_menu() -> Vec { @@ -87,13 +199,13 @@ pub fn object_menu() -> Vec { .map(|p| with_commands(p, cp(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))) .collect(); if items.is_empty() { - items.push(heading(NO_FILTERS)); + items.push(placeholder(NO_FILTERS)); } items.extend([Sep, c("Install Plug-in…", "ui.installPlugin"), c("Reload Plug-ins", "plugin.reload")]); items } -/// File › Open With's header while no importer plug-in is installed. +/// File › Open With's disabled row while no importer plug-in is installed. pub const NO_IMPORTERS: &str = "No importer plug-ins installed"; /// File › Open With: the installed importers (`file.openWith {importer}`), each by its name. @@ -102,7 +214,7 @@ pub fn open_with_menu() -> Vec { .iter() .map(|p| cp(label(&p.manifest().name, true), "file.openWith", json!({ "importer": vectorcraft_plugins::export::format_id(p.id()) }))) .collect(); - if items.is_empty() { vec![heading(NO_IMPORTERS)] } else { items } + if items.is_empty() { vec![placeholder(NO_IMPORTERS)] } else { items } } /// Effect › Plug-ins: the live-effect plug-ins, each with its commands if it has any (`None` diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 00151a7f2c..8bf05fe7d8 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -8,9 +8,10 @@ use craft::theme::{Rgba, Srgba}; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::display::Text; use craft::ui::form::SliderField; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; use craft::ui::runtime::env::UnitKind; @@ -216,25 +217,28 @@ fn resolution_row() -> Param { let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| fields.bool("__otherPpi") != Some(true)); let other = RESOLUTION_LABELS.len() - 1; let entries: Vec> = RESOLUTION_LABELS.iter().enumerate().map(|(i, label)| Entry::new(i, tl!(*label))).collect(); - ui.horizontal(|ui| { - if let Some(i) = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied() { - if let Some(p) = RESOLUTIONS.get(i) { - fields.set("ppi", *p); - } - fields.set("__otherPpi", i == other); - } + let (mut picked, mut typed) = (None, None); + let shown = Row::new().show(ui, |ui, _| { + picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied(); if preset.is_none() { let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi))) .range(1.0..=4608.0) .step(1.0) .unit_kind(UnitKind::PixelsPerInch) .show(ui); - if let Some(Some(v)) = field.edit.value().copied() { - fields.set("ppi", v); - } + typed = field.edit.value().copied().flatten(); } - }) - .response + }); + if let Some(i) = picked { + if let Some(p) = RESOLUTIONS.get(i) { + fields.set("ppi", *p); + } + fields.set("__otherPpi", i == other); + } + if let Some(v) = typed { + fields.set("ppi", v); + } + shown.output }) .companions(["__otherPpi"]) .opens_with(72.0) @@ -263,18 +267,21 @@ fn color_choice( let at = ids.iter().position(|v| current.eq_ignore_ascii_case(v)).unwrap_or(ids.len()); let start = first(fields); let entries: Vec> = labels.iter().enumerate().skip(start).map(|(i, l)| Entry::new(i, tl!(*l))).collect(); - ui.horizontal(|ui| { - if let Some(i) = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied() { - fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + let color = (at == ids.len()).then(|| Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128)))); + let (mut picked, mut pick_color) = (None, false); + let shown = Row::new().show(ui, |ui, _| { + picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied(); + if let Some(color) = color { + pick_color = Swatch::new(tl!(label), color).show(ui).clicked; } - if at == ids.len() { - let color = Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128))); - if Swatch::new(tl!(label), color).show(ui).clicked { - cx.pick_color(key, color); - } - } - }) - .response + }); + if let Some(i) = picked { + fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + } + if let Some(color) = color.filter(|_| pick_color) { + cx.pick_color(key, color); + } + shown.output }) } @@ -310,18 +317,17 @@ fn jpeg_rows(screens: bool) -> Vec { fn quality_row() -> Param { Param::custom("quality", tl!("Quality:"), |ui, fields, _| { let q = (fields.number("quality").unwrap_or(90.0) / 10.0).round().clamp(0.0, 10.0); - ui.horizontal(|ui| { + let mut slid = None; + let shown = Row::new().show(ui, |ui, _| { let out = SliderField::new(tl!("Quality:"), Bind::given(q), 0.0..=10.0).step(1.0).show(ui); - let q = match out.edit.value() { - Some(v) => { - fields.set("quality", v.round() * 10.0); - v.round() - } - None => q, - }; + slid = out.edit.value().map(|v| v.round()); + let q = slid.unwrap_or(q); Text::new(tl!(QUALITY_BANDS.get(q as usize).copied().unwrap_or_default())).show(ui); - }) - .response + }); + if let Some(v) = slid { + fields.set("quality", v * 10.0); + } + shown.output }) .opens_with(90.0) } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index e988d10099..255495d286 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -19,7 +19,9 @@ use std::sync::{Arc, LazyLock, mpsc}; use craft::behavior::{ColumnWidth, EditEvent, EditEvents, IconId, Mixed}; -use craft::print::ui::{Destination, HostedPrint, PrintAnswer, PrintFinish, PrintLayout, PrintMode, PrintSection, PrintSheet, Printer, State}; +use craft::print::ui::{ + Destination, DriverControls, HostedPrint, PrintAnswer, PrintFinish, PrintLayout, PrintMode, PrintSection, PrintSheet, Printer, State, +}; use craft::ui::buttons::ToggleButton; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; @@ -106,6 +108,8 @@ struct Open { art: Option<(ArtKey, egui::TextureHandle)>, /// `print.preview` of the settings and document it was run for. preview: Option<(Stamp, Arc>)>, + /// The printer row's driver controls, as the dialog was last given them. + driver: DriverControls, } /// The document (uid, revision) and the settings a cached preview belongs to. @@ -116,6 +120,8 @@ type ArtKey = (u64, u64, PrintLayers, [u64; 4], u32); /// What the pump took from the dialog this pass. struct Drained { + /// The printer row's driver controls for the printer chosen. + driver: DriverControls, refresh: bool, /// The preset editor's name. name: String, @@ -197,9 +203,11 @@ fn start( }; let taken: Vec = taken_names(app); let named = editing.clone(); + let driver = driver(has_setup(app), &state.settings.destination); let mut hosted = HostedPrint::new(state, fields, sections(&Lists::of(app))) .mode(mode) .layout(PrintLayout::Sections) + .driver(driver) .header(header) .json_form(|fields, out| out.extend(nested(form::json_of(&KEYS, fields)))) .check_name(move |name: &str| refusal(&taken, &named, name).map(|_| PresetError::NameTaken)) @@ -209,7 +217,7 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None }); + app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver }); Ok(Value::Null) } @@ -280,6 +288,18 @@ fn destinations(app: &mut VectorcraftApp) -> (Vec, bool) { (list, service) } +/// Whether the print service can open a printer's settings (`print.printerSetup`). +fn has_setup(app: &VectorcraftApp) -> bool { + app.services.print.as_ref().is_some_and(|s| s.has_setup()) +} + +/// The printer row's Setup…: shown when the print service can open printer settings (`setup`) and `destination` +/// is a printer. +fn driver(setup: bool, destination: &Destination) -> DriverControls { + let printer = matches!(destination, Destination::Printer(name) if name != PDF_FILE); + if setup && printer { DriverControls::Page } else { DriverControls::None } +} + /// The names a new preset may not take: [Default] and the saved presets. fn taken_names(app: &VectorcraftApp) -> Vec { std::iter::once(DEFAULT_PRESET.to_string()).chain(app.session.prefs.print_presets.iter().map(|p| p.name.clone())).collect() @@ -302,13 +322,13 @@ pub(super) fn settings(fields: &DialogFields) -> Value { /// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was /// dragged to, the presets and OK. -pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut open) = app.print_dialog.open.take() else { return }; let Some(dialogs) = app.dialogs() else { app.print_dialog.open = Some(open); return; }; - if serve(app, &dialogs, &mut open) { + if serve(app, ctx, &dialogs, &mut open) { app.print_dialog.open = Some(open); } } @@ -319,22 +339,38 @@ fn on(dialogs: &WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Opti } /// One pass of the pump over the open dialog; false once it has closed. -fn serve(app: &mut VectorcraftApp, dialogs: &WindowDialogs, open: &mut Open) -> bool { - let Some(mut d) = on(dialogs, |p| Drained { - refresh: p.take_refresh(), - name: p.preset_name().to_string(), - // Print Settings… opens the driver's dialog of the printer chosen. - setup: if p.take_setup() { p.json_fields().and_then(|f| f["printer"].as_str().map(str::to_string)) } else { None }, - moves: p.take_moves(), - events: p.take_preset_events(), - ok: p.take_ok(), - settings: settings(p.fields_mut()), - sheet: p.sheet_index(), +fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool { + let setup = has_setup(app); + let Some(mut d) = on(dialogs, |p| { + // The printer row shows Setup… for the printer chosen, and none for PDF File. + let driver = driver(setup, &p.state().settings.destination); + p.set_driver(driver); + Drained { + driver, + refresh: p.take_refresh(), + name: p.preset_name().to_string(), + // Setup… opens the settings of the printer chosen. + setup: if p.take_setup() && driver != DriverControls::None { + p.json_fields().and_then(|f| f["printer"].as_str().map(str::to_string)) + } else { + None + }, + moves: p.take_moves(), + events: p.take_preset_events(), + ok: p.take_ok(), + settings: settings(p.fields_mut()), + sheet: p.sheet_index(), + } }) else { // Closed: its answer was acted on when the OK was held. let _ = dialogs.with(|h| h.take_by_id::(open.id)); return false; }; + // The row was drawn this frame with the controls of the printer before: the next frame shows the new ones. + if d.driver != open.driver { + open.driver = d.driver; + ctx.request_repaint(); + } if d.refresh { let (list, _) = destinations(app); let (tx, rx) = mpsc::channel(); diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index f5a52fd70e..e7f8571954 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -4,8 +4,18 @@ //! Spacing and Move Artwork with Artboard, with the document's artboard count. OK runs //! `artboard.rearrange` as one undo step (#681). //! +//! Rearrange (the Artboard tool's canvas menu and Contextual Task Bar, and the Artboards panel +//! menu's Rearrange…) is the same dialog for the selected artboards (field `indices`), with their +//! count. Its OK waits for a click on the canvas, which places the grid's top-left there: the +//! grid's outline follows the pointer until then, Enter places it at the pointer (or, off the +//! canvas, at the first selected artboard's top-left), a Space-drag still pans, and Esc, another +//! tool or another document cancels it. The click or Enter runs `artboard.rearrange` with +//! `indices` and `at` as one undo step +//! (https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html). +//! //! Fields: `layout` (`gridByRow` | `gridByColumn` | `row` | `column`), `order` (`leftToRight` | -//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt) and `moveArtwork`. +//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt), `moveArtwork` and, for +//! Rearrange, `indices`. use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; @@ -19,15 +29,21 @@ use craft::ui::style::TypeRole; use craft::ui::text::NumberField; use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_engine::cmd::newdoc::ArtboardLayout; +use vectorcraft_engine::cmd::newdoc::{ArtboardLayout, rearrange_grid}; +use vectorcraft_geom::{BezPath, Point}; +use vectorcraft_tools::Overlay; use super::layer_options::check; use crate::VectorcraftApp; use crate::page_glyphs::LayoutGlyph; +use crate::state::RearrangePlacement; /// The command Rearrange All Artboards runs; the key of its dialog. pub(crate) const CMD: &str = "artboard.rearrange"; +/// The status bar's message while a Rearrange waits for its click. +pub(crate) const PLACE_HINT: &str = "Click on the canvas to place the artboards (Esc cancels)"; + static GRID_BY_ROW: LayoutGlyph = LayoutGlyph { tiles: &[(0, 0), (1, 0), (0, 1), (1, 1)] }; static GRID_BY_ROW_RTL: LayoutGlyph = LayoutGlyph { tiles: &[(1, 0), (0, 0), (1, 1), (0, 1)] }; static GRID_BY_COLUMN: LayoutGlyph = LayoutGlyph { tiles: &[(0, 0), (0, 1), (1, 0), (1, 1)] }; @@ -52,7 +68,8 @@ fn layout_glyph(l: ArtboardLayout, rtl: bool) -> (&'static str, &'static LayoutG } } -/// The settings the dialog edits. +/// The settings the dialog edits, and for Rearrange the artboards it lays out (`indices`, sorted +/// and once each), which the dialog does not edit. #[derive(Clone, Debug, PartialEq)] pub(crate) struct RearrangeValues { layout: ArtboardLayout, @@ -61,21 +78,26 @@ pub(crate) struct RearrangeValues { columns: f64, spacing: f64, move_artwork: bool, + indices: Option>, } impl Default for RearrangeValues { fn default() -> Self { - RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true } + RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true, indices: None } } } impl RearrangeValues { /// `artboard.rearrange` parameters. fn params(&self) -> Value { - json!({ + let mut p = json!({ "layout": self.layout.id(), "order": self.order(), "columns": self.columns, "spacing": self.spacing, "moveArtwork": self.move_artwork, - }) + }); + if let Some(indices) = &self.indices { + p["indices"] = json!(indices); + } + p } fn order(&self) -> &'static str { @@ -108,13 +130,36 @@ fn length_kind(unit: Unit) -> UnitKind { } } -/// `ui.menuDialog` for Rearrange All Artboards: opens the dialog on the spacing of its last OK. +/// `ui.menuDialog` for Rearrange All Artboards: opens the dialog on the spacing of its last OK. A +/// placement still waiting is dropped. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + cancel_placement(app); + open_with(app, None) +} + +/// Open Rearrange for artboards `indices`, kept sorted and once each; none opens nothing. A +/// placement still waiting is dropped. +pub(crate) fn open_selected(app: &mut VectorcraftApp, indices: &[usize]) { + cancel_placement(app); + if indices.is_empty() { + return; + } + let mut indices = indices.to_vec(); + indices.sort_unstable(); + indices.dedup(); + if let Err(e) = open_with(app, Some(indices)) { + app.status(e); + } +} + +/// Opens the dialog for `indices` (Rearrange), or for every artboard (Rearrange All Artboards). +fn open_with(app: &mut VectorcraftApp, indices: Option>) -> Result { let mut values = RearrangeValues::default(); if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() { values.spacing = spacing; } - let artboards = app.session.active().map_or(0, |doc| doc.doc.artboards.len()); + let artboards = indices.as_ref().map_or_else(|| app.session.active().map_or(0, |doc| doc.doc.artboards.len()), Vec::len); + values.indices = indices; let lengths = LengthUnits::new(UnitKind::Points, length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let dialogs = app.dialogs().ok_or("no window")?; @@ -122,18 +167,28 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { Ok(Value::Null) } -/// The Rearrange All Artboards dialog; its answer is the settings OK confirmed, which [`pump`] runs. +/// The artboards of a menu item's params that list nothing but `indices` (the Artboard tool's +/// Rearrange), as whole numbers. +pub(crate) fn menu_indices(p: &Value) -> Option> { + let o = p.as_object().filter(|o| o.len() == 1)?; + let list = o.get("indices")?.as_array()?; + list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok())).collect() +} + +/// The Rearrange All Artboards dialog, or Rearrange for the selected artboards; its answer is the +/// settings OK confirmed, which [`pump`] runs or leaves waiting for a click on the canvas. pub(crate) struct RearrangeArtboardsDialog { id: DialogId, open: bool, values: RearrangeValues, - /// The document's artboard count, which bounds Columns. + /// The artboards the dialog lays out (the document's, or the selected ones), which bounds Columns + /// and is the count it shows. artboards: usize, /// The lengths Spacing keeps and shows. lengths: LengthUnits, } -/// The rows of the dialog for a document of `artboards` artboards, Spacing shown in `unit`. +/// The rows of the dialog for `artboards` artboards, Spacing shown in `unit`. fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: LengthUnits) { Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| { let entries: Vec> = ArtboardLayout::ALL @@ -176,7 +231,8 @@ fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: L v.move_artwork = on; } }); - Text::new(crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui); + let label = if v.indices.is_some() { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") }; + Text::new(crate::i18n::fmt(label, &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui); } impl StackDialog for RearrangeArtboardsDialog { @@ -192,13 +248,11 @@ impl StackDialog for RearrangeArtboardsDialog { fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { let (artboards, lengths) = (self.artboards, self.lengths); - let shown = FormDialog::new(tl!("Rearrange All Artboards"), Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show( - ui, - |ui, _, v| { - body(ui, v, artboards, lengths); - true - }, - ); + let title = if self.values.indices.is_some() { tl!("Rearrange") } else { tl!("Rearrange All Artboards") }; + let shown = FormDialog::new(title, Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show(ui, |ui, _, v| { + body(ui, v, artboards, lengths); + true + }); match (shown.accepted, shown.closed) { (Some(value), _) => Some(DialogResult::Ok(value)), (None, Some(_)) => Some(DialogResult::Cancel), @@ -212,7 +266,12 @@ impl StackDialog for RearrangeArtboardsDialog { fn json_fields(&self) -> Option { let v = &self.values; - Some(json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork})) + let mut fields = + json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork}); + if let Some(indices) = &v.indices { + fields["indices"] = json!(indices); + } + Some(fields) } fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { @@ -247,17 +306,128 @@ impl StackDialog for RearrangeArtboardsDialog { } } -/// Runs `artboard.rearrange` for the settings OK confirmed, and remembers the spacing of a successful one. +/// Runs `artboard.rearrange` for the settings OK confirmed, and remembers the spacing of a successful +/// one. Rearrange for the selected artboards runs nothing yet: it waits for its click on the canvas +/// ([`place`]). pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::()) else { return }; - match app.run(CMD, values.params()) { - Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing), - Err(e) => app.status(e), + match &values.indices { + None => match app.run(CMD, values.params()) { + Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing), + Err(e) => app.status(e), + }, + Some(listed) => match wait_for_click(app, listed, values.params()) { + Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing), + Err(e) => app.status(e), + }, } ctx.request_repaint(); } +/// Rearrange for artboards `listed` with `params`, confirmed: it waits for its click on the canvas, +/// for the active document and the tool in use. +fn wait_for_click(app: &mut VectorcraftApp, listed: &[usize], params: Value) -> Result<(), String> { + let st = app.session.active().ok_or_else(|| "no document".to_string())?; + let ids: Vec = listed.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.id).collect(); + if ids.len() != listed.len() { + return Err("no such artboard".into()); + } + let (doc, tool) = (st.uid, app.session.tool_id().to_string()); + app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params, ids, armed: false }); + app.status(PLACE_HINT); + Ok(()) +} + +/// The artboards a waiting placement lays out. +fn placed(pl: &RearrangePlacement) -> Vec { + pl.params["indices"].as_array().into_iter().flatten().filter_map(Value::as_u64).filter_map(|i| usize::try_from(i).ok()).collect() +} + +/// Drop the placement waiting for its click, and its message in the status bar. +pub(crate) fn cancel_placement(app: &mut VectorcraftApp) { + if app.ui.rearrange_placement.take().is_some() && app.ui.status == PLACE_HINT { + app.status(""); + } +} + +/// Whether a placement waits for its click: one whose document is no longer the active one, whose +/// tool is no longer the tool in use, or whose listed places no longer hold the artboards it was +/// confirmed for (removed or moved in the list) is dropped. +pub(crate) fn refresh_placement(app: &mut VectorcraftApp) -> bool { + let Some(pl) = app.ui.rearrange_placement.as_ref() else { return false }; + let same = app.session.active().filter(|d| d.uid == pl.doc).is_some_and(|d| { + let listed = placed(pl); + listed.len() == pl.ids.len() && listed.iter().zip(&pl.ids).all(|(i, id)| d.doc.artboards.get(*i).is_some_and(|a| a.id == *id)) + }); + if same && app.session.tool_id() == pl.tool { + return true; + } + cancel_placement(app); + false +} + +/// Whether a placement waits and has been seen by one canvas pass, so a key that arrives now is not +/// the Enter that confirmed its dialog. +pub(crate) fn armed(app: &VectorcraftApp) -> bool { + app.ui.rearrange_placement.as_ref().is_some_and(|pl| pl.armed) +} + +/// Marks a waiting placement as seen by the canvas (see [`armed`]). +pub(crate) fn arm(app: &mut VectorcraftApp) { + if let Some(pl) = app.ui.rearrange_placement.as_mut() { + pl.armed = true; + } +} + +/// Runs the waiting placement's `artboard.rearrange` with the grid's top-left at `at` (the pressed +/// point, or the pointer when Enter placed it); without `at` the grid starts at the first selected +/// artboard's top-left. When every selected artboard is locked, the status bar says so. +pub(crate) fn place(app: &mut VectorcraftApp, at: Option) { + let Some(mut pl) = app.ui.rearrange_placement.take() else { return }; + let listed = placed(&pl); + let locked = app.session.active().is_some_and(|d| listed.iter().all(|i| d.doc.artboards.get(*i).is_some_and(|a| a.locked))); + if let Some(at) = at { + pl.params["at"] = json!([at.x, at.y]); + } + match app.run(CMD, pl.params) { + // Every selected artboard locked: nothing could move. + Ok(r) if r["moved"] == 0 && locked => app.status("the artboard is locked"), + Ok(_) => app.status(""), + Err(e) => app.status(e), + } +} + +/// The grid a waiting placement makes with its top-left at the pointer (`app.hover_doc`): the +/// outline of each artboard that moves, in the Artboard tool's color, 1 point wide on screen. +pub(crate) fn placement_overlays(app: &VectorcraftApp) -> Vec { + let Some(pl) = app.ui.rearrange_placement.as_ref().filter(|pl| app.session.tool_id() == pl.tool) else { return vec![] }; + let (Some(at), Some(st)) = (app.hover_doc, app.session.active().filter(|d| d.uid == pl.doc)) else { return vec![] }; + let boards: Vec<&vectorcraft_doc::Artboard> = placed(pl).into_iter().filter_map(|i| st.doc.artboards.get(i)).collect(); + let sizes: Vec<(f64, f64)> = boards.iter().map(|a| (a.rect.width(), a.rect.height())).collect(); + let p = &pl.params; + let layout = p["layout"].as_str().and_then(ArtboardLayout::parse).unwrap_or_default(); + let lines = p["columns"].as_f64().filter(|c| c.is_finite()).map_or(2, |c| c.round().max(1.0) as u64); + let spacing = p["spacing"].as_f64().filter(|s| s.is_finite()).unwrap_or(20.0).clamp(-1.0e5, 1.0e5); + let (origins, ..) = rearrange_grid(&sizes, at, layout, lines, spacing, p["order"] == "rightToLeft"); + // A locked artboard keeps its cell but stays where it is. + origins + .iter() + .zip(&sizes) + .zip(&boards) + .filter(|(_, a)| !a.locked) + .map(|((o, (w, h)), _)| { + let mut path = BezPath::new(); + path.move_to(*o); + path.line_to((o.x + w, o.y)); + path.line_to((o.x + w, o.y + h)); + path.line_to((o.x, o.y + h)); + path.close_path(); + Overlay::Path { path, color: vectorcraft_tools::xform::BLUE, width: 1.0, dashed: false } + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -296,6 +466,11 @@ mod tests { crate::dialogs::host::pump(app, &ctx); } + /// The open dialog's fields. + fn fields(app: &VectorcraftApp) -> Value { + app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap() + } + /// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a /// setting the layout makes meaningless is refused. #[test] @@ -337,7 +512,72 @@ mod tests { ok(&mut app); app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); - let fields = app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap(); - assert_eq!(fields["spacing"].as_f64(), Some(37.0)); + assert_eq!(fields(&app)["spacing"].as_f64(), Some(37.0)); + } + + /// The Artboard tool's canvas menu opens Rearrange for the artboards the tool has selected, + /// with their count; OK moves nothing and waits for a click on the canvas with those artboards + /// and the dialog's fields. Rearrange All Artboards still lays out every artboard at once. + #[test] + fn rearrange_from_the_canvas_menu_waits_for_a_click_with_the_selected_artboards() { + let mut app = app(3); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 2])); + let items = crate::menus::context_items(&app); + let target = items.iter().find_map(|i| match i { + crate::menus::Node::Item(item) if item.label == "Rearrange" => { + Some(crate::menus::click_target("Rearrange", &item.command.id, &item.command.params)) + } + _ => None, + }); + let (id, p) = target.expect("Rearrange in the canvas menu"); + crate::menus::invoke(&mut app, &id, p); + assert!(app.dialogs().unwrap().with(|host| host.get::().is_some()), "Rearrange opens"); + let shown = fields(&app); + assert_eq!(shown["indices"], json!([0, 2])); + let (title, count) = app.dialogs().unwrap().with(|host| { + let d = host.get::().unwrap(); + (d.values.indices.is_some(), d.artboards) + }); + assert_eq!((title, count), (true, 2), "Rearrange for the 2 selected artboards"); + set(&app, &[("layout", json!("row"))]).unwrap(); + let (before, undo) = (origins(&app), app.session.doc().unwrap().history.undo.len()); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!((origins(&app), app.session.doc().unwrap().history.undo.len()), (before.clone(), undo)); + let waiting = app.ui.rearrange_placement.as_ref().expect("waits for a click"); + assert_eq!((waiting.params["indices"].clone(), waiting.params["layout"].clone()), (json!([0, 2]), json!("row"))); + assert_eq!(app.ui.status, PLACE_HINT); + + // Rearrange All Artboards drops it and runs at once. + app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); + assert!(app.ui.rearrange_placement.is_none()); + assert!(fields(&app).get("indices").is_none()); + ok(&mut app); + assert_ne!(origins(&app), before); + assert_ne!(app.ui.status, PLACE_HINT); + } + + /// The outline of a waiting placement follows the pointer: the first selected artboard's cell + /// starts at the pointer, and a locked selected artboard has none. + #[test] + fn the_placement_outline_starts_at_the_pointer_and_leaves_locked_artboards_out() { + let mut app = app(3); + app.session.execute("artboard.setProps", &json!({"index": 2, "locked": true})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 1, 2])); + crate::panels::artboards::open_rearrange_selected(&mut app); + set(&app, &[("layout", json!("row")), ("spacing", json!(10))]).unwrap(); + ok(&mut app); + assert!(placement_overlays(&app).is_empty(), "no pointer over the canvas"); + app.hover_doc = Some(Point::new(500.0, 300.0)); + let starts: Vec = placement_overlays(&app) + .iter() + .map(|o| match o { + Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()).unwrap(), + o => panic!("{o:?}"), + }) + .collect(); + assert_eq!(starts, [Point::new(500.0, 300.0), Point::new(610.0, 300.0)]); } } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index fb8aea7c51..c6c9f72d3d 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -212,8 +212,6 @@ const ARROW: ColumnKey = ColumnKey::new("arrow"); const NEW: ColumnKey = ColumnKey::new("new"); const HEX: ColumnKey = ColumnKey::new("hex"); /// The arrow of a row that is recolored, and of one that is excluded (a dashed line without a head). -// PLAN: assumed icons `dc-recolor-arrow` and `dc-recolor-arrow-off` (VectorCraft's own solid and dashed arrows); -// the assets owner draws them and adds them to `assets/icons`, `icon_data.rs` and `ASSETS.md`. const ARROW_ON: &str = "dc-recolor-arrow"; const ARROW_OFF: &str = "dc-recolor-arrow-off"; diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 3804c4ea3a..a61190970e 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -9,7 +9,8 @@ use craft::behavior::{DisplayOrder, ItemSource, SelectionChange}; use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::contract::Entry; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; use craft::ui::runtime::env::LengthUnits; @@ -369,19 +370,23 @@ pub(crate) fn bevel_row(data: &Data, effect: &str, place: Place) -> Param { }; let default_at = options[..builtin].iter().position(|(_, v, _)| *v == default); let titles: Vec = options.iter().map(|(l, _, _)| l.clone()).collect(); - ui.horizontal(|ui| { - if let Some((_, v, c)) = pick(ui, c3("Bevel Shape"), &titles, current, default_at).and_then(|i| options.get(i)) { - set_value(fields, "bevel", v); - if let Some((n, p)) = c { - set_value(fields, BEVEL_NAME, &json!(n)); - set_value(fields, BEVEL_PROFILE, p); - } + // The row's body may run more than once in a pass: it reports the pick and the press, which apply after it. + let (mut picked, mut edit) = (None, false); + let row = Row::new().show(ui, |ui, _| { + picked = pick(ui, c3("Bevel Shape"), &titles, current, default_at); + edit = place == Place::Panel && pressed(ui, tl!("Edit Bevels…"), file, None); + }); + if let Some((_, v, c)) = picked.and_then(|i| options.get(i)) { + set_value(fields, "bevel", v); + if let Some((n, p)) = c { + set_value(fields, BEVEL_NAME, &json!(n)); + set_value(fields, BEVEL_PROFILE, p); } - if place == Place::Panel && pressed(ui, tl!("Edit Bevels…"), file, None) { - fields.set("__editBevels", true); - } - }) - .response + } + if edit { + fields.set("__editBevels", true); + } + row.output }) .companions([BEVEL_NAME, BEVEL_PROFILE, "__editBevels"]) } @@ -675,12 +680,13 @@ fn light_color_row() -> Param { Param::custom("lightColor", tl!("Color"), |ui, fields, cx| { let hex = fields.text("lightColor").unwrap_or("#ffffff").to_owned(); let color = Srgba::from_hex(&hex).unwrap_or(Srgba::rgb(1.0, 1.0, 1.0)); - ui.horizontal(|ui| { - if pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color"))) { - cx.pick_color("__lightPick", color); - } - }) - .response + // The row's body may run more than once in a pass: the picker opens after it. + let mut ask = false; + let row = Row::new().show(ui, |ui, _| ask = pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color")))); + if ask { + cx.pick_color("__lightPick", color); + } + row.output }) .opens_with("#ffffff") } @@ -711,11 +717,11 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { // The classic effects' lights have no colour. let settings: Vec = settings.into_iter().filter(|p| !(classic && p.key == "lightColor")).collect(); Param::custom("lights", tl!("Lights"), move |ui, fields, cx| { + if let Some(Value::String(hex)) = fields.color("__lightPick").map(|c| json!(Srgba::from_rgb_array(c).to_hex())) { + fields.remove("__lightPick"); + set_light_value(fields, "lightColor", json!(hex)); + } ui.vertical(|ui| { - if let Some(Value::String(hex)) = fields.color("__lightPick").map(|c| json!(Srgba::from_rgb_array(c).to_hex())) { - fields.remove("__lightPick"); - set_light_value(fields, "lightColor", json!(hex)); - } let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); let mut index = light_index(fields, list.len()); let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -724,27 +730,31 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { } // Add Light is off while a setting of the single light is mixed. let mixed = explicit_lights(fields).is_none() && LIGHT_KEYS.iter().any(|(_, key)| fields.is_mixed(key)); - ui.horizontal(|ui| { - if pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None) { - let mut added = selected_light(fields); - let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); - for (_, key) in LIGHT_KEYS { - if let Some(value) = defaults.get(key) { - set_value(&mut added, key, value); - } - } - set_value(&mut added, "lightRotation", &json!(0.0)); - set_value(&mut added, "lightHeight", &json!(90.0)); - list.push(light_record(&added)); - index = list.len() - 1; - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } - if pressed(ui, tl!("Delete Light"), list.len() > 1, None) && index < list.len() { - list.remove(index); - index = index.min(list.len().saturating_sub(1)); - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut add, mut delete) = (false, false); + Row::new().show(ui, |ui, _| { + add = pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None); + delete = pressed(ui, tl!("Delete Light"), list.len() > 1, None); }); + if add { + let mut added = selected_light(fields); + let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); + for (_, key) in LIGHT_KEYS { + if let Some(value) = defaults.get(key) { + set_value(&mut added, key, value); + } + } + set_value(&mut added, "lightRotation", &json!(0.0)); + set_value(&mut added, "lightHeight", &json!(90.0)); + list.push(light_record(&added)); + index = list.len() - 1; + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } + if delete && index < list.len() { + list.remove(index); + index = index.min(list.len().saturating_sub(1)); + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } fields.set("__light", i64::try_from(index).unwrap_or(0)); if place == Place::Panel || classic { super::revolve_lights::sphere(ui, fields, cx, classic); diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index f11bc461bf..53f7a888fe 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -158,6 +158,35 @@ fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() { assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect"); } +/// The theme's plot size, as a pass of the app's interface resolves it. +fn plot_size() -> egui::Vec2 { + let mut plot = None; + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let size = craft::ui::runtime::env::Env::of(ui).tokens.size.plot; + plot = Some(vec2(size.width, size.height)); + }) + .textures_delta + .clear(); + plot.expect("the pass ran") +} + +#[test] +fn map_art_surface_preview_takes_the_themes_plot_size() { + let mut h = opened(with_symbol("M50 50L150 50L150 150L50 150Z"), json!({"effect":CLASSIC_EXTRUDE,"item":null})); + h.set("__page", json!("mapArt")); + let plot = plot_size(); + let tree = h.fixture.tree(); + let surface = h + .fixture + .by_role(craft::ui::contract::Role::CANVAS) + .into_iter() + .find(|t| tree.name_of(t.node) == Some("Surface")) + .expect("Map Art shows the surface canvas"); + assert_eq!(surface.rect.height(), plot.y, "the preview is as tall as the theme's plot: {:?}", surface.rect); + assert!(surface.rect.width() >= plot.x, "the preview is at least as wide as the theme's plot: {:?}", surface.rect); +} + #[test] fn map_art_maps_no_more_surfaces_than_an_object_takes() { let max = vectorcraft_effects::MAX_MAPS; diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 3ef06cecef..985b13174a 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -19,9 +19,10 @@ use craft::ui::contract::{ Remember as _, Role, Show as _, }; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog}; +use craft::ui::primitives::{ContentPainterCx, TextRun}; use craft::ui::runtime::focus::KeyUse; -use craft::ui::style::{ComponentStyle, StyleColor, StyleCx}; -use egui::{Align2, FontId, Painter, Pos2, Rect, Response, Stroke, Ui, Vec2, vec2}; +use craft::ui::style::{ComponentStyle, StyleColor, StyleCx, TypeRole}; +use egui::{Pos2, Rect, Response, Stroke, Ui, Vec2, vec2}; use serde_json::json; use vectorcraft_effects::{CLASSIC_REVOLVE, REVOLVE}; use vectorcraft_geom::Point; @@ -39,6 +40,8 @@ const RING_REACH: f32 = 9.0; const ORBIT_REACH: f32 = 14.0; /// How far from the light's handle a press takes it, in points. const LIGHT_REACH: f32 = 18.0; +/// The least radius of the plate under an axis letter, in points; a taller letter gets a plate as tall as its line. +const AXIS_PLATE: f32 = 9.0; const RING: PartKey = PartKey::new("ring"); const CENTRE: PartKey = PartKey::new("centre"); @@ -568,7 +571,7 @@ impl Component for RevolveGizmo<'_> { let Some(g) = Geometry::new(&space.view, &self.subject.fields, self.subject.bounds) else { return }; let content = ui.content_painter(cx); let paint = Paint { - painter: &content.painter, + content: &content, style: cx.style, view: &space.view, subject: self.subject, @@ -606,7 +609,8 @@ fn light_position(g: Geometry, options: Revolve) -> Pos2 { /// What a pass draws with. struct Paint<'a> { - painter: &'a Painter, + /// The content painter: its `painter` draws the rings and plates, and its `Draw` lays out and paints the labels. + content: &'a ContentPainterCx<'a>, style: &'a RevolveGizmoStyle, view: &'a CanvasView, subject: &'a Subject, @@ -620,10 +624,11 @@ struct Paint<'a> { impl Paint<'_> { fn rotation(&self) { - let (g, s, painter) = (self.g, self.style, self.painter); + let (g, s, painter) = (self.g, self.style, &self.content.painter); for (axis, ring) in g.rings.iter().enumerate() { let hot = self.active == Some(axis); - let color = if hot { s.hot.egui() } else { s.axis(axis).egui() }; + let ink = if hot { s.hot } else { s.axis(axis) }; + let color = ink.egui(); for i in 0..SAMPLES { let angle = i as f32 * std::f32::consts::TAU / SAMPLES as f32; let behind = ring.depth[0] * angle.cos() + ring.depth[1] * angle.sin() < -0.05; @@ -641,8 +646,10 @@ impl Paint<'_> { _ => 4.7, }; let p = g.center + ring.point(phase); - painter.circle_filled(p, 9.0, s.plate.egui()); - painter.text(p, Align2::CENTER_CENTER, ["X", "Y", "Z"][axis], FontId::proportional(11.0), color); + self.text(["X", "Y", "Z"][axis], ink, |size| { + painter.circle_filled(p, (size.max_elem() * 0.5).max(AXIS_PLATE), s.plate.egui()); + p - size * 0.5 + }); } painter.circle(g.center, 8.0, s.plate.egui().gamma_multiply(0.8), Stroke::new(1.5, s.muted.egui())); painter.line_segment([g.center - vec2(4.0, 0.0), g.center + vec2(4.0, 0.0)], Stroke::new(1.0, s.muted.egui())); @@ -654,12 +661,12 @@ impl Paint<'_> { if let Some(Mode::Ring { axis, .. }) = self.dragging { let degrees = self.values.rotation.get(axis).copied().unwrap_or(0.0); let text = format!("{} {degrees:.1}°", ["X", "Y", "Z"].get(axis).unwrap_or(&"")); - self.readout(text, g.center + vec2(0.0, g.radius * 1.12 + 18.0), 12.0); + self.readout(&text, g.center + vec2(0.0, g.radius * 1.12 + 18.0)); } } fn light(&self) { - let (g, s, painter) = (self.g, self.style, self.painter); + let (g, s, painter) = (self.g, self.style, &self.content.painter); let options = light_options(&self.subject.fields); let radius = g.radius * 1.4; painter.circle_stroke(g.center, radius, Stroke::new(1.0, s.muted.egui().gamma_multiply(0.3))); @@ -682,7 +689,7 @@ impl Paint<'_> { let label = labels[axis]; painter.rect_filled(label, 4.0, if self.active == Some(axis) { s.plate_hover.egui() } else { s.plate.egui() }); let text = if axis == 0 { tl!("Rotation") } else { tl!("Height") }; - painter.text(label.center(), Align2::CENTER_CENTER, text, FontId::proportional(11.0), s.hot.egui()); + self.text(text, s.hot, |size| label.center() - size * 0.5); } let p = light_position(g, options); let delta = g.center - p; @@ -710,22 +717,34 @@ impl Paint<'_> { painter.line_segment([p + direction * 13.0, p + direction * 17.0], Stroke::new(1.5, s.hot.egui())); } let name = crate::i18n::tr_ctx(crate::i18n::current(), "lighting", "Light"); - let galley = painter.layout_no_wrap(name.to_string(), FontId::proportional(11.0), s.hot.egui()); - let name_pos = p - vec2(galley.size().x * 0.5, 25.0 + galley.size().y); - painter.rect_filled(Rect::from_min_size(name_pos - vec2(4.0, 2.0), galley.size() + vec2(8.0, 4.0)), 3.0, s.plate.egui()); - painter.galley(name_pos, galley, s.hot.egui()); + self.text(name, s.hot, |size| { + let name_pos = p - vec2(size.x * 0.5, 25.0 + size.y); + painter.rect_filled(Rect::from_min_size(name_pos - vec2(4.0, 2.0), size + vec2(8.0, 4.0)), 3.0, s.plate.egui()); + name_pos + }); if self.dragging.is_some() { let text = format!("{} {:.1}° {} {:.1}°", tl!("Rotation"), self.values.light_rotation, tl!("Height"), self.values.light_height); - self.readout(text, g.center + vec2(0.0, radius + 56.0), 11.5); + self.readout(&text, g.center + vec2(0.0, radius + 56.0)); } } /// `text` on a plate centred at `at`. - fn readout(&self, text: String, at: Pos2, size: f32) { - let (s, painter) = (self.style, self.painter); - let galley = painter.layout_no_wrap(text, FontId::proportional(size), s.ink.egui()); - painter.rect_filled(Rect::from_center_size(at, galley.size() + vec2(14.0, 8.0)), 4.0, s.plate.egui()); - painter.galley(at - galley.size() * 0.5, galley, s.ink.egui()); + fn readout(&self, text: &str, at: Pos2) { + let (s, painter) = (self.style, &self.content.painter); + self.text(text, s.ink, |size| { + painter.rect_filled(Rect::from_center_size(at, size + vec2(14.0, 8.0)), 4.0, s.plate.egui()); + at - size * 0.5 + }); + } + + /// Paints `text` in the label type role and `color` at the top left `place` gives for its size; `place` may paint + /// what goes under the text. + fn text(&self, text: &str, color: StyleColor, place: impl FnOnce(Vec2) -> Pos2) { + self.content.with_draw(|draw| { + let layout = draw.layout(&TextRun::new(text).role(TypeRole::Label).color(color), f32::INFINITY); + let at = place(layout.size()); + draw.galley(at, &layout); + }); } } diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 921dd8d37f..b65a1f40cb 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -35,7 +35,8 @@ use vectorcraft_eps::{Level, Overprint, Preview}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, TooltipSpec}; +use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{ThumbAspect, ToggleState}; use craft::ui::notices::Notice; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; @@ -399,10 +400,12 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> let mut boards = picked_boards(fields, n); let before = boards.clone(); let files = board_files(menus.doc.as_deref(), fields.text("path").unwrap_or_default(), &boards); - let response = ui - .vertical(|ui| { + let response = Stack::new() + .show(ui, |ui, _| { + // Each run of the body starts from the checks as they stood: a check flips them, and the body may run twice. + boards.clone_from(&before); ui.label(tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")); - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { if Button::new(tl!("Select All")).show(ui).clicks > 0 { boards.iter_mut().for_each(|b| *b = true); } @@ -444,7 +447,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } } }) - .response; + .output; if boards != before || boards_in(fields).is_none() { fields.set("boards", FieldValue::Json(json!(boards))); } diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index cb848e5c85..6def4534d4 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -23,6 +23,7 @@ use craft::ui::choice::Swatch; use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; use craft::ui::form::Field; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use craft::ui::text::HexField; @@ -207,10 +208,8 @@ pub(super) fn colour_rows(gamut: Gamut<'static>) -> Vec { // Spot colours are always global. Param::new("global", tl!("Global").to_owned(), ParamKind::bool(false)).enabled_when("type", "process").disabled_value(true), Param::new("mode", field_label(tl!("Color Mode:")), ParamKind::choice(modes, Some("rgb".to_owned()))), - Param::custom("color", tl!("Color").to_owned(), move |ui, fields, context| { - ui.vertical(|ui| edit_colour(ui, fields, &gamut, context)).response - }) - .companions(["hex", "hsb"]), + Param::custom("color", tl!("Color").to_owned(), move |ui, fields, context| edit_colour(ui, fields, &gamut, context)) + .companions(["hex", "hsb"]), ] } @@ -412,7 +411,7 @@ pub(super) fn correct(app: &mut VectorcraftApp, id: DialogId) { /// The colour row: one slider and value field per component of the dialog's mode, the hex field (RGB, HSB and /// Web), a chip of the colour and under it the mode's warnings. The colour follows the mode: a colour in another /// model is converted when the mode changes. -fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'static>, context: &mut CustomContext) { +fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'static>, context: &mut CustomContext) -> egui::Response { // A hex colour set from outside the row (automation) replaces the colour once. if let Some(hex) = fields.text("hex").map(str::to_owned) { fields.remove("hex"); @@ -439,8 +438,9 @@ fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'stat warnings.push((Warning::Web, ColorWarning::web_colors(tl!("Out of Web Color Warning").to_owned(), Srgba::rgb(r, g, b)))); } let mut edit: Option<(Color, Option)> = None; - ui.horizontal_top(|ui| { - ui.vertical(|ui| { + let mut actions = Vec::new(); + let shown = Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { for (i, ch) in model.channels().iter().enumerate() { let mut rule = ChannelRule::of(ch); if web { @@ -478,21 +478,26 @@ fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'stat } } }); - ui.vertical(|ui| { + Stack::new().show(ui, |ui, _| { Swatch::new(tl!("Color").to_owned(), near).show(ui); + actions.clear(); for (warning, chip) in &warnings { if ColorWarningChip::new(chip).show(ui).clicked { - context.request_action(warning.action()); + actions.push(warning.action()); } } }); }); + for action in actions { + context.request_action(action); + } if let Some((c, kept)) = edit { set_color(fields, c); if let Some(k) = kept.filter(|k| k.model == HsbModel.id()) { fields.set("hsb", FieldValue::Json(json!([k.values[0], k.values[1], k.values[2]]))); } } + shown.output } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/tests_custom_rows.rs b/crates/ui-egui/src/dialogs/tests_custom_rows.rs new file mode 100644 index 0000000000..a7bae37aea --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_custom_rows.rs @@ -0,0 +1,73 @@ +//! Dialogs whose custom rows lay out several controls side by side or one under another take the width of their rows, +//! read from the access tree of the window. + +use egui::accesskit::Role; +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::fileio::FORMATS; + +use super::tests::{SCREEN, app, frame, settle}; +use crate::VectorcraftApp; + +/// The width of the dialog named `title` once it has settled. +fn dialog_width(app: &mut VectorcraftApp, title: &str) -> f32 { + settle(app); + let out = frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let dialog = update.nodes.iter().find(|(_, node)| node.role() == Role::Dialog && node.label() == Some(title)); + let bounds = dialog.and_then(|(_, node)| node.bounds()).unwrap_or_else(|| panic!("the {title} dialog is open")); + (bounds.x1 - bounds.x0) as f32 +} + +/// Writes `value` into `key` of the top dialog, as automation does. +fn set(app: &VectorcraftApp, key: &str, value: Value) { + let ctx = app.ui_ctx.clone().expect("a window app"); + let host = app.dialogs().expect("a dialog host"); + host.with(|h| { + let id = h.open_dialogs().last().map(|d| d.id).expect("an open dialog"); + h.set_json_field(&ctx, id, key, value) + }) + .unwrap(); +} + +/// Opens the options of raster format `id` for an export. +fn raster_options(app: &mut VectorcraftApp, id: &str) { + let f = FORMATS.iter().find(|f| f.id == id).expect("a raster format"); + super::png_options::open(app, f, json!({"format": id, "path": format!("/out/a.{id}")})); +} + +/// A custom row drawn as an egui layout measured as wide as the room the dialog offered it, so the dialog took the +/// window's whole width. Each dialog here holds such a row and stays well inside the window. +#[test] +fn dialogs_with_custom_rows_take_the_width_of_their_rows() { + let half = SCREEN.x / 2.0; + + let mut a = app(); + crate::menus::invoke(&mut a, "ui.dxfOptionsDialog", json!({})); + let dxf = dialog_width(&mut a, "DXF Options"); + + let mut a = app(); + crate::menus::invoke(&mut a, "ui.newSwatch", json!({})); + let swatch = dialog_width(&mut a, "New Swatch"); + + let mut a = app(); + raster_options(&mut a, "png"); + settle(&mut a); + set(&a, "ppi", json!(100)); + set(&a, "__otherPpi", json!(true)); + set(&a, "background", json!("#336699")); + let png = dialog_width(&mut a, "PNG Options"); + + let mut a = app(); + raster_options(&mut a, "jpg"); + let jpeg = dialog_width(&mut a, "JPEG Options"); + + let mut a = app(); + a.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap(); + a.run("select.all", json!({})).unwrap(); + super::effect::open(&mut a, &json!({"effect": "blur.radial"})).unwrap(); + let blur = dialog_width(&mut a, "Radial Blur"); + + for (name, width) in [("DXF Options", dxf), ("New Swatch", swatch), ("PNG Options", png), ("JPEG Options", jpeg), ("Radial Blur", blur)] { + assert!(width < half, "{name} is {width} pt wide in a {} pt window", SCREEN.x); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 600e1d8fa2..0330cd7521 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -160,6 +160,38 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { assert_eq!(pens(&fields(&app)), json!(automatic)); } +/// A press of Add adds one pen, a press of a pen's Remove removes that pen, a press of a pen's swatch opens one picker +/// whose color that pen takes, and a press of One Pen per Color sets the table aside, though the rows' bodies run more +/// than once in the pass that reads the press. +#[test] +fn pen_rows_apply_each_press_once() { + let (mut app, _) = app(1); + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + frame(&mut app); + press_control(&mut app, json!({"name": "Add", "role": "Button"})); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(["#ff0000", "#000000", "#000000"])); + press_control(&mut app, json!({"name": "Remove", "role": "Button", "index": 0})); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(["#000000", "#000000"])); + // The second pen's swatch opens the picker over the dialog; its OK colors that pen alone. + press_control(&mut app, json!({"name": "Pen color", "role": "ColorWell", "index": 1})); + frame(&mut app); + let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); + assert_eq!(open(&app), 2, "one picker opens on the dialog"); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app); + frame(&mut app); + assert_eq!((open(&app), kind(&app).as_deref()), (1, Some("hpglOptions"))); + assert_eq!(pens(&fields(&app)), json!(["#000000", "#00ff00"])); + press_control(&mut app, json!({"name": "One Pen per Color", "role": "RadioButton"})); + frame(&mut app); + let d = fields(&app); + assert!(pens(&d).is_null()); + assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#000000", "#00ff00"])); +} + /// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than /// starting from one black pen that the corrected options would keep. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 249c52a3f9..30a1aa9d65 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -492,3 +492,51 @@ fn the_text_choice_applies_to_embedded_places_only() { assert!(!matches!(placed.kind, NodeKind::PlacedDocument(_)), "embedded: {:?}", placed.kind); assert_eq!(type_objects(&app), before, "placed as outlines"); } + +/// `file.place` reads an empty or null `password` as none: a place from a path with Link on stays +/// linked with the PDF Text preference at Outlines, and only a password that is given embeds it. +#[test] +fn an_empty_password_keeps_a_place_linked() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-empty-password"); + let path = dir.join("one.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(1)).unwrap(); + for password in [json!(""), json!(null)] { + let mut p = json!({"path": path, "password": password}); + import_pdf::place_with_preferred_text_as(&app, &mut p); + assert_eq!(p, json!({"path": path, "password": password}), "no textAs with password {password}"); + } + let mut p = json!({"path": path, "password": "pw"}); + import_pdf::place_with_preferred_text_as(&app, &mut p); + assert_eq!(p["textAs"], "outlines", "a password embeds the page"); + + crate::place::run_for_user(&mut app, &json!({"path": path, "password": ""})).unwrap(); + opened(&mut app); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); +} + +/// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its +/// password, as one placed without `password` does; a password that is given goes to `file.place`. +#[test] +fn an_empty_password_still_asks_for_the_password() { + let mut app = app(); + let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); + let data = vectorcraft_format::base64_encode(&bytes); + let close = |app: &VectorcraftApp| { + let id = dialog_id(app).expect("an Import PDF dialog"); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx(app), id))); + assert!(!is_open(app)); + }; + for password in [json!(""), json!(null)] { + let p = json!({"name": "locked.pdf", "dataBase64": data, "password": password}); + assert!(import_pdf::offer_place_password(&mut app, &p), "asks with password {password}"); + assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + close(&app); + } + let p = json!({"name": "locked.pdf", "dataBase64": data, "password": "pw"}); + assert!(!import_pdf::offer_place_password(&mut app, &p), "a given password is placed with"); + assert!(!is_open(&app)); +} diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 67d45de47e..3429cf323e 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -223,6 +223,59 @@ impl PrintService for UprightQueue { } } +/// The printers whose settings the setup service was asked to open. +type Setups = Rc>>>; + +/// A print service that opens printer settings, recording each printer it was asked for. +struct SetupPrint(Jobs, Setups); + +impl PrintService for SetupPrint { + fn printers(&mut self) -> Vec { + MockPrint(self.0.clone()).printers() + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.0.clone()).print(job) + } + + fn has_setup(&self) -> bool { + true + } + + fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { + self.1.borrow_mut().push(printer.map(str::to_string)); + Ok(()) + } +} + +#[test] +fn setup_opens_the_settings_of_the_printer_chosen() { + let setups = Setups::default(); + let services = Services { print: Some(Box::new(SetupPrint(Jobs::default(), setups.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + press(&mut app, "Setup…"); + set(&mut app, "printer", json!("Office")); + press(&mut app, "Setup…"); + assert_eq!(*setups.borrow(), [Some("Proofer".to_string()), Some("Office".to_string())], "the default printer, then the one chosen"); + // PDF File has no printer settings. + set(&mut app, "printer", json!("PDF File")); + // The frame after the change draws the row with PDF File's controls. + pump(&mut app); + pump(&mut app); + let r = call_raw(&mut app, "ui.click", json!({"control": {"name": "Setup…"}})); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(setups.borrow().len(), 2); + // A service without printer settings shows no Setup…. + let (mut app, _) = self::app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + let r = call_raw(&mut app, "ui.click", json!({"control": {"name": "Setup…"}})); + assert_eq!(r["ok"], false, "{r}"); +} + #[test] fn a_landscape_job_goes_upright_to_a_queue_that_does_not_turn_it() { let sizes = |pdf: &[u8]| vectorcraft_pdf::info(pdf, None).unwrap().pages.iter().map(|p| (p.width, p.height)).collect::>(); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 622fce6a5e..544985b8d2 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -162,6 +162,42 @@ fn checked_artboards_read_as_a_range() { } } +/// The rect the frame `shapes` paint `texture` over; `None` when none paints it. +fn painted(shapes: &[egui::epaint::ClippedShape], texture: egui::TextureId) -> Option { + fn walk(shape: &egui::Shape, texture: egui::TextureId, out: &mut Option) { + match shape { + egui::Shape::Vec(all) => all.iter().for_each(|s| walk(s, texture, out)), + egui::Shape::Mesh(mesh) if mesh.texture_id == texture => { + let at = mesh.calc_bounds(); + *out = Some(out.map_or(at, |r| r.union(at))); + } + _ => {} + } + } + let mut out = None; + shapes.iter().for_each(|clipped| walk(&clipped.shape, texture, &mut out)); + out +} + +/// The grid's tiles and the list's thumbnails are square; an artboard of another shape keeps its +/// proportions in them. +#[test] +fn an_artboards_picture_keeps_its_proportions() { + let (mut app, _) = app(1, false); + open(&mut app); + for view in ["grid", "list"] { + set(&mut app, "view", json!(view)); + frame(&mut app); + let ctx = app.ui_ctx.clone().expect("a test app has a window"); + let out = crate::testing::part_frame(&mut app, &ctx, Default::default(), |app, ui| app.ui(ui)); + let tex = app.canvas.artboard_thumbs.as_ref().and_then(|(_, thumbs)| thumbs.first().cloned().flatten()).expect("the artboard has a picture"); + let drawn = painted(&out.shapes, tex.id()).expect("the artboard's picture is drawn"); + let (picture, shown) = (tex.size_vec2(), drawn.size()); + assert!(picture.x > picture.y, "the 60×40 pt artboard is wider than high"); + assert!((shown.x / shown.y - picture.x / picture.y).abs() < 0.02, "{view}: a {picture:?} picture is drawn {shown:?}"); + } +} + #[test] fn opens_with_the_artboards_the_artboard_tool_selected_and_exports_only_them() { let (mut app, log) = app(4, true); diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 390c536503..8f1d65807f 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -14,11 +14,12 @@ use craft::ui::canvas::{CanvasSpace, canvas_space}; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Picture; +use craft::ui::layout_components::Row; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; -use craft::ui::runtime::env::UnitKind; +use craft::ui::runtime::env::{Env, UnitKind}; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::DataColor; use craft::ui::text::NumberField; @@ -32,6 +33,7 @@ use vectorcraft_effects::{ use super::revolve::{Place, bevel_row, c3, light_editor}; use super::three_d::{Data, with_fields}; +use super::track_cube::{SHADE_DARK, SHADE_LIGHT}; use crate::VectorcraftApp; /// The field that holds the number of the surface Map Art shows. @@ -288,7 +290,9 @@ fn navigator(count: usize, seen: Vec) -> Param { Param::custom(MAP_SURFACE, tl!("Surface"), move |ui, fields, _| { let current = shown_surface(fields, count); let mut next = None; - let row = ui.horizontal(|ui| { + let row = Row::new().show(ui, |ui, _| { + // The row's body may run more than once in a pass: the last run's step applies. + next = None; for (icon, tip, target, enabled) in [ ("chevrons_left", tl!("First Surface"), 1, current > 1), ("chevron_left", tl!("Previous Surface"), current.saturating_sub(1), current > 1), @@ -318,7 +322,7 @@ fn navigator(count: usize, seen: Vec) -> Param { if fields.number(MAP_SURFACE) != Some(shown as f64) { fields.set(MAP_SURFACE, shown as f64); } - row.response + row.output }) } @@ -379,10 +383,11 @@ pub(crate) fn map_done(dialog: &mut HostedParamDialog, effect: &str) { fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { let surface = surface_number(fields); let map = maps_of(fields).into_iter().find(|m| m.surface == surface); - let size = vec2(ui.available_width().max(ui.spacing().slider_width), ui.spacing().slider_width); // PLAN: tokens.size.plot + let tokens = Env::of(ui).tokens.clone(); + let size = vec2(ui.available_width().max(tokens.size.plot.width), tokens.size.plot.height); let (room, response) = ui.allocate_exact_size(size, Sense::hover()); let (width, height) = (flat.width.max(1e-6), flat.height.max(1e-6)); - let margin = f64::from(ui.spacing().item_spacing.x) * 2.0; + let margin = f64::from(tokens.space.gap.item) * 2.0; let zoom = ((f64::from(room.width()) - margin) / width).min((f64::from(room.height()) - margin) / height).max(1e-6); let view = CanvasView::new(room, Point::ZERO, zoom); let rect = flat.art.map(art_rect); @@ -390,7 +395,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { Canvas::new(tl!("Surface")).view(view).show_at(ui, room, |ui, body| { let corner = |x: f64, y: f64| view.to_screen(Point::new(x, y)); let page = egui::Rect::from_two_pos(corner(-width / 2.0, -height / 2.0), corner(width / 2.0, height / 2.0)); - let fill = if flat.visible { Color32::from_gray(205) } else { Color32::from_gray(90) }; + let fill = if flat.visible { SHADE_LIGHT } else { SHADE_DARK }; if let Some(space) = canvas_space(&body.env) { space.paint_picture(ui.ctx(), vec![egui::Shape::rect_filled(page, 0.0, fill)]); } @@ -428,21 +433,25 @@ fn map_actions(flat: Flat, has_map: bool, any_map: bool) -> Param { Param::custom("__mapActions", "", move |ui, fields, _| { let surface = surface_number(fields); let map = maps_of(fields).into_iter().find(|m| m.surface == surface); - ui.horizontal(|ui| { - let fit = Button::new(tl!("Scale to Fit")).enabled(has_map && flat.art.is_some()).show(ui); - if let (true, Some(m), Some(art)) = (fit.clicked(), map.as_ref(), flat.art) { - let art = vectorcraft_geom::Rect::new(0.0, 0.0, art.0, art.1); - let (scale_x, scale_y) = m.fitting_scales(art, (flat.width, flat.height)).unwrap_or((m.scale_x, m.scale_y)); - store_map(fields, surface, Some(&SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() })); - } - if Button::new(tl!("Clear")).enabled(has_map).show(ui).clicked() { - store_map(fields, surface, None); - } - if Button::new(tl!("Clear All")).enabled(any_map).show(ui).clicked() { - fields.set(MAP_ART, FieldValue::Json(json!([]))); - } - }) - .response + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut fit, mut clear, mut clear_all) = (false, false, false); + let row = Row::new().show(ui, |ui, _| { + fit = Button::new(tl!("Scale to Fit")).enabled(has_map && flat.art.is_some()).show(ui).clicked(); + clear = Button::new(tl!("Clear")).enabled(has_map).show(ui).clicked(); + clear_all = Button::new(tl!("Clear All")).enabled(any_map).show(ui).clicked(); + }); + if let (true, Some(m), Some(art)) = (fit, map.as_ref(), flat.art) { + let art = vectorcraft_geom::Rect::new(0.0, 0.0, art.0, art.1); + let (scale_x, scale_y) = m.fitting_scales(art, (flat.width, flat.height)).unwrap_or((m.scale_x, m.scale_y)); + store_map(fields, surface, Some(&SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() })); + } + if clear { + store_map(fields, surface, None); + } + if clear_all { + fields.set(MAP_ART, FieldValue::Json(json!([]))); + } + row.output }) .full_width() // The page's maps: automation sets them whole, as the rows above edit them one surface at a time. diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index 917cd5dc50..569f93bf81 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -20,14 +20,15 @@ use craft::host::{PickRequest, Picked}; use craft::ui::buttons::Button; use craft::ui::contract::SelectMode; use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; -use craft::ui::display::Text; -use craft::ui::layout_components::Row; +use craft::ui::display::{Shade, Text}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow}; // PLAN: assumed `craft::ui::patterns::form_dialogs::FieldValue` and `craft::ui::runtime::env::Label` paths. use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, PromptChoice, StackDialog, StandardPrompt, dialog_id}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; @@ -123,46 +124,55 @@ impl StackDialog for Manager { let (data, action) = (&self.data, &mut self.action); let dialog = Dialog::new(tl!("Tracing Presets")).buttons([FooterButton::new(tl!("Close"), DialogRole::Cancel)]); let shown = dialog.show(ui, |ui, _| { - Text::new(tl!("Presets:")).show(ui); - let out = List::new(tl!("Presets")) - .select(SelectMode::Single) - .max_rows(LIST_ROWS) - .selection(Bind::given(Selection::single(at))) - .show_items(ui, &Labels(&labels), &mut |&k, _| ListRow::new(labels[k].clone())); - for event in out.events { - if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event - && let Some(p) = keys.last().and_then(|&k| list.presets.get(k)) - { - *action = Some(Action::Select(p.0.clone())); - } - } - Row::new().show(ui, |ui, _| { - let buttons = [ - (Button::new(tl!("New…")).tooltip(tl!("A new preset starting from the selected one")), Action::New, true), - (Button::new(tl!("Edit…")), Action::Edit, !builtin), - (Button::new(tl!("Delete")), Action::Delete, !builtin), - (Button::new(tl!("Import…")), Action::Import, true), - (Button::new(tl!("Export…")), Action::Export, any_saved), - ]; - for (button, act, enabled) in buttons { - if clicked(&button.enabled(enabled).show(ui)) { - *action = Some(act); + // The list and its buttons on the left, the selected preset's name and settings on the right. + Row::new().id_salt("presets-body").show(ui, |ui, _| { + Stack::new().id_salt("presets-list").show(ui, |ui, _| { + Text::new(tl!("Presets:")).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + let out = List::new(tl!("Presets")) + .select(SelectMode::Single) + .max_rows(LIST_ROWS) + .selection(Bind::given(Selection::single(at))) + .show_items(ui, &Labels(&labels), &mut |&k, _| ListRow::new(labels[k].clone())); + for event in out.events { + if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event + && let Some(p) = keys.last().and_then(|&k| list.presets.get(k)) + { + *action = Some(Action::Select(p.0.clone())); + } } - } + Row::new().show(ui, |ui, _| { + let buttons = [ + (Button::new(tl!("New…")).tooltip(tl!("A new preset starting from the selected one")), Action::New, true), + (Button::new(tl!("Edit…")), Action::Edit, !builtin), + (Button::new(tl!("Delete")), Action::Delete, !builtin), + (Button::new(tl!("Import…")), Action::Import, true), + (Button::new(tl!("Export…")), Action::Export, any_saved), + ]; + for (button, act, enabled) in buttons { + if clicked(&button.enabled(enabled).show(ui)) { + *action = Some(act); + } + } + }); + }); + Stack::new().id_salt("presets-details").show(ui, |ui, _| { + Text::new(list_label(preset)).role(TypeRole::BodyStrong).show(ui); + // The selected preset's settings, as the editor shows them, to read only: edits land in a copy. + let mut params = preset.1.clone(); + // PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them. + ui.scope(|ui| { + ui.disable(); + rows::main_rows(ui, &mut params, data, RowsHost::Dialog); + rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None); + }); + if builtin { + Text::new(tl!("Built-in presets don't change: New makes a copy you can edit.")) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); + } + }); }); - // PLAN: the sheet's two columns and a strong name need layout and text variants that are not in the bundle; stacked and plain here. - Text::new(list_label(preset)).show(ui); - // The selected preset's settings, as the editor shows them, to read only: edits land in a copy. - let mut params = preset.1.clone(); - // PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them. - ui.scope(|ui| { - ui.disable(); - rows::main_rows(ui, &mut params, data, RowsHost::Dialog); - rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None); - }); - if builtin { - Text::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).show(ui); - } }); shown.output.result(|| ()) } diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs index 1c1d25b0eb..3df7af4cc8 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -66,9 +66,17 @@ fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, ok: bool) { /// The texts the dialogs paint, once they have faded in (each frame is a quarter second on). fn frame_texts(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { - fn walk(s: &egui::Shape, out: &mut Vec) { + frame_runs(app, ctx).into_iter().map(|(text, _, _)| text).collect() +} + +/// The texts the dialogs paint with where each is drawn and its font, once they have faded in. +fn frame_runs(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::Rect, Option)> { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect, Option)>) { match s { - egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Text(t) => { + let font = t.galley.job.sections.first().map(|section| section.format.font_id.clone()); + out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()), font)); + } egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), _ => {} } @@ -145,6 +153,22 @@ fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() { assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited)); } +#[test] +fn the_selected_preset_shows_beside_the_list_under_a_strong_name() { + let (mut app, ctx) = windowed(Default::default()); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + pass(&mut app, &ctx); + let runs = frame_runs(&app, &ctx); + let rect = |names: &[&str]| runs.iter().find(|r| names.contains(&r.0.as_str())).map(|r| r.1); + let (Some(export), Some(mode)) = (rect(&["Export…"]), rect(&["Mode", "Mode:"])) else { panic!("Export… and Mode: {runs:?}") }; + // The settings column starts right of the list's buttons and level with the list, not under it. + assert!(mode.left() >= export.right() && mode.top() < export.top(), "Mode {mode:?}, Export… {export:?}"); + // The selected preset's name over its settings is set apart from its row in the list. + let names: Vec<_> = runs.iter().filter(|r| r.0 == "[Default]").collect(); + assert_eq!(names.len(), 2, "{runs:?}"); + assert_ne!(names[0].2, names[1].2, "the list row and the name: {names:?}"); +} + #[test] fn the_editor_shows_document_library_s_library_and_colors() { let (mut app, ctx) = windowed(Default::default()); diff --git a/crates/ui-egui/src/dialogs/track_cube.rs b/crates/ui-egui/src/dialogs/track_cube.rs index 80d3a2746f..c920e48708 100644 --- a/crates/ui-egui/src/dialogs/track_cube.rs +++ b/crates/ui-egui/src/dialogs/track_cube.rs @@ -22,6 +22,12 @@ const CUBE_BOX: f32 = 124.0; const CUBE_HALF: f32 = 25.0; const RING_IN: f32 = 47.0; const RING_OUT: f32 = 60.0; +/// The grays the 3D dialogs shade a surface with, the same in every theme: light for the cube's top and bottom faces +/// and a Map Art surface the viewer sees, mid for the cube's left and right faces, and dark for its back face and a +/// hidden Map Art surface. +pub(super) const SHADE_LIGHT: Color32 = Color32::from_gray(205); +pub(super) const SHADE_MID: Color32 = Color32::from_gray(155); +pub(super) const SHADE_DARK: Color32 = Color32::from_gray(90); /// How far an edge reaches for the pointer (points). const EDGE_REACH: f32 = 5.0; /// Degrees one point of pointer movement turns the cube. @@ -425,12 +431,11 @@ fn paint_cube(painter: &egui::Painter, s: &RowStyle, rect: Rect, m: M3, active: if !face_visible(m, axis, side) { continue; } - // PLAN: the gray steps are literals; the data tokens of area plan §2 w3 were not visible to this writer. let fill = match (axis, side) { (2, true) => colors[2], - (2, false) => Color32::from_gray(90), - (1, _) => Color32::from_gray(205), - _ => Color32::from_gray(155), + (2, false) => SHADE_DARK, + (1, _) => SHADE_LIGHT, + _ => SHADE_MID, }; let points: Vec = face_corners(axis, side).iter().map(|&i| corner(m, center, i)).collect(); painter.add(egui::Shape::convex_polygon(points, fill, Stroke::NONE)); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 3150baae30..c9fbd71eb0 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -22,7 +22,8 @@ use std::sync::OnceLock; use craft::behavior::IconId; use craft::behavior::overlay::Side; use craft::ui::buttons::ToggleButton; -use craft::ui::contract::{Bind, Outcome as _, Show as _}; +use craft::ui::contract::{Bind, Outcome as _, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; use craft::ui::primitives::IconSpec; use craft::ui::rails::{DrawerGroup, DropAt, SlotId, ToolRailOutput, ToolSlot, ToolbarDrawer, ToolbarEdit}; @@ -456,7 +457,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ui: &mut Ui, rail_out: &ToolRailO if target.is_some() { return; } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (name, label, icon) in crate::state::ToolbarShow::CONTROLS { let on = shown.get(name); let button = ToggleButton::new(tl!(label), Bind::given(on)).icon(IconSpec::svg(IconId::new(icon))).icon_only(); diff --git a/crates/ui-egui/src/export_progress.rs b/crates/ui-egui/src/export_progress.rs index bfef9a1f61..c8170460a3 100644 --- a/crates/ui-egui/src/export_progress.rs +++ b/crates/ui-egui/src/export_progress.rs @@ -39,9 +39,10 @@ pub(crate) struct Shown { pub hide: Option<&'static str>, } -/// Seconds on the clock the jobs record their start with. -pub(crate) fn now() -> f64 { - craft::platform::clock::monotonic_ms() / 1000.0 +/// Seconds on the clock the jobs record their start with: the app's clock, which a test can hold +/// still. +pub(crate) fn now(app: &VectorcraftApp) -> f64 { + app.now() } /// The window of the first table that has a job it shows. Opening and placing wait for the tables @@ -58,7 +59,7 @@ fn first(app: &VectorcraftApp) -> Option { /// no other dialog is open, and runs the command of the button pressed. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let Some(shown) = first(app) else { return }; - let age = now() - shown.started; + let age = now(app) - shown.started; if age < DELAY { // Nothing else wakes the frame that opens the window. ui.ctx().request_repaint_after(Duration::from_secs_f64(DELAY - age)); @@ -99,7 +100,8 @@ mod tests { use super::DELAY; use crate::{Services, VectorcraftApp, background}; - /// An app whose background writer waits until `go` is set. + /// An app whose background writer waits until `go` is set. Its clock stands still: a job is only + /// old enough for its window after [`age`]. fn app(go: Arc) -> VectorcraftApp { let services = Services { write_shared: Some(Arc::new(move |_: &str, _: &[u8]| { @@ -112,6 +114,7 @@ mod tests { }; let mut app = VectorcraftApp::new(Session::new(), services); crate::tests_background::threaded(&mut app); + app.now_override = Some(0.0); app } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 764e53b9ff..768c162388 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -896,6 +896,7 @@ font-technology Variable Променливи Direct Selection Tool Инструмент „Директен избор“ Direction Handles Маркери за посока Disable Auto Add/Delete Изключване на автоматично добавяне/изтриване + Delete Removes Anchor Points and Keeps Paths Joined Delete премахва опорните точки и запазва контурите свързани Interpolate Control Points When Moving Anchors Интерполиране на маркерите за посока при преместване на опорни точки Disable Opacity Mask Изключване на маска за непрозрачност Discard Отхвърляне @@ -1284,6 +1285,147 @@ font-technology Variable Променливи Drop Artwork Поставяне на графика @msg {key} must be [x, y] with finite coordinates {key} трябва да е [x, y] с крайни координати @msg ids must contain 1–10000 object ids ids трябва да съдържа от 1 до 10000 идентификатора на обекти +@msg {what} can't be exported in 3D: {e} {what} не може да се експортира в 3D: {e} +@msg asset {id} isn't a 3D asset ресурсът {id} не е 3D ресурс +@msg asset {id} is a 3D asset: assets.export3D writes it ресурсът {id} е 3D ресурс: записва се с assets.export3D +@msg no 3D assets yet: collect an object with a 3D effect first (assets.add3D) все още няма 3D ресурси: първо съберете обект с 3D ефект (assets.add3D) +@msg select an object with a 3D effect (or give its ids) изберете обект с 3D ефект (или задайте идентификаторите му) +@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 изберете текст по затворен път +@msg `Custom` stands for changed settings: save the preset under another name `Custom` означава променени настройки: запазете предварителната настройка под друго име +@msg the selection has no gradient fill селекцията няма запълване с градиент +@msg the selection has no gradient stroke селекцията няма щрих с градиент +@msg the selection has no pattern fill селекцията няма запълване с мостра +@msg the selection has no pattern stroke селекцията няма щрих с мостра +@msg no gradient swatch `{name}` няма образец на градиент `{name}` +@msg no pattern swatch `{name}` няма образец на мостра `{name}` +@msg the library item is damaged елементът от библиотеката е повреден +@msg its zlib compression is damaged компресията му zlib е повредена +@msg its Zstandard compression is damaged компресията му Zstandard е повредена +@msg it decompresses to more than {_1} MB след декомпресиране заема повече от {_1} MB +@msg its editing data is for a different page данните му за редактиране са за друга страница +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` трябва да е "emBox", "capHeight", "xHeight" или "icfBox" +@msg Choose a .js or .jsx script Изберете скрипт .js или .jsx +@msg Ran {name} Изпълнен е {name} +@msg The script was stopped and its changes were undone Скриптът беше спрян и промените му бяха отменени +@msg a script is running: stop it or wait for it to finish изпълнява се скрипт: спрете го или изчакайте да завърши +@msg this is a compiled script, which cannot be run; use its source text това е компилиран скрипт, който не може да се изпълни; използвайте изходния му текст +@msg the script is not UTF-8 text скриптът не е текст в UTF-8 +@msg the script is too large to run скриптът е твърде голям, за да се изпълни +@msg a drag or an undo group is open; finish it before running a script има отворено влачене или група за отмяна; завършете го, преди да изпълните скрипт +@msg the script left a document that cannot be kept скриптът остави документ, който не може да се запази +@msg the script is no longer in the Scripts folder скриптът вече не е в папката 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 recovery copy could not be written, so the script was not run не можа да се запише копие за възстановяване, затова скриптът не беше изпълнен +@msg Script file access denied Достъпът до файла на скрипта е отказан +@msg Script file exceeds 8 MiB Файлът на скрипта надхвърля 8 MiB +@msg Script file is not open Файлът на скрипта не е отворен +@msg Script file cannot be decoded Файлът на скрипта не може да се декодира +@msg Script file is not a regular file Файлът на скрипта не е обикновен файл +@msg Script file does not exist Файлът на скрипта не съществува +@msg Script file could not be read Файлът на скрипта не можа да се прочете +@msg Script folder has more than 2,048 entries Папката на скрипта има повече от 2,048 елемента +@msg Script file open mode must be r, w, e or a Режимът на отваряне на файла на скрипта трябва да е r, w, e или a +@msg Script file writing is not available Записването на файлове от скрипт не е налично +@msg Script file dialogs are not available Файловите диалогови прозорци за скриптове не са налични +@msg Script files cannot be opened in another application Файловете на скриптове не могат да се отварят в друго приложение +@msg Script file access is unavailable on the web Достъпът до файлове от скрипт не е наличен в уеб версията +@msg Script has 256 files open Скриптът има 256 отворени файла +@msg Script file path exceeds 32,767 characters Пътят до файла на скрипта надхвърля 32,767 знака +@msg Script folder mask takes too many steps to match Маската за папка на скрипта изисква твърде много стъпки за съвпадение +@msg the script opened more file data than one run may open (32 MiB) скриптът отвори повече файлови данни, отколкото е разрешено за едно изпълнение (32 MiB) +@msg File.seek: takes a position and a mode File.seek: приема позиция и режим +@msg vc.run: give a command id, as a string vc.run: задайте идентификатор на команда като низ +@msg vc.run: takes a command id and an object of parameters vc.run: приема идентификатор на команда и обект с параметри +@msg vc.run: the parameters must be an object vc.run: параметрите трябва да са обект +@msg vc.run: the result{place} is too large for a script vc.run: резултатът{place} е твърде голям за скрипт +@msg $.evalFile requires a file path $.evalFile изисква път до файл +@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: времето за изчакване трябва да е крайно число милисекунди, 0 или повече +@msg $.evalFile: takes a file path and a timeout $.evalFile: приема път до файл и време за изчакване +@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: ред {line}, колона {column} от {file}: {e} (хвърлена грешка) +@msg {name}: line {line}, column {column}: {e} (thrown) {name}: ред {line}, колона {column}: {e} (хвърлена грешка) +@msg {name}: {e} (thrown) {name}: {e} (хвърлена грешка) +@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: ред {line}, колона {column} от {file}: {e} (ограничение) +@msg {name}: line {line}, column {column}: {e} (limit) {name}: ред {line}, колона {column}: {e} (ограничение) +@msg {name}: {e} (limit) {name}: {e} (ограничение) +@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: ред {line}, колона {column} от {file}: {e} (синтаксис) +@msg {name}: line {line}, column {column}: {e} (syntax) {name}: ред {line}, колона {column}: {e} (синтаксис) +@msg {name}: {e} (syntax) {name}: {e} (синтаксис) +@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: ред {line}, колона {column} от {file}: {e} (спрян) +@msg {name}: line {line}, column {column}: {e} (stopped) {name}: ред {line}, колона {column}: {e} (спрян) +@msg {name}: {e} (stopped) {name}: {e} (спрян) +@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: ред {line}, колона {column} от {file}: {e} (вътрешна грешка) +@msg {name}: line {line}, column {column}: {e} (internal) {name}: ред {line}, колона {column}: {e} (вътрешна грешка) +@msg {name}: {e} (internal) {name}: {e} (вътрешна грешка) +@msg {e} (these files stay written: {paths}) {e} (тези файлове остават записани: {paths}) +@msg $.{name}: give a name, as a string $.{name}: задайте име като низ +@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: задайте локал, например "en" или "de_DE", или null за този на интерфейса +@msg $.localize: give true or false $.localize: задайте true или false +@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: може да се зададе само 512, което включва локализацията, или 0 +@msg $.flags: give a number $.flags: задайте число +@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: скриптовете тук четат и записват само UTF-8 +@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: задайте името на кодировка като низ +@msg $.memCache: the memory cache size cannot be set $.memCache: размерът на кеша в паметта не може да се задава +@msg $.setenv: give a value, as a string $.setenv: задайте стойност като низ +@msg $.setenv: only {_1} can be set $.setenv: може да се зададе само {_1} +@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: стойността има най-много {MAX_ENV_BYTES} букви, цифри и _ . - @ +@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: задайте брой милисекунди от 0 до {MAX_SLEEP_MS} +@msg $.sleep: give a number of milliseconds $.sleep: задайте брой милисекунди +@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: изпълнението не може да чака в обратно извикване на вградена функция, в getter, в преобразуване или във файл, изпълнен от $.evalFile; извикайте го от собствения код на скрипта +@msg $.bp: scripts here have no debugger $.bp: скриптовете тук нямат дебъгер +@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: скриптовете все още не могат да показват диалогов прозорец +@msg {name}: give a message {name}: задайте съобщение +@msg {name}: give the text the field starts with {name}: задайте началния текст на полето +@msg {name}: the message is longer than 16 KiB {name}: съобщението е по-дълго от 16 KiB +@msg {name}: the title is longer than 256 bytes {name}: заглавието е по-дълго от 256 байта +@msg {name}: the text the field starts with is longer than 16 KiB {name}: началният текст на полето е по-дълъг от 16 KiB +@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: диалогов прозорец не може да се отвори в обратно извикване на вградена функция, в getter, в преобразуване или във файл, изпълнен от $.evalFile; извикайте го от собствения код на скрипта +@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: следващият отговор в `answers` е за {_1}, а не за {name} +@msg {name}: `answers` has no answer left for this dialog {name}: в `answers` не е останал отговор за този диалогов прозорец +@msg `answers` must be a list of answers `answers` трябва да е списък с отговори +@msg `answers` has more than {MAX_ANSWERS} answers `answers` има повече от {MAX_ANSWERS} отговора +@msg `answers` is larger than 1 MiB `answers` е по-голям от 1 MiB +@msg must be an object with `kind` and `value` трябва да е обект с `kind` и `value` +@msg must have exactly `kind` and `value` трябва да има точно `kind` и `value` +@msg is an alert's answer, whose `value` must be "ok" е отговор на предупреждение, чиято стойност `value` трябва да е "ok" +@msg is a confirm's answer, whose `value` must be true or false е отговор на потвърждение, чиято стойност `value` трябва да е true или false +@msg is longer than 16 KiB е по-дълъг от 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null е отговор на подкана, чиято стойност `value` трябва да е низ или null +@msg must have `kind` alert, confirm or prompt трябва да има `kind` alert, confirm или prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` е само за изпълнение без човек, когото да се пита: в приложението човекът отговаря на всеки диалогов прозорец +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` трябва да е цяло число от 1 до {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` е вложен на повече от 64 нива +@msg `args` must be an object `args` трябва да е обект +@msg `args` is larger than 1 MiB `args` е по-голям от 1 MiB +@msg `path` is empty `path` е празен +@msg `installed` takes a `path`, not a `source` `installed` приема `path`, а не `source` +@msg `path` must name a .js or .jsx file `path` трябва да сочи файл .js или .jsx +@msg give exactly one of `path` and `source` задайте точно едно от `path` и `source` +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg vc.document{place} is too large for a script vc.document{place} е твърде голям за скрипт +@msg vc.log: the log of this run is full vc.log: дневникът на това изпълнение е пълен +@msg this function's script run has ended изпълнението на скрипта на тази функция е приключило +@msg the script made more host calls than one run may make скриптът направи повече извиквания към приложението, отколкото е разрешено за едно изпълнение +@msg the script passed more data to and from commands than one run may pass скриптът предаде повече данни към и от команди, отколкото е разрешено за едно изпълнение +@msg the script added more objects and data to the documents than one run may add скриптът добави повече обекти и данни в документите, отколкото е разрешено за едно изпълнение +@msg {what}: the object is not a File or a Folder {what}: обектът не е File или Folder +@msg {what}: the count must be a finite number, 0 or more {what}: броят трябва да е крайно число, 0 или повече +@msg File.seek: the position must be a finite number File.seek: позицията трябва да е крайно число +@msg File.seek: the mode must be 0, 1 or 2 File.seek: режимът трябва да е 0, 1 или 2 +@msg script file is compiled: {value} файлът на скрипта е компилиран: {value} +@msg `name` must be the name of a script engine `name` трябва да е име на скриптов двигател +@msg the main script engine is new for each run and is never kept, so it cannot be dropped основният скриптов двигател е нов при всяко изпълнение и никога не се запазва, затова не може да бъде премахнат +@msg there is no script engine named {name} няма скриптов двигател с име {name} +@msg Running a script Изпълнява се скрипт +@msg Data Recovery can't keep copies in {path}: {e} Възстановяването на данни не може да пази копия в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Приставките не могат да се зареждат от {path}: {e} +@msg select a path изберете път File Файл File Dimensions Размери на файла @@ -2385,6 +2527,12 @@ font-technology Variable Променливи {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable разделителната способност не е налична + estimated memory {memory} приблизителна памет {memory} + memory unavailable паметта не е налична + Unknown format Неизвестен формат {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2533,6 +2681,7 @@ font-technology Variable Променливи One Point Perspective Preset 5 Предварителна настройка 5 за едноточкова перспектива Only Web Colors Само уеб цветове Opacity Непрозрачност + Show Opacity Показване на непрозрачността Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване Opacity Mask Маска за непрозрачност Opacity Mask Info Информация за маската за непрозрачност @@ -2970,6 +3119,9 @@ digits Malayalam Малаялам Scale Artwork with Artboard Мащабиране на графиката заедно с работната област Artboards: {n} Работни области: {n} Rearrange All Artboards… Пренареждане на всички работни области… + Rearrange… Пренареждане… + Selected Artboards: {n} Избрани работни области: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Кликнете върху платното, за да поставите работните области (Esc отменя) Recall Selection Възстановяване на селекцията RECENT СКОРОШНИ Recent Скорошни @@ -3221,6 +3373,7 @@ digits Malayalam Малаялам A two-finger rotate gesture on a trackpad rotates the canvas view. Жест за завъртане с два пръста върху тъчпад завърта изгледа на платното. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Задържането на клавиш изпълнява инструмента или командата от колоната „Задръжте“ в „Клавишни комбинации“; краткото натискане изпълнява обичайната му комбинация. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Колко секунди трябва да се задържи клавиш, преди вместо обичайната му комбинация да се изпълни комбинацията му със задържане. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete премахва избраните опорни точки и напасва кривата около всяка от тях, вместо да отваря контура там. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Когато премествате котвени точки, всяка крива с една преместена крайна точка запазва формата си спрямо краищата си. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Задържането на клавишната комбинация на инструмент го избира, докато я пуснете, а след това отново се избира предишният инструмент. Shows the bounding box while you move the selection or draw a shape. Показва ограничителната рамка, докато премествате селекцията или рисувате форма. @@ -3946,6 +4099,8 @@ digits Malayalam Малаялам Flattener Preset Предварителна настройка за сплескване X X Y Y +@msg the file's layers weren't read ({_1}): it comes in as its page, in one layer слоевете на файла не бяха прочетени ({_1}): той се импортира като своята страница, в един слой +@msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part слоевете на файла не бяха прочетени от данните му за редактиране ({_1}): те идват от частта му PDF Spot Colors Спот цветове Spot Colors… Спот цветове… Spread: Разпространение: @@ -4117,6 +4272,48 @@ digits Malayalam Малаялам Composite Fonts Съставни шрифтове Export Composite Fonts Експортиране на съставни шрифтове Import Composite Fonts Импортиране на съставни шрифтове +@msg each font must be {{name, parts}} всеки шрифт трябва да е {{name, parts}} +@msg unknown key `{k}`; a font takes name and parts неизвестен ключ `{k}`; шрифтът приема name и parts +@msg each font needs a name всеки шрифт изисква име +@msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не може да е име на съставен шрифт (от 1 до {COMPOSITE_NAME_MAX} знака, без управляващи знаци) +@msg `{name}`: parts must be an object `{name}`: parts трябва да е обект +@msg `{name}`: unknown class `{k}`; the classes are kanji, kana, punctuation, symbols, roman and numerals `{name}`: неизвестен клас `{k}`; класовете са kanji, kana, punctuation, symbols, roman и numerals +@msg `{name}`: {_1} must be an object `{name}`: {_1} трябва да е обект +@msg `{name}`: unknown key `{k}` in {_1} `{name}`: неизвестен ключ `{k}` в {_1} +@msg `{name}`: give the kanji part `{name}`: задайте частта kanji +@msg a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts документът съдържа най-много {COMPOSITE_FONTS_MAX} съставни шрифта +@msg two composite fonts are named `{_1}` два съставни шрифта имат името `{_1}` +@msg `{_1}` is the name of an installed font `{_1}` е името на инсталиран шрифт +@msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} е зададен с `{font}`, който е съставен шрифт +@msg give fonts: [{{name, parts}}…] задайте fonts: [{{name, parts}}…] +@msg path is empty path е празен +@msg fonts must be a list of composite fonts fonts трябва да е списък от съставни шрифтове +@msg names must be strings names трябва да са низове +@msg no composite font named `{n}` няма съставен шрифт с име `{n}` +@msg names must be a list of names names трябва да е списък от имена +@msg no composite fonts to export няма съставни шрифтове за експортиране +@msg not a composite fonts file: {e} не е файл със съставни шрифтове: {e} +@msg not a composite fonts file: no compositeFonts list не е файл със съставни шрифтове: няма списък compositeFonts +@msg the file holds more than {COMPOSITE_FONTS_MAX} composite fonts файлът съдържа повече от {COMPOSITE_FONTS_MAX} съставни шрифта +@msg the file is larger than 4 MB файлът е по-голям от 4 MB +@msg dataBase64 is not base64 dataBase64 не е в base64 +@msg give one of path, data or dataBase64 задайте едно от path, data или dataBase64 +@msg the file holds no composite fonts файлът не съдържа съставни шрифтове +@msg the file holds two composite fonts named `{_1}` файлът съдържа два съставни шрифта с име `{_1}` +@msg `{_1}` can't name a composite font `{_1}` не може да е име на съставен шрифт +@msg {k}: give a font {k}: задайте шрифт +@msg `{name}`: {k}: give a font `{name}`: {k}: задайте шрифт +@msg {k}: size must be {_1} to {_2}% {k}: size трябва да е от {_1} до {_2}% +@msg `{name}`: {k}: size must be {_1} to {_2}% `{name}`: {k}: size трябва да е от {_1} до {_2}% +@msg {k}: baseline must be {_1} to {_2}% {k}: baseline трябва да е от {_1} до {_2}% +@msg `{name}`: {k}: baseline must be {_1} to {_2}% `{name}`: {k}: baseline трябва да е от {_1} до {_2}% +@msg {k}: scale must be {_1} to {_2}% {k}: мащабът трябва да е от {_1} до {_2}% +@msg `{name}`: {k}: scale must be {_1} to {_2}% `{name}`: {k}: мащабът трябва да е от {_1} до {_2}% +@msg {k}: only kana, roman and numerals can be scaled {k}: само kana, roman и numerals могат да се мащабират +@msg `{name}`: {k}: only kana, roman and numerals can be scaled `{name}`: {k}: само kana, roman и numerals могат да се мащабират +@msg {k}: only kana can be scaled at the center {k}: само kana може да се мащабира спрямо центъра +@msg `{name}`: {k}: only kana can be scaled at the center `{name}`: {k}: само kana може да се мащабира спрямо центъра +@msg no composite font няма съставен шрифт Delete Font Изтриване на шрифт Kanji Канджи Kana Кана @@ -4783,6 +4980,10 @@ axis Both И двете @msg Save for Web: the image is empty Запис за уеб: изображението е празно @msg Save writes {_1}, not {_2}: use document.export for other formats Записът записва {_1}, а не {_2}: използвайте document.export за други формати @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Записът записва {_1}, а не {_2}: използвайте file.saveAsTemplate, за да го запишете +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 записва стари файлове .ai, а не шаблони .ait +@msg `groupColors` must be an array `groupColors` трябва да е масив +@msg `preserve` must be an object `preserve` трябва да е обект +@msg `{key}` must be an array `{key}` трябва да е масив @msg Saved recovery data for {title} Запазени данни за възстановяване за {title} @msg Saved to User Defined: {_1} Запазено в Потребителски: {_1} @msg Saved {path} Записано: {path} @@ -4794,13 +4995,18 @@ axis Both И двете @msg Split Into Grid: select paths large enough for the grid Разделяне на мрежа: изберете пътища, достатъчно големи за мрежата @msg Targa files are RGB: colorModel rgb Файловете Targa са RGB: colorModel rgb @msg Text Wrap: select a wrap object Обгръщане на текст: изберете обгръщащ обект -@msg This shortcut file is in a form VectorCraft can't read. Този файл с преки пътища е във формат, който VectorCraft не може да прочете. +@msg This shortcut file is in a form VectorCraft can't read. Този файл с преки пътища е във формат, който VectorCraft не може да прочете. @msg `antiAlias` must be "none", "sharp", "crisp" or "strong" `antiAlias` трябва да е "none", "sharp", "crisp" или "strong" @msg `aspect` must be a number (%) `aspect` трябва да бъде число (%) @msg `at` must be [x, y] `at` трябва да бъде [x, y] @msg `color` must be a colour `color` трябва да бъде цвят @msg `sliders` must be none, oklch or hsl `sliders` трябва да бъде none, oklch или hsl @msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство +@msg the Color Picker is not open Палитрата с цвят не е отворена +@msg the screen color sampler is already open инструментът за вземане на цвят от екрана вече е отворен +@msg this system has no screen color sampler тази система няма инструмент за вземане на цвят от екрана +@msg the screen color sampler did not answer инструментът за вземане на цвят от екрана не отговори +@msg the screen color sampler failed инструментът за вземане на цвят от екрана се провали @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив @@ -4819,6 +5025,19 @@ axis Both И двете @msg `{keep}` is not a side of this axis `{keep}` не е страна на тази ос @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 color `{key}` трябва да бъде цвят във формат #rrggbb +@msg `{key}` must be a #rrggbb color or a layer color name `{key}` трябва да бъде цвят във формат #rrggbb или име на цвят на слой +@msg unknown Live Paint option `{key}` неизвестна опция за динамично оцветяване `{key}` +@msg unknown Shape Builder option `{key}` неизвестна опция за инструмента за създаване на форми `{key}` +@msg `{key}` must be a profile name or null `{key}` трябва да е име на профил или null +@msg `top` and `below` can't both be true `top` и `below` не могат да са true едновременно +@msg `select` must be true or false `select` трябва да е true или false +@msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` и `maxAnchors` трябва да са цели числа +@msg `{key}` must be a number not below 0 `{key}` трябва да е число не по-малко от 0 +@msg `{key}` must be four numbers not below 0: [tl, tr, br, bl] `{key}` трябва да е четири числа не по-малки от 0: [tl, tr, br, bl] +@msg `{key}` must be [x, y, width, height]: four finite numbers, width and height not negative `{key}` трябва да е [x, y, width, height]: четири крайни числа, като width и height не са отрицателни +@msg `{min_key}` is greater than `{max_key}` `{min_key}` е по-голямо от `{max_key}` +@msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` задайте поне едно от `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white триадичен цвят не може да оцвети изображение в нива на сивото с прозрачност: използвайте спот цвят, черно или бяло @msg `{key}` must be a #rrggbb colour `{key}` трябва да бъде цвят във формат #rrggbb @msg `{key}` must be a number `{key}` трябва да бъде число @msg `{key}` must be a number, not {v} `{key}` трябва да бъде число, а не {v} @@ -4875,6 +5094,10 @@ axis Both И двете @msg a gradient needs at least two stops градиентът се нуждае от поне две опорни точки @msg a graphic style named `{to}` already exists графичен стил с име `{to}` вече съществува @msg a key object sits on that point в тази точка има основен обект +@msg `name` is empty `name` е празно +@msg `newName` is empty `newName` е празно +@msg `{name}` is a built-in preset and can't change: save it under another name `{name}` е вградена предварителна настройка и не може да се променя: запазете я под друго име +@msg `{name}` is a built-in preset and stays `{name}` е вградена предварителна настройка и остава @msg a page is missing липсва страница @msg a page out of range страница извън диапазона @msg a page tree kid isn't a reference дете в дървото на страниците не е препратка @@ -4884,6 +5107,9 @@ axis Both И двете @msg a swatch or color group named `{n}` exists образец или цветова група с име `{n}` вече съществува @msg a slice size must be a positive number of points размерът на парчето трябва да бъде положително число в точки @msg a spine keeps at least two points оста запазва поне две точки +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` е null, име на цвят на слой или #rrggbb +@msg the Simplify slider is not open плъзгачът за опростяване не е отворен +@msg the Smooth slider is not open плъзгачът за изглаждане не е отворен @msg a stream runs past the end потокът преминава отвъд края @msg a stream's length is wrong дължината на потока е грешна @msg a stream's length isn't a number дължината на потока не е число @@ -4954,6 +5180,15 @@ axis Both И двете @msg index must be a number or first, previous, next or last index трябва да е число или first, previous, next или last @msg index must be a number or first, previous, next or last, not `{other}` index трябва да е число или first, previous, next или last, а не `{other}` @msg index must be ≥ 0 index трябва да е ≥ 0 +@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): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller: turn on Write pages longer than 200 in at full size in points страницата на работна област {n} е {size}, по-дълга от ограничението на PDF за страница от 14,400 pt (200 in): записва се с UserUnit {unit}, затова приложенията, които пренебрегват UserUnit, я показват толкова пъти по-малка: включете Записване на страници, по-дълги от 200 in, в пълен размер в точки +@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 line {line}: value for `{var}` must be true or false ред {line}: стойността за `{var}` трябва да е true или false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes ред {line}: стойността за `{var}` е по-дълга от {MAX_GRAPH_CSV} байта @msg installing from a path is not available on the web; pass the module as `dataBase64` инсталирането от път не е налично в уеб; предайте модула като `dataBase64` @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) вътрешна грешка в `{cmd}`: {msg} (документът беше оставен в състоянието си отпреди; моля, докладвайте тази грешка) @msg internal error: {msg} (please report this bug) вътрешна грешка: {msg} (моля, докладвайте тази грешка) @@ -4995,6 +5230,10 @@ axis Both И двете @msg no bounds няма граници @msg no brush named `{name}` няма четка с име `{name}` @msg a bristle brush name can have at most {max} characters: `{name}` has {count} най-голяма дължина на името на четка с косъм (знаци): {max}; в `{name}` знаците са {count} +@msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` не е документ на VectorCraft, PDF или PDF-съвместим файл .ai +@msg no saved preset named `{name}` няма запазена предварителна настройка с име `{name}` +@msg no saved preset named `{name}` to rename няма запазена предварителна настройка с име `{name}` за преименуване +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: препратката би била по-голяма от {MAX_BYTES} байта @msg no brush selected няма избрана четка @msg brushes move only within their type четките се преместват само в рамките на своя тип @msg no catalog няма каталог @@ -5079,6 +5318,7 @@ axis Both И двете @msg `link` and `independent` cannot both be true `link` и `independent` не могат и двата да са true @msg `link` places a handle: give `handle` `link` поставя дръжка: задайте `handle` @msg no such spine segment няма такъв сегмент от оста +@msg node {_1} is on a locked artboard възелът {_1} е върху заключена работна област @msg no such subpath няма такъв подпът @msg no such user library няма такава потребителска библиотека @msg no such view няма такъв изглед @@ -5098,8 +5338,10 @@ axis Both И двете @msg not a VectorCraft file: {0} не е файл на VectorCraft: {0} @msg not a VectorCraft shortcut set (missing `overrides`) не е набор от клавишни комбинации на VectorCraft (липсват `overrides`) @msg not a blend не е преливане +@msg not a PICT file не е файл PICT +@msg thumbnail: no page {n} (the file has 1) миниатюра: няма страница {n} (файлът има 1) @msg not a graphic style library (format `{_1}`) не е библиотека със стилове на графики (формат `{_1}`) -@msg not a shortcut set: the text doesn't start with a slash name and an opening brace не е набор от преки пътища: текстът не започва с име със слъш и отваряща скоба +@msg not a shortcut set: the text doesn't start with a slash name and an opening brace не е набор от преки пътища: текстът не започва с име със слъш и отваряща скоба @msg not a stored central record не е съхранен централен запис @msg not a valid plug-in module: {0} не е валиден модул за плъгин: {0} @msg not an EMF or WMF file не е EMF или WMF файл @@ -5139,6 +5381,12 @@ axis Both И двете @msg percent must be above 0 and at most 6400, not {p} percent трябва да е над 0 и най-много 6400, а не {p} @msg pick a colour, gradient or pattern to save as a swatch изберете цвят, градиент или мостра за запазване като образец @msg plane must be left, right or ground plane трябва да е left, right или ground +@msg tolerance must be 0 or more tolerance трябва да е 0 или повече +@msg give `at` or `clear`, not both задайте `at` или `clear`, но не и двете +@msg anchorPoint must be true or false anchorPoint трябва да е true или false +@msg gridlineIntersection must be true or false gridlineIntersection трябва да е true или false +@msg the perspective grid is hidden перспективната мрежа е скрита +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Автоматичното позициониране на равнина е изключено: включете anchorPoint или gridlineIntersection (perspective.widget.options) @msg plug-in ABI: {0} ABI на плъгин: {0} @msg plug-in exceeded its {0} плъгинът надвиши своя {0} @msg plug-in failed: {0} плъгинът се провали: {0} @@ -5155,14 +5403,39 @@ axis Both И двете @msg recovery copy `{file}`: {e} възстановяване на копие `{file}`: {e} @msg resolutions must be between 1 and 2400 ppi резолюциите трябва да бъдат между 1 и 2400 ppi @msg result would exceed the canvas (coordinates out of range) резултатът ще надвиши платното (координатите са извън обхвата) -@msg objects can't be nested more than 32 deep обектите не могат да бъдат вложени на повече от 32 нива -@msg the SVG's elements are nested more than {0} deep елементите на SVG са вложени на повече от {0} нива +@msg objects can't be nested more than 32 deep обектите не могат да бъдат вложени на повече от 32 нива +@msg the SVG's elements are nested more than {0} deep елементите на SVG са вложени на повече от {0} нива @msg scale must be a number from {_1} to {_2}, not {_3} scale трябва да е число от {_1} до {_2}, а не {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale трябва да е число от {_1} до {_2}, а не {s} @msg select (or target) objects whose appearance isn't basic изберете (или насочете към) обекти, чийто изглед не е основен @msg select a Live Paint group изберете група за интерактивно оцветяване (Live Paint) @msg select a blend изберете преход (blend) @msg select a blend or give `id` изберете преливане или задайте неговия `id` +@msg select an Objects on Path group изберете група „Обекти по пътя“ +@msg choose the object to detach with its Select/Move widget изберете обекта за откачане с неговия манипулатор за избиране и преместване +@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects път в съставен път, преливане, плик, повторение или група за преплитане не може да приема обекти +@msg a clipping path can't take objects изрязващ път не може да приема обекти +@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path обекти в преливане, плик, повторение или група за преплитане не могат да се прикачват към път +@msg a clipping path can't be attached to a path изрязващ път не може да се прикачи към път +@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 with a color mask изберете изображение с цветова маска +@msg the color mask's settings are out of range настройките на цветовата маска са извън допустимия диапазон +@msg a CMYK image can't take a color mask изображение в CMYK не може да приеме цветова маска +@msg the mask would hide every pixel маската би скрила всеки пиксел +@msg Recolor completed; {locked} and {hidden} were left unchanged Преоцветяването завърши; {locked} и {hidden} останаха непроменени +@msg Recolor completed; {objects} were left unchanged Преоцветяването завърши; {objects} останаха непроменени +@msg Recolor completed; {objects} was left unchanged Преоцветяването завърши; {objects} остана непроменен +@msg 1 locked object 1 заключен обект +@msg {n} locked objects {n} заключени обекта +@msg 1 hidden object 1 скрит обект +@msg {n} hidden objects {n} скрити обекта @msg select a clip group изберете група за изрязване @msg select a flare изберете взрив @msg select a gradient mesh изберете мрежа на градиент (gradient mesh) @@ -5260,6 +5533,8 @@ axis Both И двете @msg the selection has no URL (or they differ) селекцията няма URL адрес (или те се различават) @msg the selection isn't in perspective селекцията не е в перспектива @msg the spine has no segments оста няма сегменти +@msg panels can't be shown in Presentation Mode панелите не могат да се показват в режим на презентация +@msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) неизвестна предварителна настройка `{name}`: не е вградена или запазена предварителна настройка (вижте imageTrace.presets) @msg the stroke has no weight щрихът няма дебелина @msg the thumbnail image is malformed миниатюрното изображение е дефектно @msg the top object must be a path, compound path or text object to use as a clipping mask горният обект трябва да бъде път, съставен път или текстов обект, за да се използва като маска за изрязване @@ -5270,6 +5545,7 @@ axis Both И двете @msg this file's PostScript couldn't be read ({why}): {what} PostScript файлът не можа да бъде прочетен ({why}): {what} @msg this format holds one artboard: export several as PDF or with document.exportForScreens този формат съдържа една работна област: експортирайте няколко като PDF или с document.exportForScreens @msg this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that това е DWG чертеж, който не може да бъде прочетен: запазете го от CAD приложението като ASCII DXF и го отворете +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG това е файл PostScript (.ai, запазен в по-стар формат или без съвместимост с PDF, или файл EPS), който все още не може да се отвори: запазете го като PDF, PDF-съвместим .ai или SVG @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS това е PostScript файл (.ai, запазен в по-стар формат или без съвместимост с PDF, или EPS файл), а не PDF: Файл › Отваряне и Файл › Вмъкване го четат като EPS @msg this is not a PostScript file това не е PostScript файл @msg tool shortcuts must be a single key (optionally with Shift) клавишните комбинации за инструменти трябва да са един клавиш (по избор със Shift) @@ -5311,6 +5587,9 @@ axis Both И двете @msg unknown workspace (one of {_1}) непознато работно пространство (едно от {_1}) @msg unsupported: {0} не се поддържа: {0} @msg variables are locked променливите са заключени +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} повече от {MAX_CSV_ROWS} набора от данни: Импортиране на набори от данни чете най-много {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} повече от {MAX_CSV_COLS} променливи: Импортиране на набори от данни чете най-много {MAX_CSV_COLS} +@msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` и `options.{key}: {inner}` си противоречат: задайте опцията веднъж @msg variables that aren't text were left out: {kinds} променливите, които не са текстови, бяха пропуснати: {kinds} @msg a new document won't read these variables back with their kind: {names} нов документ няма да прочете тези променливи обратно с техния вид: {names} @msg a new document refuses this file because of these variables: {names} нов документ отказва този файл заради тези променливи: {names} @@ -5319,6 +5598,121 @@ axis Both И двете @msg width and height are at least 1 pixel ширината и височината са най-малко 1 пиксел @msg workspace name can't be empty името на работното пространство не може да бъде празно @msg x and y must be finite x и y трябва да са крайни числа +@msg {_1} is an exporter (File › Export › Export As…) {_1} е формат за експортиране (Файл › Експортиране › Експортиране като…) +@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` е {size} байта (ограничение {MAX_DOCUMENT_DATA}) +@msg a mask that covers several layers comes in as a clipping group in each layer it covers маска, която покрива няколко слоя, се импортира като група за изрязване във всеки покрит слой +@msg a graph's records don't end where they should: its art was read as it is записите на диаграма не завършват където трябва: графиката ѝ беше прочетена такава, каквато е +@msg `{w}` takes no operands `{w}` не приема операнди +@msg a wraparound group is inside a compound path обгръщаща група е в съставен път +@msg it ends inside a multi-layer mask завършва вътре в многослойна маска +@msg a multi-layer mask's operators are out of order операторите на многослойна маска не са в правилния ред +@msg a multi-layer mask needs one clipping path многослойната маска изисква един изрязващ път +@msg a group crosses a multi-layer mask група пресича многослойна маска +@msg graphs come in as plain art, without their data or settings диаграмите се импортират като обикновена графика, без данните и настройките си +@msg the active document changed while the question was open; nothing was deleted активният документ се промени, докато въпросът беше отворен; нищо не беше изтрито +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Връзката е в символ, дизайн на диаграма, мостра или маска за непрозрачност и няма място върху платното +@msg source must be the id of a Shaper Group's original shape source трябва да е идентификаторът на оригинална форма от група от форми +@msg group must be the id of a Shaper Group group трябва да е идентификаторът на група от форми +@msg the shape is not an editable original shape of that Shaper Group формата не е редактируема оригинална форма от тази група от форми +@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 the PCX file is cut short файлът PCX е прекъснат +@msg the PCX file's header is damaged заглавката на файла PCX е повредена +@msg PCX files with {bits}-bit pixels in {planes} planes can't be read файлове PCX с {bits}-битови пиксели в {planes} равнини не могат да се четат +@msg the Pixar file is cut short файлът Pixar е прекъснат +@msg the Pixar file's header is damaged заглавката на файла Pixar е повредена +@msg the Pixar file's image data is damaged данните за изображението във файла Pixar са повредени +@msg the JPEG 2000 file can't be read файлът JPEG 2000 не може да се прочете +@msg the JPEG 2000 file has an unsupported color space or JPX content файлът JPEG 2000 има неподдържано цветово пространство или съдържание JPX +@msg the HEIC or HEIF file can't be read файлът HEIC или HEIF не може да се прочете +@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 JPEG XL file is cut short файлът JPEG XL е прекъснат +@msg the JPEG XL container is too large to read контейнерът JPEG XL е твърде голям за четене +@msg CMYK JPEG XL images can't be read изображенията JPEG XL в CMYK не могат да се четат +@msg the JPEG XL file can't be read: {e} файлът JPEG XL не може да се прочете: {e} +@msg Extrude & Bevel Избутване и фасетка +@msg Revolve Завъртане около ос +@msg Inflate Издуване +@msg Rotate Завъртане +@msg Extrude & Bevel (Classic) Избутване и фасетка (класически) +@msg Revolve (Classic) Завъртане около ос (класическо) +@msg Rotate (Classic) Ротация (класическа) +@msg This effect Този ефект +@msg clipping paths изрязващи пътища +@msg other objects други обекти +@msg {label} requires a group holding a shape with at least two anchors {label} изисква група, съдържаща форма с поне две опорни точки +@msg Revolve requires a group holding a shape with at least two anchors Завъртането около ос изисква група, съдържаща форма с поне две опорни точки +@msg Revolve requires a shape with at least two anchors Завъртането около ос изисква форма с поне две опорни точки +@msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} върху група изисква пътища, съставни пътища, текст, групи, групи за изрязване, преливания и инстанции на символи: първо освободете или разширете {what}. +@msg {label} on a group takes at most {MAX_MEMBERS} objects {label} върху група приема най-много {MAX_MEMBERS} обекта +@msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke 3D ефект върху група или слой се прилага към самата група, а не към нейното запълване или щрих +@msg a 3D effect on a group's fill or stroke draws nothing 3D ефект върху запълването или щриха на група не рисува нищо +@msg a 3D effect on a group's fill or stroke draws nothing to export 3D ефект върху запълването или щриха на група не рисува нищо за експортиране +@msg The 3D object is too complex to export 3D обектът е твърде сложен за експортиране +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) обектът няма 3D ефект (Избутване и фасетка, Завъртане около ос, Издуване или Завъртане) +@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` трябва да е обект, съдържащ само `mode`, със стойност shaded или wireframe +@msg its 3D effect builds no solid неговият 3D ефект не изгражда тяло +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel трябва да е none или едно от {_1}, или custom с {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom изисква {BEVEL_PROFILE}, точките на фасетката +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} трябва да е низ +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} трябва да е от 2 до {most} точки [x, y], всяка стойност между 0 и 1, от [0, 0] (ръбът на капачката) до [1, 1] (страничната стена) +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} не може да изгради тела от тази графика: нейните инстанции на символи, преливания и групи за изрязване съдържат твърде много обекти +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} не може да изгради тяло от инстанцията на символа "{symbol}": графиката на символа не е налична +@msg {_1}: the clipping path is too complex to cut the art with {_1}: изрязващият път е твърде сложен, за да се изреже графиката с него +@msg {_1} takes at most {MAX_MEMBERS} objects {_1} приема най-много {MAX_MEMBERS} обекта +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} не може да изгради тела от графика, вложена на повече от {MAX_DEPTH} нива +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Боята на завъртането около ос е твърде сложна за тази повърхност; намалете Сегменти или опростете градиента +@msg Revolve edge must be left or right Завъртане около ос: edge трябва да е left или right +@msg Revolve cap must be a boolean Завъртане около ос: cap трябва да е булева стойност +@msg the revolved object has no fill or stroke завъртяният около ос обект няма запълване или щрих +@msg lightColor must be an opaque RGB color in #rrggbb form lightColor трябва да е непрозрачен цвят RGB във формат #rrggbb +@msg lights must contain one to ten lights lights трябва да съдържа от един до десет източника на светлина +@msg each light must be an object всеки източник на светлина трябва да е обект +@msg unknown light setting: use color, intensity, rotation, height, softness or behind неизвестна настройка на светлината: използвайте color, intensity, rotation, height, softness или behind +@msg light {key} must be a number from {min} to {max} {key} на светлината трябва да е число от {min} до {max} +@msg light color must use opaque #rrggbb светлина: color трябва да е непрозрачен #rrggbb +@msg light behind must be true or false behind на светлината трябва да е true или false +@msg shadow must be true or false shadow трябва да е true или false +@msg shadowPosition must be behind or below shadowPosition трябва да е behind или below +@msg {key} must be a number from {min} to {max} {key} трябва да е число от {min} до {max} +@msg each of `{GRAPHICS}` must be an object всеки елемент от `{GRAPHICS}` трябва да е обект +@msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` елементите на `{GRAPHICS}` приемат symbol, face, x, y, scale и rotation, а не `{k}` +@msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol всеки елемент от `{GRAPHICS}` изисква `symbol`, името на символ +@msg `{GRAPHICS}` face must be front or back face в `{GRAPHICS}` трябва да е front или back +@msg `{GRAPHICS}` face must be front, back or side face в `{GRAPHICS}` трябва да е front, back или side +@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` трябва да е число от {lo} до {hi} +@msg `{GRAPHICS}` must be an array `{GRAPHICS}` трябва да е масив +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графиките се нанасят върху типовете обекти Равнина, Избутване, Завъртане около ос и Издуване +@msg Revolve maps graphics onto its side: map them onto the front Завъртането около ос нанася графиките върху страната си: нанесете ги върху предната страна +@msg Inflate maps graphics onto its front and back, not onto a side Издуването нанася графиките върху предната и задната си страна, а не върху странична +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on обект {_1}: задната страна на издуването приема графики, когато И двете страни и Капачка са включени +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графиките са твърде сложни за тази повърхност: опростете графиката на символите или намалете Сегменти +@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приема най-много {MAX_GRAPHICS} графики +@msg A plane has one face: map its graphics onto the front Равнината има една страна: нанесете графиките ѝ върху предната страна +@msg The graphics are too complex: simplify the symbols' art Графиките са твърде сложни: опростете графиката на символите +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Графиката на нанесен елемент може да е вложена най-много на {MAX_LEVELS} нива: опростете графиката на символа +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Графиката на нанесен елемент може да влага символи най-много на {MAX_NESTING} нива: опростете графиката на символа +@msg A graphic's art holds too many objects: simplify the symbol's art Графиката на нанесен елемент съдържа твърде много обекти: опростете графиката на символа +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Нанесен елемент рисува най-много {MAX_PIECES} запълвания и щрихи: опростете графиката на символа +@msg `surface` must be one of {_1} `surface` трябва да е едно от {_1} +@msg {label} draws the source art for this object instead of its 3D surface {label} рисува изходната графика за този обект вместо 3D повърхността му +@msg {label} draws no faces for this object {label} не рисува страни за този обект +@msg the wireframe has more than {MAX_WIRE_EDGES} edges телената рамка има повече от {MAX_WIRE_EDGES} ръба +@msg the params must be an object, not {got} параметрите трябва да са обект, а не {got} +@msg unknown parameter `{path}`; the object takes no keys неизвестен параметър `{path}`; обектът не приема ключове +@msg unknown parameter `{path}`; it takes: {keys} неизвестен параметър `{path}`; приема: {keys} +@msg missing `{path}` липсва `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` трябва да е {expected}, а не {got} +@msg `{path}` is nested too deeply `{path}` е вложен твърде дълбоко +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: не е изображение PNG, JPEG, WebP, TIFF или BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ изображението е {iw} × {ih} пиксела, а работната област при тази ширина е {rw} × {rh} пиксела: пропорциите им се различават +@msg `threshold` must be a number from 0 to 1 `threshold` трябва да е число от 0 до 1 +@msg background {v}: a color such as "#808080" background {v}: цвят, например "#808080" +@msg comparing with an image file isn't available in the browser сравняването с файл на изображение не е налично в браузъра +@msg columns {first} and {column} both name the variable `{name}` колоните {first} и {column} именуват една и съща променлива `{name}` +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for нищо от набора от данни {name} не беше приложено: нито един обект не е свързан с променлива, за която наборът има стойност +@msg no bound object reports a value (locked objects and embedded images report none) нито един свързан обект не връща стойност (заключените обекти и вградените изображения не връщат) @msg {C}: no effect at index {from} {C}: няма ефект на индекс {from} @msg {_1} failed: {e} {_1} неуспешно: {e} @msg {_1} files can be opened but not written (see document.formats) {_1} файловете могат да се отварят, но не и да се записват (вижте document.formats) @@ -6302,11 +6696,11 @@ theme Appearance Външен вид Drawer menu Меню на чекмеджето Toolbar: Show Controls Лента с инструменти: Показване на контроли @msg control must be fillStroke, coloring, drawMode or screenMode control трябва да бъде fillStroke, coloring, drawMode или screenMode -@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode неизвестен контрол `{name}`: fillStroke, coloring, drawMode или screenMode -@msg give a fraction `t` from 0 to 1 въведете дробно число `t` от 0 до 1 -@msg give the path `id` въведете `id` на пътя -@msg invalid stroke widths невалидни ширини на щриха -@msg object has no weighted stroke обектът няма претеглен щрих +@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode неизвестен контрол `{name}`: fillStroke, coloring, drawMode или screenMode +@msg give a fraction `t` from 0 to 1 въведете дробно число `t` от 0 до 1 +@msg give the path `id` въведете `id` на пътя +@msg invalid stroke widths невалидни ширини на щриха +@msg object has no weighted stroke обектът няма претеглен щрих Single Corner Radius Радиус на единичен ъгъл Top Left: Горно ляво: Top Right: Горно дясно: @@ -6462,6 +6856,8 @@ theme Appearance Външен вид Save Variable Library… Запазване на библиотека с променливи… @msg a variable library holds text variables, and the document has none библиотеката с променливи съдържа текстови променливи, а документът няма такива @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` променливата `{name}` не може да бъде запазена в библиотека с променливи: преименувайте я така, че да започва с буква или `_`, без интервали и символи, различни от `-`, `_` и `.` +@msg {k} has control characters {k} съдържа управляващи знаци +@msg {k} has control characters or line breaks {k} съдържа управляващи знаци или нови редове @msg data set `{name}` holds a control character, which a variable library can't hold наборът от данни `{name}` съдържа управляващ знак, който библиотеката с променливи не може да съдържа @msg data set `{name}` starts or ends with white space, which a variable library can't hold наборът от данни `{name}` започва или завършва с интервал, който библиотеката с променливи не може да съдържа Make Graph Dynamic Динамична диаграма @@ -6516,6 +6912,7 @@ theme Appearance Външен вид # User Interface › Color Scheme Color Scheme Цветова схема Modern Модерна +@msg `{key}` must be an array of these names: {_1} `{key}` трябва да е масив от тези имена: {_1} # Symbol Options › Export Type Export Type: Тип на експортиране: @@ -6559,6 +6956,33 @@ theme Appearance Външен вид @msg only http, https and mailto URLs open in the browser, not “{url}” в браузъра се отварят само URL адреси с http, https и mailto, не „{url}“ @msg {id} opens another app: only the person at the keyboard can run it {id} отваря друга програма: само човекът пред клавиатурата може да изпълни командата @msg “{name}” is not a file „{name}“ не е файл +@msg a mask has more than one art block маската има повече от един блок графика +@msg mask art ends outside a mask dictionary графиката на маската завършва извън речник на маска +@msg cancelled; nothing was changed отменено; нищо не беше променено +@msg a linked image can't become a gradient mesh: embed it first свързано изображение не може да стане мрежа на градиент: първо го вградете +@msg the image has no usable size or position изображението няма използваем размер или позиция +@msg the image's pixels can't be read пикселите на изображението не могат да се прочетат +@msg Persistent libraries not found: {files} Не са намерени постоянни библиотеки: {files} +@msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` не е панел на библиотека (вижте window.swatchLibrary) +@msg library panel `{given}` isn't open панелът на библиотека `{given}` не е отворен +@msg too many changed shortcuts твърде много променени клавишни комбинации +@msg library panel `{given}` isn't missing its library на панела на библиотека `{given}` не липсва библиотеката му +@msg too many library panels were opened in this session в тази сесия бяха отворени твърде много панели на библиотеки +@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Изображението е {_1} × {_2} пиксела, повече от {LARGE_TRACE_SIDE} по една страна: трасира се, но по-бавно. Предварителна настройка с по-ниска точност или по-малко копие на изображението се трасира по-бързо. +@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Изображението беше трасирано при {_1} × {_2} пиксела, намалено от {_3} × {_4} (най-много {_5} мегапиксела). +@msg byColor must be true or false byColor трябва да е true или false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor не може да разделя групи от Автоматично групиране: трасирайте без Автоматично групиране +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor не може да прегрупира трасиране с динамичен ефект Търсач на пътища: разширете без byColor +@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 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"` +@msg `colorGroup` needs `mode: "color"` `colorGroup` изисква `mode: "color"` +@msg no color group `{name}` in the document (see swatch.list) в документа няма цветова група `{name}` (вижте swatch.list) +@msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. Режимът „Плоско лого“ трасира изображението при {_1} × {_2} пиксела, осреднено от {_3} × {_4}. Enable Guides for 9-Slice Scaling Включване на водачи за 9-slice мащабиране Persistent Постоянна Locate Library… Намиране на библиотека… @@ -6600,10 +7024,269 @@ theme Appearance Външен вид @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest библиотеката с променливи на файла беше прочетена частично (пропуснати записи: {_1}): панелът „Променливи“ показва останалите @msg the file's variable library couldn't be read: the Variables panel doesn't list it библиотеката с променливи на файла не можа да бъде прочетена: панелът „Променливи“ не я показва @msg a variable of unknown kind can't be bound to objects променлива от неизвестен вид не може да бъде свързана с обекти +@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` трябва да е grayscale, rgb, hsb, cmyk или websafe +@msg `view` must be wheel or box `view` трябва да е wheel или box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` трябва да е hue, saturation, brightness, red, green или blue # Select by Color (select.color) Select by Color Избиране по цвят Move Anchor Point Преместване на опорна точка @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} запазва 1 от {n} работни области на документа: файлът се отваря отново с един. Включете „Запазване на възможностите за редактиране“, за да запазите всички. +@msg `spread` must be pad, repeat or reflect `spread` трябва да е pad, repeat или reflect +@msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` трябва да е цяло число от 1 до {MAX_REPEATS} +@msg `spread` applies to linear, radial, conic and diamond gradients `spread` се прилага към линейни, радиални, конични и ромбовидни градиенти +@msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} завърши, но междувременно документът или приставката се промени: изпълнете отново +@msg Running “{name}”… Изпълнява се „{name}“… +@msg a live effect runs while the document is drawn, so it can't be `heavy` динамичният ефект се изпълнява, докато документът се рисува, затова не може да е `heavy` +@msg an exporter always gets an export's budget: leave `budget` out форматът за експортиране винаги получава бюджета на експортиране: пропуснете `budget` +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ иска голям бюджет (всяко изпълнение до {minutes} минути и {times} пъти обичайния брой инструкции): човек трябва да го одобри в настолното приложение или подайте `allowHeavy: true` в сесия, стартирана с --allow-plugin-grants +@msg `name` must be 1-64 printable characters `name` трябва да е от 1 до 64 видими знака +@msg `version`, `description` or `author` is too long `version`, `description` или `author` е твърде дълго +@msg `warnings` must be a list of strings `warnings` трябва да е списък от низове +@msg `{k}` must be one of {_1} `{k}` трябва да е едно от {_1} +@msg `{k}` must be {what} `{k}` трябва да е {what} +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` форматът за експортиране обявява от 1 до {MAX_EXTENSIONS} `extensions` +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` най-много {MAX_UNGROUPED} параметъра извън групи: задайте `group` на останалите +@msg can't encode the input входните данни не могат да се кодират +@msg expected {{"dataBase64": "…"}} очаква се {{"dataBase64": "…"}} +@msg expected {{"objects": [...]}} очаква се {{"objects": [...]}} +@msg export `{name}`: {e} експортиране `{name}`: {e} +@msg extension {e} is listed twice разширението {e} е изброено два пъти +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot разширение {e}: използвайте от 1 до 16 малки букви и цифри, без точката +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - невалиден id {_1}: използвайте от 1 до 64 знака от A-Z a-z 0-9 . _ - +@msg invalid parameter name {k} невалидно име на параметър {k} +@msg manifest is not UTF-8 манифестът не е в UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) манифестът е твърде дълъг (ограничение {MAX_MANIFEST_BYTES} байта) +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) манифестът е {_1} байта (ограничение {MAX_MANIFEST_BYTES}) +@msg module is {_1} bytes (limit {_2}) модулът е {_1} байта (ограничение {_2}) +@msg needs approval: it asks for {0}, which the user grants when installing it on its own изисква одобрение: иска {0}, което потребителят разрешава, когато я инсталира самостоятелно +@msg not JSON: {e} не е JSON: {e} +@msg not a WebAssembly binary (missing \\0asm header) не е двоичен файл WebAssembly (липсва заглавка \\0asm) +@msg parameter `{k}`: {what} параметър `{k}`: {what} +@msg parameter `{name}`: {what} параметър `{name}`: {what} +@msg plug-in parameters must be a JSON object параметрите на приставката трябва да са обект JSON +@msg the module must export its linear memory as `memory` модулът трябва да експортира линейната си памет като `memory` +@msg the objects to change are no longer in the document обектите за промяна вече не са в документа +@msg the runtime panicked средата за изпълнение аварира +@msg unexpected host trap неочакван прихванат срив в приложението +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version върна {v}; това приложение реализира версия {ABI_VERSION} +@msg vc_alloc returned 0 (out of memory) vc_alloc върна 0 (няма достатъчно памет) +@msg vc_alloc returned a block outside memory vc_alloc върна блок извън паметта +@msg vc_run returned error code {packed} vc_run върна код на грешка {packed} +@msg {_1} is not a file {_1} не е файл +@msg {_1} is {_2} bytes (limit {_3}) {_1} е {_2} байта (ограничение {_3}) +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} обекта (ограничение {MAX_OBJECTS}) +@msg {at}: {msg} {at}: {msg} +@msg {what} points outside memory {what} сочи извън паметта +@msg `angle` must be a number `angle` трябва да е число +@msg `aspect` must be from 0.01 to 100 `aspect` трябва да е от 0.01 до 100 +@msg `cap` must be "butt", "round" or "square" `cap` трябва да е "butt", "round" или "square" +@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` трябва да е "nonzero" или "evenodd" +@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` трябва да е адрес https:// с най-много {MAX_HELP_URL} байта +@msg `help` must be 1-{MAX_HELP} printable characters `help` трябва да е от 1 до {MAX_HELP} видими знака +@msg `id` must be an effect id of 1-{MAX_EFFECT_ID} bytes `id` трябва да е идентификатор на ефект от 1 до {MAX_EFFECT_ID} байта +@msg `id` must be the id of an input object `id` трябва да е идентификаторът на входен обект +@msg `join` must be "miter", "round" or "bevel" `join` трябва да е "miter", "round" или "bevel" +@msg `label` and `group` must be 1-{MAX_LABEL} printable characters `label` и `group` трябва да са от 1 до {MAX_LABEL} видими знака +@msg `maxLength` must be 1-{MAX_TEXT}, and the default no longer `maxLength` трябва да е от 1 до {MAX_TEXT}, а стойността по подразбиране да не е по-дълга +@msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` и `maxItems` трябва да са от 0 до {MAX_LIST}, `maxItems` поне 1, а стойността по подразбиране да има толкова елемента +@msg `name` must be a string `name` трябва да е низ +@msg `opacity` must be a number `opacity` трябва да е число +@msg `type` must be "path" or "compound" `type` трябва да е "path" или "compound" +@msg `unit` must be 1-{MAX_UNIT} printable characters `unit` трябва да е от 1 до {MAX_UNIT} видими знака +@msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` изброява от 1 до {MAX_CONDITION_VALUES} стойности за `{other}` +@msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` посочва `{other}`, който не е параметър, обявен преди този +@msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` посочва най-много {MAX_CONDITIONS} параметъра +@msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` приема стойностите на `{other}`, които са на отметка или на избор +@msg `visible` must be true or false `visible` трябва да е true или false +@msg `{key}` must be a number from {_1} to {_2} `{key}` трябва да е число от {_1} до {_2} +@msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` трябва да е масив с най-много {MAX_ITEMS} елемента +@msg a color default must be a color object or a hex string such as "#3a7bd5" цветовата стойност по подразбиране трябва да е обект на цвят или шестнадесетичен низ, например "#3a7bd5" +@msg a color object or a hex string such as "#3a7bd5" обект на цвят или шестнадесетичен низ, например "#3a7bd5" +@msg a freeform gradient holds at most {MAX_ITEMS} points and lines свободният градиент съдържа най-много {MAX_ITEMS} точки и линии +@msg a freeform gradient line names a point it doesn't have линия на свободен градиент посочва точка, която той няма +@msg a gradient needs 1-{MAX_ITEMS} stops градиентът изисква от 1 до {MAX_ITEMS} спирки +@msg a list of numbers списък от числа +@msg a list of {min_items} to {max_items} numbers списък от {min_items} до {max_items} числа +@msg a new object needs a `path` нов обект изисква `path` +@msg a number число +@msg a painted live effect returns only `objects` рисуващ динамичен ефект връща само `objects` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` частта на рисуващ динамичен ефект има само `path`, `fillRule`, `fills` и `strokes` +@msg a read-only object was left out обект само за четене беше пропуснат +@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given обект само за четене беше пропуснат: върнете го само като {{"id": …}} или такъв, какъвто е зададен +@msg a string низ +@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` щрихът има само `paint`, `width`, `join`, `cap` и `miterLimit` +@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} щрихът трябва да е {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} +@msg an effect must be {{"id", "params"?, "visible"?}} ефектът трябва да е {{"id", "params"?, "visible"?}} +@msg an effect on a fill returns only `fills` ефект върху запълване връща само `fills` +@msg an effect on a stroke returns only `strokes` ефект върху щрих връща само `strokes` +@msg an object must be a JSON object обектът трябва да е обект JSON +@msg bad range невалиден диапазон +@msg choices must be 1-64 non-empty, printable strings изборите трябва да са от 1 до 64 непразни низа от видими знаци +@msg coordinate out of range (limit ±{MAX_COORD} pt) координатата е извън диапазона (ограничение ±{MAX_COORD} pt) +@msg default is not one of the options стойността по подразбиране не е от опциите +@msg each piece needs a `path` всяка част изисква `path` +@msg is listed twice е изброено два пъти +@msg pattern transform out of range трансформацията на мострата е извън диапазона +@msg read-only field '{field}' changed полето само за четене '{field}' е променено +@msg stops must be in order of `offset` спирките трябва да са подредени по `offset` +@msg the document has no pattern {pattern} документът няма мостра {pattern} +@msg the document has no swatch {n} документът няма образец {n} +@msg `plates` requires a stop linked to a spot swatch `plates` изисква спирка, свързана със спот образец +@msg the output изходът +@msg the path has no anchor points пътят няма опорни точки +@msg too many anchor points (limit {MAX_ANCHORS}) твърде много опорни точки (ограничение {MAX_ANCHORS}) +@msg true or false true или false +@msg a number >= {_1} число >= {_1} +@msg a number > {_1} число > {_1} +@msg a number <= {_1} число <= {_1} +@msg a number < {_1} число < {_1} +@msg a number {_1} to {_2} число от {_1} до {_2} +@msg a number >= {_1} and < {_2} число >= {_1} и < {_2} +@msg a number > {_1} and <= {_2} число > {_1} и <= {_2} +@msg a number > {_1} and < {_2} число > {_1} и < {_2} +@msg a number ({_1}) число ({_1}) +@msg a number >= {_1} ({_2}) число >= {_1} ({_2}) +@msg a number > {_1} ({_2}) число > {_1} ({_2}) +@msg a number <= {_1} ({_2}) число <= {_1} ({_2}) +@msg a number < {_1} ({_2}) число < {_1} ({_2}) +@msg a number {_1} to {_2} ({_3}) число от {_1} до {_2} ({_3}) +@msg a number >= {_1} and < {_2} ({_3}) число >= {_1} и < {_2} ({_3}) +@msg a number > {_1} and <= {_2} ({_3}) число > {_1} и <= {_2} ({_3}) +@msg a number > {_1} and < {_2} ({_3}) число > {_1} и < {_2} ({_3}) +@msg an integer цяло число +@msg an integer >= {_1} цяло число >= {_1} +@msg an integer <= {_1} цяло число <= {_1} +@msg an integer {_1} to {_2} цяло число от {_1} до {_2} +@msg one of {_1} едно от {_1} +@msg an object id (a non-negative integer) идентификатор на обект (неотрицателно цяло число) +@msg a list of object ids списък от идентификатори на обекти +@msg a color (a string, [r, g, b] or an object) цвят (низ, [r, g, b] или обект) +@msg [x, y] (two numbers) [x, y] (две числа) +@msg an object обект +@msg a list списък +@msg unknown key `{k}`; the keys here are {_1} неизвестен ключ `{k}`; ключовете тук са {_1} +@msg {_1} is listed twice {_1} е изброен два пъти +@msg {_1} is not the id of an input object {_1} не е идентификаторът на входен обект +@msg {_1} is read-only {_1} е само за четене +@msg {what} must be from {lo} to {hi} {what} трябва да е от {lo} до {hi} +@msg a color component цветови компонент +@msg a plate печатна плака +@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`, след като потребителят се съгласи +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ изброява `{id}` в `commandAllowlist`, а приставка не може да я извиква +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: не е изброена в `commandAllowlist` на манифеста +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: идентификаторът или аргументите са извън паметта на модула +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: идентификаторът или аргументите не са в UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: аргументите не са обект JSON +@msg only a filter with the usual budget declares `commandAllowlist` само филтър с обичайния бюджет обявява `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) извиквания на команди ({MAX_CALLS} извиквания и {MAX_CALL_BYTES} байта на изпълнение) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) размер на извикване на команда (vc_call `{shown}`: {len} байта, ограничение {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` най-много {MAX_ALLOWED_COMMANDS} команди в `commandAllowlist` +@msg a plug-in may not call this command приставка не може да извиква тази команда +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` изисква разрешението `commands`, а `commands` изисква `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` посочва `{shown}`, който не е идентификатор на команда или е изброен два пъти +@msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} разрешението `{permission}` изисква ниво {PROGRESS_API} на API за приставки: задайте `api` {PROGRESS_API} +@msg the module imports `env.{name}` with another type than the host's: it is {signature} модулът импортира `env.{name}` с тип, различен от този на приложението: той е {signature} +@msg the module imports `env.{name}`, which a plug-in may use only at plug-in API level {PROGRESS_API} (`api` {PROGRESS_API}) and with the permission `{permission}` модулът импортира `env.{name}`, която приставка може да използва само при ниво {PROGRESS_API} на API за приставки (`api` {PROGRESS_API}) и с разрешението `{permission}` +@msg the module imports `{from}.{name}`, which the host doesn't offer: a plug-in may import only the `env.vc_*` functions that docs/plugins.md lists (plug-in API level 2), and no WASI, files or network модулът импортира `{from}.{name}`, която приложението не предлага: приставка може да импортира само функциите `env.vc_*`, изброени в docs/plugins.md (ниво 2 на API за приставки), и никакви WASI, файлове или мрежа +@msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` е {_1}; това приложение реализира нива от 1 до {API_LEVEL} на API за приставки +@msg `paintOutput` may only be true `paintOutput` може да е само true +@msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` е само за динамичен ефект (`kind` "effect") при `api` 2 +@msg `grant` must be a list of permission names `grant` трябва да е списък от имена на разрешения +@msg `grant` names an unknown permission `{shown}` `grant` посочва неизвестно разрешение `{shown}` +@msg a plug-in of kind `{_1}` needs the permission `{_2}` приставка от вид `{_1}` изисква разрешението `{_2}` +@msg at most {MAX_PERMISSIONS} `permissions` най-много {MAX_PERMISSIONS} `permissions` +@msg permission `{shown}` doesn't apply to a plug-in of kind `{_1}` разрешението `{shown}` не се отнася за приставка от вид `{_1}` +@msg permission `{shown}` is listed twice разрешението `{shown}` е изброено два пъти +@msg only a filter declares `inputs` само филтър обявява `inputs` +@msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` посочва неизвестен вид обект `{shown}`: използвайте type, image или symbolInstance +@msg `inputs` lists `{shown}` twice `inputs` изброява `{shown}` два пъти +@msg `inputs` needs `api` 2 or later `inputs` изисква `api` 2 или по-ново +@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 +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` и `allowHeavy` действат само в сесия, стартирана с --allow-plugin-grants: одобрете приставката в настолното приложение +@msg Only the person at the keyboard can approve installing a plug-in Само човекът на клавиатурата може да одобри инсталирането на приставка +@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed на „{name}“ не е дадено `{p}`, което е нужно за изхода ѝ: нищо не беше променено +@msg a heavy filter runs in the background, so it can't declare `commands` тежък филтър се изпълнява във фонов режим, затова не може да обявява `commands` +@msg at most {MAX_COMMANDS} `commands` най-много {MAX_COMMANDS} `commands` +@msg command {name} is declared twice командата {name} е обявена два пъти +@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`: нищо не беше инсталирано +@msg select one object изберете един обект +@msg Global Edit is off Глобалното редактиране е изключено +@msg only an object of the Global Edit other than the one it started from can be left out може да се пропусне само обект от глобалното редактиране, различен от този, от който то е започнало +@msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} +@msg `{_1}` has no symbols to place `{_1}` няма символи за поставяне +@msg missing `library` (see symbol.libraries) липсва `library` (вижте symbol.libraries) +@msg no symbol `{n}` няма символ `{n}` +@msg no symbol `{n}` in `{_1}` няма символ `{n}` в `{_1}` +@msg no symbol library `{key}` (see symbol.libraries) няма библиотека със символи `{key}` (вижте symbol.libraries) +@msg the document has no symbols to save документът няма символи за запазване +@msg `{_1}` has no brushes to apply `{_1}` няма четки за прилагане +@msg missing `library` (see brush.libraries) липсва `library` (вижте brush.libraries) +@msg no brush `{n}` няма четка `{n}` +@msg no brush `{n}` in `{_1}` няма четка `{n}` в `{_1}` +@msg no brush library `{key}` (see brush.libraries) няма библиотека с четки `{key}` (вижте brush.libraries) +@msg the document has no brushes to save документът няма четки за запазване +@msg a {width}×{height} screenshot's byte count overflows броят байтове на екранна снимка {width}×{height} препълва +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot {what} на прозореца ({points} точки × {scale} DPI) не може да определи размера на екранна снимка +@msg {label} must be a number {label} трябва да е число +@msg {label} must be a number of at least 0.1 {label} трябва да е число не по-малко от 0.1 +@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 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}` +@msg {_1} is an importer (File › Open With) {_1} е формат за импортиране (Файл › Отваряне с) +@msg missing `importer` (see document.formats) липсва `importer` (вижте document.formats) +@msg `importer` must be a plug-in format id (see document.formats) `importer` трябва да е идентификатор на формат на приставка (вижте document.formats) +@msg “{shown}” opens {_1} files, not `{_2}` „{shown}“ отваря файлове {_1}, а не `{_2}` +@msg `{_1}` is a plug-in of kind `{_2}`, not an importer `{_1}` е приставка от вид `{_2}`, а не формат за импортиране +@msg `{_1}` is a plug-in of kind `{_2}`, not an exporter `{_1}` е приставка от вид `{_2}`, а не формат за експортиране +@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` е формат за импортиране: отворете файл с document.open {{"importer": "{_2}"}} +@msg `{_1}` is an exporter: export with document.export {{"format": "{_2}"}} `{_1}` е формат за експортиране: експортирайте с document.export {{"format": "{_2}"}} +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` е динамичен ефект: приложете го с effect.apply {{"effect": "{_2}"}} +@msg the importer returned no objects форматът за импортиране не върна обекти +@msg an importer returns `objects` and `warnings`, not `{key}` форматът за импортиране връща `objects` и `warnings`, а не `{key}` +@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads файлът е по-голям от {MAX_INPUT_BYTES} байта, които чете форматът за импортиране +@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` форматът за импортиране обявява от 1 до {MAX_EXTENSIONS} `extensions` +@msg only an exporter or an importer declares `extensions` само формат за експортиране или за импортиране обявява `extensions` +@msg an importer always gets an import's budget: leave `budget` out форматът за импортиране винаги получава бюджета на импортиране: пропуснете `budget` +@msg only paths and compound paths can be aligned to the pixel grid само пътища и съставни пътища могат да се подравняват към пикселната мрежа +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` трябва да са номера на редове в конзолата, като first е преди last +@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} отложени ефекта на приставки. Ефект › Обновяване на отложените ефекти ги изпълнява. +@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} +@msgplural Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`|Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}` Зареден е „{name}“: {n} стъпка има неизвестна команда и беше запазена: „{action}“, стъпка {step}, `{command}`|Зареден е „{name}“: {n} стъпки имат неизвестни команди и бяха запазени; първата: „{action}“, стъпка {step}, `{command}` Chalk & Charcoal… Креда и въглен… Chalk & Charcoal Креда и въглен Graphic Pen… Графична писалка… @@ -8036,7 +8719,349 @@ breakText Glyphs Глифи Pulse Stroke Пулсиращ щрих Round Flow Кръгъл поток Chisel Flow Скосен поток +@msg Script file access denied: {path} Достъпът до файла на скрипта е отказан: {path} +@msg Script file access to the app's own folders is not allowed Достъпът от скрипт до собствените папки на приложението не е разрешен +@msg Script file cannot encode the text Файлът на скрипта не може да кодира текста +@msg Script file could not be written Файлът на скрипта не можа да се запише +@msg Script file dialogs need a person to answer them Файловите диалогови прозорци за скриптове изискват човек, който да им отговори +@msg Script file is not open for writing Файлът на скрипта не е отворен за запис +@msg Script file name is already in use Името на файла на скрипта вече се използва +@msg Script file name must be a name without a folder Името на файла на скрипта трябва да е име без папка +@msg Script file permission can be kept only for a script run from a file Разрешението за файлове може да се запази само за скрипт, изпълнен от файл +@msg Script file permission could not be saved Разрешението за файлове на скрипта не можа да се запази +@msg Script folder is not empty Папката на скрипта не е празна +@msg Script files cannot make aliases Файловете на скриптове не могат да създават псевдоними +@msg Script file hidden setting cannot be changed Настройката за скриване на файла на скрипта не може да се променя +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файлов диалогов прозорец не може да се отвори в обратно извикване на вградена функция, в getter, в преобразуване или във файл, изпълнен от $.evalFile; извикайте го от собствения код на скрипта +@msg the script wrote more file data than one run may write (32 MiB) скриптът записа повече файлови данни, отколкото е разрешено за едно изпълнение (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` за файлов диалогов прозорец на скрипт трябва да е едно от: once, always, deny, stop +@msg choose a file or folder first, or deny първо изберете файл или папка или откажете +@msg the script file permissions could not be saved: {e} разрешенията за файлове на скрипта не можаха да се запазят: {e} +@msg this script's file access can be allowed only once достъпът до файлове на този скрипт може да се разреши само веднъж +@msg Only the person at the keyboard can allow a script's file access Само човекът на клавиатурата може да разреши достъпа на скрипт до файлове +@msg A script is given at most 2,048 files: the files picked after them were left out На скрипт се дават най-много 2,048 файла: файловете, избрани след тях, бяха пропуснати +@msg assignment to a constant binding присвояване на константна връзка +@msg invalid array length невалидна дължина на масив +@msg array literal too long литералът на масив е твърде дълъг +@msg the value is not a function стойността не е функция +@msg apply was called on a value that is not a function apply беше извикан за стойност, която не е функция +@msg the argument list is not an object списъкът с аргументи не е обект +@msg too many arguments твърде много аргументи +@msg the value is not a constructor стойността не е конструктор +@msg cannot convert the object to a primitive value обектът не може да се преобразува в примитивна стойност +@msg cannot convert undefined or null to an object undefined или null не може да се преобразува в обект +@msg the right side of 'in' is not an object дясната страна на 'in' не е обект +@msg the right side of 'instanceof' is not a function дясната страна на 'instanceof' не е функция +@msg the function's prototype is not an object прототипът на функцията не е обект +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} не е дефиниран +@msg cannot read property '{key}' of {base} свойството '{key}' на {base} не може да се прочете +@msg cannot set property '{key}' of {base} свойството '{key}' на {base} не може да се зададе +@msg cannot read a property of {base} свойство на {base} не може да се прочете +@msg cannot set a property of {base} свойство на {base} не може да се зададе +@msg cannot define property '{key}': {why} свойството '{key}' не може да се дефинира: {why} +@msg cannot assign to property '{key}': {why} на свойството '{key}' не може да се присвои: {why} +@msg cannot delete property '{key}' свойството '{key}' не може да се изтрие +@msg cannot declare function {ident} функцията {ident} не може да се декларира +@msg invalid assignment target невалидна цел на присвояване +@msg the array's length is read-only дължината на масива е само за четене +@msg the property cannot be redefined свойството не може да се предефинира +@msg the object is not extensible обектът не е разширяем +@msg the length cannot be redefined дължината не може да се предефинира +@msg it is read-only то е само за четене +@msg an element cannot be deleted елемент не може да се изтрие +@msg it has only a getter то има само getter +@msg the value is a primitive стойността е примитивна +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` има {n} отговор, който скриптът не използва|`answers` има {n} отговора, които скриптът не използва +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} остави {n} обект под четката непроменен ({_2}): променя формата само на пътища|{_1} остави {n} обекта под четката непроменени ({_2}): променя формата само на пътища +liquify-tool Warp Изкривяване +liquify-tool Twirl Въртене +liquify-tool Pucker Свиване +liquify-tool Bloat Надуване +liquify-tool Scallop Назъбване +liquify-tool Crystallize Кристализация +liquify-tool Wrinkle Набръчкване +liquify-kind graphs диаграми +liquify-kind type текст +liquify-kind symbols символи +liquify-kind images изображения +liquify-kind meshes мрежи +liquify-kind envelopes пликове +liquify-kind repeats повторения +liquify-kind placed documents поставени документи +liquify-kind blends преливания +liquify-list-two {0}, {1} {0} и {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} и {1} +@msg give one element задайте един елемент +@msg the element needs an id, the filter's name елементът изисква id, името на филтъра +@msg an SVG filter's id is at most {MAX_NAME} characters id на SVG филтър е най-много {MAX_NAME} знака +@msg <{_1}> isn't an element of an SVG filter <{_1}> не е елемент на SVG филтър +@msg an SVG filter has no event attributes such as {_1} SVG филтърът няма атрибути за събития като {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs изображенията на SVG филтър са data: URL адреси на PNG, JPEG, GIF или WebP +@msg the SVG filter isn't valid XML: {e} SVG филтърът не е валиден XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves на feTurbulence е най-много {MAX_OCTAVES} +@msg {what} is at most {max} {what} е най-много {max} +@msg feConvolveMatrix's order order на feConvolveMatrix +@msg feMorphology's radius radius на feMorphology +@msg a blur's stdDeviation stdDeviation на размазване +@msg the SVG filter has no primitives SVG филтърът няма примитиви +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG филтърът има най-много {MAX_PRIMITIVES} примитива +@msg the SVG filter is too large once its attributes are written out SVG филтърът е твърде голям, след като атрибутите му бъдат изписани +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all изображенията на SVG филтър имат общо най-много {MAX_IMAGE_PIXELS} пиксела +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG филтърът не може да се нарисува: проверете примитивите му и техните входове +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep елементите на SVG филтър се влагат най-много на {MAX_DEPTH} нива +@msg an SVG filter is at most {_1} KB SVG филтърът е най-много {_1} KB +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` трябва да е [a, b, c, d], всяко от -1000 до 1000, като a·d - b·c е на поне 0.001 от 0 +@msg `angle` must be from -180 to 180 degrees `angle` трябва да е от -180 до 180 градуса +@msg `roundness` must be from 0 to 100% `roundness` трябва да е от 0 до 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` трябва да е от 0.01 до 100 pt +@msg style must be "pencil" or "brush" style трябва да е "pencil" или "brush" +@msg extend end must be "start" or "end" end за удължаване трябва да е "start" или "end" +@msg connect end must be "start" or "end" end за свързване трябва да е "start" или "end" +@msg `roundness` must be from 1 to 100% `roundness` трябва да е от 1 до 100% +@msg 3D effects require finite coordinates within 100 million points 3D ефектите изискват крайни координати в рамките на 100 милиона точки +@msg 3D effects require one to ten lights 3D ефектите изискват от един до десет източника на светлина +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel дълбочина на BMP {_1}: 1, 4, 8, 16, 24 или 32 бита на пиксел +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer кодирането в BMP е неуспешно: {width} × {height} пиксела не се побират във формата или в буфера на пикселите +@msg GIF encoding failed: the palette image is malformed кодирането в GIF е неуспешно: изображението с палитра е неправилно оформено +@msg GIF encoding failed: {e} кодирането в GIF е неуспешно: {e} +@msg JPEG colour profile: {e} цветови профил на JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size кодирането в JPEG е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg JPEG encoding failed: {e} кодирането в JPEG е неуспешно: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size кодирането в PNG е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg PNG encoding failed: the palette image is malformed кодирането в PNG е неуспешно: изображението с палитра е неправилно оформено +@msg PNG encoding failed: {e} кодирането в PNG е неуспешно: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size кодирането в PNG е неуспешно: {width} × {height} пиксела не е валиден размер на изображение +@msg PSD colour profile: {e} цветови профил на PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size кодирането в PSD е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg Revolve profile contains invalid coordinates профилът за завъртане около ос съдържа невалидни координати +@msg Revolve profile is too complex профилът за завъртане около ос е твърде сложен +@msg Revolve projection is not finite проекцията на завъртането около ос не е крайна +@msg Revolve requires finite profile coordinates within 100 million points завъртането около ос изисква крайни координати на профила в рамките на 100 милиона точки +@msg Revolve surface is too complex; reduce Segments or simplify the profile повърхността на завъртането около ос е твърде сложна; намалете Сегменти или опростете профила +@msg Revolve surface is too complex; simplify the profile повърхността на завъртането около ос е твърде сложна; опростете профила +@msg Revolve visibility cannot split the projected boundary изчисляването на видимостта при завъртане около ос не може да раздели проектираната граница +@msg Revolve visibility creates too many fragments изчисляването на видимостта при завъртане около ос създава твърде много фрагменти +@msg Revolve visibility creates too many vector anchors изчисляването на видимостта при завъртане около ос създава твърде много векторни опорни точки +@msg Revolve visibility exceeds its geometry work limit изчисляването на видимостта при завъртане около ос надхвърля ограничението си за геометрична работа +@msg Revolve visibility exceeds its spatial index limit изчисляването на видимостта при завъртане около ос надхвърля ограничението си за пространствен индекс +@msg Revolve visibility has too many boundary crossings изчисляването на видимостта при завъртане около ос има твърде много пресичания на граници +@msg Revolve visibility has too many input anchors изчисляването на видимостта при завъртане около ос има твърде много входни опорни точки +@msg Revolve visibility requires convex cap sectors изчисляването на видимостта при завъртане около ос изисква изпъкнали сектори на капачката +@msg Revolve visibility requires finite projected faces изчисляването на видимостта при завъртане около ос изисква крайни проектирани страни +@msg SVG options: {e} опции за SVG: {e} +@msg Save for Web settings: {e} настройки за запис за уеб: {e} +@msg TIFF colour profile: {e} цветови профил на TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size кодирането в TIFF е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg TIFF encoding failed: {e} кодирането в TIFF е неуспешно: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel дълбочина на Targa {_1}: 16, 24 или 32 бита на пиксел +@msg Targa encoding failed: the pixel buffer doesn't match the image size кодирането в Targa е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg The 3D projection is not finite 3D проекцията не е крайна +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D сянката е твърде сложна; изключете Сенки или опростете графиката +@msg The shape contains invalid coordinates Формата съдържа невалидни координати +@msg Too many Revolve faces for visibility evaluation Твърде много страни на завъртането около ос за изчисляване на видимостта +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft чете най-много {ASE_MAX_ENTRIES} цвята и групи от файл за обмен на образци, а тази библиотека има {entries} +@msg WebP encoding failed: {e} кодирането в WebP е неуспешно: {e} +@msg WebP encoding failed: the image is too large for lossy WebP: lower the resolution or choose Lossless кодирането в WebP е неуспешно: изображението е твърде голямо за WebP със загуба: намалете разделителната способност или изберете Без загуба +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` трябва да е "document", {{artboards: [index, …]}} или {{layers: [id, …]}} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` е smallThumb, mediumThumb, largeThumb, smallList или largeList +@msg `{file}` has no swatches of its own `{file}` няма собствени образци +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` има образци на мостри, които файл .vcswatches не може да съдържа +@msg a line can't run from a point to itself линия не може да минава от точка до самата нея +@msg a line needs at least two points линията изисква поне две точки +@msg a linked image file is outside the read roots свързан файл на изображение е извън корените за четене +@msg a linked file's export folder is outside the read roots папката за експортиране на свързан файл е извън корените за четене +@msg a number cannot be read число не може да се прочете +@msg a swatch exchange block is too long блок за обмен на образци е твърде дълъг +@msg a swatch exchange name is too long име за обмен на образци е твърде дълго +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels изображение {sw} × {sh} не може да се преоразмери до {width} × {height} пиксела +@msg a {width} × {height} image is too large изображение {width} × {height} е твърде голямо +@msg a {width} × {height} image: {e} изображение {width} × {height}: {e} +@msg an image could not be written: {e} изображение не можа да се запише: {e} +@msg an image that couldn't be read was left out изображение, което не можа да се прочете, беше пропуснато +@msg can't open “{name}”: {e} „{name}“ не може да се отвори: {e} +@msg cannot align zip entries to {align} bytes елементите на zip не могат да се подравнят на {align} байта +@msg cannot open the automation {kind} root `{_1}`: {e} коренът {kind} за автоматизация `{_1}` не може да се отвори: {e} +@msg cannot read profile: {0} профилът не може да се прочете: {0} +@msg color book version {version} isn't supported (only 1) версия {version} на цветова книга не се поддържа (само 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) цветови книги в цветово пространство {other} не се поддържат (само RGB, CMYK и Lab) +@msg file name too long to zip: {_1} името на файла е твърде дълго за zip: {_1} +@msg file name too long to zip: {name} името на файла е твърде дълго за zip: {name} +@msg freeform line {i}: {e} свободна линия {i}: {e} +@msg freeform point {i}: {e} свободна точка {i}: {e} +@msg give `{key}` or `{other}`, not both задайте `{key}` или `{other}`, но не и двете +@msg grayscale profiles can't be working spaces yet профилите в нива на сивото все още не могат да бъдат работни пространства +@msg input contains NaN or infinite coordinates входните данни съдържат NaN или безкрайни координати +@msg input path could not be closed входният път не можа да се затвори +@msg invalid ICC profile: {0} невалиден профил ICC: {0} +@msg invalid scale {scale} невалиден мащаб {scale} +@msg its localized names take more than {_1} KB локализираните му имена заемат повече от {_1} KB +@msg its objects are nested too deep ({e}) обектите му са вложени твърде дълбоко ({e}) +@msg its tag table lists the `{_1}` tag more than once таблицата му с тагове изброява тага `{_1}` повече от веднъж +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again не са намерени подобни обекти (отразените копия не се съпоставят); променете опциите за глобално редактиране и опитайте отново +@msg not a graphic style library: {e} не е библиотека с графични стилове: {e} +@msg not a swatch library (.vcswatches or .gpl) не е библиотека с образци (.vcswatches или .gpl) +@msg not a swatch library (format `{_1}`) не е библиотека с образци (формат `{_1}`) +@msg not a swatch library: {e} не е библиотека с образци: {e} +@msg not an action set file ({e}) не е файл с набор от действия ({e}) +@msg numbers out of order in {{}} quantifier числата в квантора {{}} не са в правилния ред +@msg profile colour space {other} is not RGB, CMYK or Gray цветовото пространство на профила {other} не е RGB, CMYK или Gray +@msg regular expression too large регулярният израз е твърде голям +@msg script file is not UTF-8 text: {value} файлът на скрипта не е текст в UTF-8: {value} +@msg step {step} of “{action}” runs the unknown command `{command}` стъпка {step} от „{action}“ изпълнява неизвестната команда `{command}` +@msg stop {i}: {e} спирка {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) версия {major}.{minor} на обмена на образци не се поддържа (само 1.x) +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: използвайте "{_1}" или "{_2}" +@msg the SVG's style sheets take too long to match съпоставянето на стиловете на SVG отнема твърде дълго +@msg the SVG's styles expand to more than {0} MB стиловете на SVG се разширяват до повече от {0} MB +@msg the color book holds more than {ASE_MAX_ENTRIES} colors цветовата книга съдържа повече от {ASE_MAX_ENTRIES} цвята +@msg the color book is cut short цветовата книга е прекъсната +@msg the color book's names take more than {_1} MB имената в цветовата книга заемат повече от {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution изображението би било {w} × {h} пиксела; растерното експортиране е ограничено до {MAX_RASTER_SIDE} пиксела на страна и {_1} мегапиксела: намалете мащаба или разделителната способност +@msg the optimised image can't be read back: {e} оптимизираното изображение не може да се прочете обратно: {e} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) боята не е свободен градиент (приложете такъв с paint.editGradient {{kind: "freeform"}}) +@msg the pixel buffer doesn't match the image size буферът на пикселите не съответства на размера на изображението +@msg the preview: {e} визуализацията: {e} +@msg the request may not read the New Document profiles folder заявката не може да чете папката с профили за нов документ +@msg the shapes are too degenerate to combine формите са твърде дегенерирали за комбиниране +@msg the shapes cross themselves and each other too often to combine формите пресичат себе си и една друга твърде често за комбиниране +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups файлът за обмен на образци съдържа повече от {ASE_MAX_ENTRIES} цвята и групи +@msg the swatch exchange file is cut short файлът за обмен на образци е прекъснат +@msg the {_1} plate can't be read: {e} плаката {_1} не може да се прочете: {e} +@msg this binary DXF file is damaged or cut short този двоичен файл DXF е повреден или прекъснат +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that това е DWG чертеж, който не може да бъде прочетен: запазете го от CAD приложението като DXF и го отворете +@msg too many classes твърде много класове +@msg too many groups твърде много групи +@msg too many layers for PSD (at most 32767) твърде много слоеве за PSD (най-много 32767) +@msg too many swatch exchange blocks твърде много блокове за обмен на образци +@msg unknown colour profile: {0} неизвестен цветови профил: {0} +@msg {_1} clashes with a built-in profile name {_1} съвпада с име на вграден профил +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} пиксела е твърде голямо за GIF (най-много 65535 пиксела на страна): намалете разделителната способност +@msg {_1}: no usable transform to/from sRGB {_1}: няма използваемо преобразуване към или от sRGB +@msg {name} is not a CMYK profile {name} не е профил CMYK +@msg {name} is not an RGB profile {name} не е профил RGB +@msg {path}: could not be read {path}: не можа да се прочете +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} пиксела е твърде голямо за JPEG (най-много 65535 пиксела на страна): намалете разделителната способност +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} пиксела е твърде голямо за Targa (най-много 65535 пиксела на страна): намалете разделителната способност +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пиксела е твърде голямо за PSD (най-много {MAX_SIDE} пиксела на страна): намалете разделителната способност +@msg the template name can't be empty името на шаблона не може да е празно +@msg the template name isn't usable as a file name името на шаблона не може да се използва като име на файл +@msg no metadata templates folder here тук няма папка с шаблони за метаданни +@msg give `name` or `path`, not both задайте `name` или `path`, но не и двете +@msg give one of `path`, `name` and `data` задайте едно от `path`, `name` и `data` +@msg mode must be replace, keep or append mode трябва да е replace, keep или append +@msg the file is not an XMP metadata template файлът не е шаблон за метаданни XMP +@msg no path painted with a brush is selected не е избран път, нарисуван с четка +@msg the selected paths are painted with brushes of different types избраните пътища са нарисувани с четки от различни типове +@msg give `params` or `reset`, not both задайте `params` или `reset`, но не и двете +@msg a bristle brush has no options of its own on a path четката с косъм няма собствени опции върху път +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all някои растерни ефекти не бяха превърнати в изображения: биха заели общо повече от 1,024 изображения или 256 мегапиксела +@msg Shape Builder: select all paths you want to merge Инструмент за създаване на форми: изберете всички пътища, които искате да обедините +@msg action step {_1} (`{id}`) failed: {reason} стъпката на действие {_1} (`{id}`) е неуспешна: {reason} +@msg `points` must be three [x, y] pairs of numbers `points` трябва да са три двойки числа [x, y] +@msg direct-select three anchor points, or give `points` изберете директно три опорни точки или задайте `points` +@msg no circle passes through these points: two are the same or all three lie on one line никоя окръжност не минава през тези точки: две от тях съвпадат или и трите лежат на една линия +@msg `{panel}` has no display sizes to cycle `{panel}` няма размери на показване за превключване +@msg the panels are not shown панелите не са показани +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first линия или друг отворен път, който не огражда площ, не променя формата на резултата; за да го включите, първо приложете към него Обект › Път › Преобразуване на щриха в контур +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} даде празен резултат: линия или друг отворен път не огражда площ; за да го включите, първо приложете към него Обект › Път › Преобразуване на щриха в контур +@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first линия или друг отворен път, който не огражда площ, не добавя площ към съставната форма; за да го включите, първо приложете към него Обект › Път › Преобразуване на щриха в контур +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Извадено е {n} вградено изображение в {folder}|Извадени са {n} вградени изображения в {folder} +@msg every numbered name for {name} is taken in that folder всяко номерирано име за {name} вече е заето в тази папка +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Импортирането чете файл с източник на данни, завършващ на .csv, .tsv, .txt или .xml +variable-kind Visibility Видимост +variable-kind Linked File Свързан файл +variable-kind Graph Data Данни за диаграма +variable-kind Unknown Непознат +variable-list-two {0}, {1} {0} и {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} и {1} +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Минимум не трябва да надхвърля Желано, нито Желано да надхвърля Максимум +@msg side is left or right, not `{v}` side е left или right, а не `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order е цяло число от 0 до {others}, а не `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (името на лента с инструменти) трябва да е низ +@msg no toolbar named `{name}` няма лента с инструменти с име `{name}` +@msg toolbar name can't be empty името на лентата с инструменти не може да е празно +@msg a toolbar name has at most {MAX_NAME} characters името на лента с инструменти има най-много {MAX_NAME} знака +@msg there is already a toolbar named `{name}` вече има лента с инструменти с име `{name}` +@msg there is already a toolbar named `{to}` вече има лента с инструменти с име `{to}` +@msg a workspace keeps at most {MAX} toolbars работното пространство съдържа най-много {MAX} ленти с инструменти +@msg name (a toolbar's name) must be a string name (името на лента с инструменти) трябва да е низ +@msg name (a toolbar's name) is required name (името на лента с инструменти) е задължително +@msg to (the new name) is required to (новото име) е задължително +@msg name must be a toolbar's name name трябва да е името на лента с инструменти # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Редактиране на оригинала с: file-filter Applications Приложения +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out текстът, растерните изображения, преливанията, контурите, щрихите на четки и другите обекти от CDR, които VectorCraft все още не чете, бяха пропуснати +@msg CDR fountain, pattern, texture and PostScript fills were left out запълванията от CDR с преход, мостра, текстура и PostScript бяха пропуснати +@msg colors in CDR color models VectorCraft doesn't read were opened as black цветовете в цветови модели на CDR, които VectorCraft не чете, бяха отворени като черно +@msg CDR library colors that the drawing stores only by number were opened as black spot colors цветовете от библиотеки на CDR, които чертежът съхранява само по номер, бяха отворени като черни спот цветове +@msg CDR outline arrowheads were left out върховете на стрелки на контурите от CDR бяха пропуснати +@msg CDR envelopes were not applied, and the shapes under them keep their outlines пликовете от CDR не бяха приложени и формите под тях запазват очертанията си +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque лещите и прозрачността на обекти от CDR не бяха приложени и обектите, върху които са, се показват непрозрачни +@msg parts of the drawing nested too deeply, or past the import limits, were left out части от чертежа, вложени твърде дълбоко или извън ограниченията за импортиране, бяха пропуснати +@msg damaged parts of the drawing were left out повредените части от чертежа бяха пропуснати +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страниците от CDR, по-дълги от 163,830 pt, бяха отворени с тази дължина и графиката близо до ръбовете им е извън работната област +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out текстът, изображенията, правоъгълниците, елипсите, изрязващите пътища и другите обекти от CMX, които VectorCraft все още не чете, бяха пропуснати +@msg CMX fills other than uniform colors were left out запълванията от CMX, различни от еднородни цветове, бяха пропуснати +@msg colors in CMX color models VectorCraft doesn't read were opened as black цветовете в цветови модели на CMX, които VectorCraft не чете, бяха отворени като черно +@msg CMX library colors that the file stores only by number were opened as black spot colors цветовете от библиотеки на CMX, които файлът съхранява само по номер, бяха отворени като черни спот цветове +@msg CMX outline arrowheads were left out върховете на стрелки на контурите от CMX бяха пропуснати +@msg CMX lenses were not applied лещите от CMX не бяха приложени +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страниците от CMX, по-дълги от 163,830 pt, бяха отворени с тази дължина и графиката близо до ръбовете им е извън работната област +@msg the file is no longer loaded файлът вече не е зареден +@msg 1 type layer came in as pixels: the text isn't editable 1 текстов слой беше импортиран като пиксели: текстът не може да се редактира +@msg {n} type layers came in as pixels: the text isn't editable {n} текстови слоя бяха импортирани като пиксели: текстът не може да се редактира +@msg 1 adjustment layer was not applied 1 коригиращ слой не беше приложен +@msg {n} adjustment layers were not applied {n} коригиращи слоя не бяха приложени +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 слой за запълване не беше нарисуван (запълване с градиент или мостра, цвят, който не може да се прочете, или форма, която не съхранява пиксели) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} слоя за запълване не бяха нарисувани (запълване с градиент или мостра, цвят, който не може да се прочете, или форма, която не съхранява пиксели) +@msg the layer effects of 1 layer weren't drawn ефектите на слоя на 1 слой не бяха нарисувани +@msg the layer effects of {n} layers weren't drawn ефектите на слоевете на {n} слоя не бяха нарисувани +@msg the vector masks of 1 layer weren't applied векторните маски на 1 слой не бяха приложени +@msg the vector masks of {n} layers weren't applied векторните маски на {n} слоя не бяха приложени +@msg the knockout of 1 layer wasn't applied избиването на 1 слой не беше приложено +@msg the knockout of {n} layers wasn't applied избиването на {n} слоя не беше приложено +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 слой беше пропуснат (скрити слоеве и слоевете, изрязани по тях) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} слоя бяха пропуснати (скрити слоеве и слоевете, изрязани по тях) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 слой, изрязан по слой за запълване, който не беше нарисуван, беше пропуснат +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} слоя, изрязани по слоеве за запълване, които не бяха нарисувани, бяха пропуснати +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them слоевете в режими на смесване, които VectorCraft няма ({modes}), бяха обединени със слоевете под тях +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 слой в режими на смесване, които VectorCraft няма, беше импортиран като Нормално: обединяването изисква повече памет от разрешеното +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} слоя в режими на смесване, които VectorCraft няма, бяха импортирани като Нормално: обединяването изисква повече памет от разрешеното +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 слой, изрязан по слоя отдолу, беше импортиран без изрязване: обединяването изисква повече памет от разрешеното +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} слоя, изрязани по слоя отдолу, бяха импортирани без изрязване: обединяването изисква повече памет от разрешеното +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers се прилага към файл PSD, поставен с layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: свързан файл PSD се поставя като плоското си изображение; задайте link: false, за да го вградите с отрязъците му +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: свързан файл PSD се поставя като плоското си изображение; пропуснете link или задайте link: false +@msg 1 slice lies outside the canvas or has no size and was left out 1 отрязък е извън платното или няма размер и беше пропуснат +@msg {n} slices lie outside the canvas or have no size and were left out {n} отрязъка са извън платното или нямат размер и бяха пропуснати +@msg 1 slice would lie outside the canvas and was left out 1 отрязък би бил извън платното и беше пропуснат +@msg {n} slices would lie outside the canvas and were left out {n} отрязъка биха били извън платното и бяха пропуснати +@msg the slices' descriptor holds too many values дескрипторът на отрязъците съдържа твърде много стойности +@msg the slices' descriptor has a version other than 16 дескрипторът на отрязъците има версия, различна от 16 +@msg the slices' descriptor has no list of slices дескрипторът на отрязъците няма списък с отрязъци +@msg the slices' descriptor lists something other than a slice дескрипторът на отрязъците изброява нещо, което не е отрязък +@msg a slice in the slices' descriptor has no bounds отрязък в дескриптора на отрязъците няма граници +@msg a slice's bounds in the slices' descriptor aren't numbers границите на отрязък в дескриптора на отрязъците не са числа +@msg the slices' descriptor nests too deep дескрипторът на отрязъците е вложен твърде дълбоко +@msg the slices can't be read ({e}) and were left out отрязъците не могат да се прочетат ({e}) и бяха пропуснати +@msg the slices are stored in version {v}, which isn't read отрязъците са съхранени във версия {v}, която не се чете +@msg the file has {count} slices, more than the {MAX_SLICES} read файлът има {count} отрязъка, повече от {MAX_SLICES}, които се четат +@msg a text in the slices has more than the {MAX_TEXT} characters read текст в отрязъците има повече от {MAX_TEXT} знака, които се четат +@msg the slices' descriptor has a reference of an unknown kind ({_1}) дескрипторът на отрязъците има препратка от неизвестен вид ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) дескрипторът на отрязъците има стойност от неизвестен тип ({_1}) +@msg the layers can't be read ({e}): the file was placed as its merged image слоевете не могат да се прочетат ({e}): файлът беше поставен като обединеното си изображение +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on обектът {_1} е изображение, променено с Перспективно изкривяване или Свободно изкривяване, с което тази команда не работи +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape изображението {_1} не може да се изкриви така: ъглите му не биха образували изпъкнала форма +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon изображението {_1} не може да се изкриви така: ъглите му биха пресекли хоризонта на деформацията +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map изображението {_1} не може да се изкриви така: ъглите му биха били твърде близо един до друг за перспективно преобразуване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9a4f7158fe..7ef7d815b9 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -344,6 +344,9 @@ Artboards Radne ploče Convert to Artboards Pretvori u radne ploče Rearrange All Artboards… Preuredi sve radne ploče… + Rearrange… Preuredi… + Selected Artboards: {n} Odabrane radne ploče: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kliknite na platno da postavite radne ploče (Esc otkazuje) Fit to Artwork Bounds Uklopi u granice crteža Fit to Selected Art Uklopi u odabrani crtež Graph Grafikon @@ -504,6 +507,7 @@ Fill & Stroke Ispuna i potez Fill Color Boja ispune Opacity Neprozirnost + Show Opacity Prikaži neprozirnost Stroke Color Boja poteza Fill Gradient Gradijent ispune Stroke Gradient Gradijent poteza @@ -3677,6 +3681,12 @@ theme Appearance Izgled {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable rezolucija nije dostupna + estimated memory {memory} procijenjena memorija {memory} + memory unavailable memorija nije dostupna + Unknown format Nepoznat format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4127,6 +4137,7 @@ theme Appearance Izgled Data Recovery Oporavak podataka Default Language Zadani jezik Disable Auto Add/Delete Onemogući automatsko dodavanje/brisanje + Delete Removes Anchor Points and Keeps Paths Joined Delete uklanja sidrene tačke i zadržava putanje spojenim Interpolate Control Points When Moving Anchors Interpoliraj ručke smjera pri pomjeranju sidrenih tačaka Display All Blacks Accurately Prikaži sve crne tačno Display All Blacks as Rich Black Prikaži sve crne kao bogatu crnu @@ -4708,6 +4719,7 @@ font-technology Variable Varijabilni A two-finger rotate gesture on a trackpad rotates the canvas view. Pokret rotacije s dva prsta na dodirnoj podlozi rotira prikaz platna. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Držanje tipke pokreće alat ili naredbu iz njene kolone „Zadrži“ u Prečicama na tastaturi; kratki pritisak pokreće njenu uobičajenu prečicu. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Koliko sekundi tipka mora biti pritisnuta prije nego što se umjesto uobičajene prečice pokrene njena prečica zadržavanjem. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete uklanja odabrane sidrene tačke i ponovo prilagođava krivu oko svake od njih, umjesto da tamo otvori putanju. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kada pomjerate sidrene tačke, svaka kriva s jednim pomjerenim krajem zadržava svoj oblik u odnosu na svoje krajeve. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Držanje prečice alata bira taj alat dok je ne pustite, a zatim se ponovo bira prethodni alat. Shows the bounding box while you move the selection or draw a shape. Prikazuje granični okvir dok pomjerate odabir ili crtate oblik. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0ebd34bda7..7cc27b2f1c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1331,6 +1331,7 @@ arrowhead Target Diana Direction: Direcció: Directives Directrius Disable Auto Add/Delete Desactiva l’addició i la supressió automàtiques + Delete Removes Anchor Points and Keeps Paths Joined Suprimir elimina els punts d’ancoratge i manté els camins units Interpolate Control Points When Moving Anchors Interpola les manetes de direcció en moure punts d’ancoratge Disable Opacity Mask Desactiva la màscara d’opacitat Discard Descarta @@ -3199,6 +3200,7 @@ digits Malayalam Malaiàlam One Point Perspective Preset 5 Preajust 5 de perspectiva d’un punt Only Web Colors Només colors web Opacity Opacitat + Show Opacity Mostra l’opacitat Opacity & Mask Define Knockout Shape L’opacitat i la màscara defineixen la forma d’exclusió Opacity Mask Màscara d’opacitat Opacity Mask Info Informació de la màscara d’opacitat @@ -3435,6 +3437,12 @@ digits Malayalam Malaiàlam {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable resolució no disponible + estimated memory {memory} memòria estimada {memory} + memory unavailable memòria no disponible + Unknown format Format desconegut {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -3792,6 +3800,9 @@ digits Malayalam Malaiàlam Rearrange All Reorganitza-ho tot Rearrange All Artboards Reorganitza tots els taulers Rearrange All Artboards… Reorganitza tots els taulers… + Rearrange… Reorganitza… + Selected Artboards: {n} Taulers seleccionats: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Fes clic al llenç per col·locar els taulers (Esc cancel·la) Rearrange Artboards Reorganitza els taulers Recall Selection Recupera la selecció RECENT RECENTS @@ -4079,6 +4090,7 @@ digits Malayalam Malaiàlam A two-finger rotate gesture on a trackpad rotates the canvas view. Un gest de rotació amb dos dits al trackpad gira la vista del llenç. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Mantenir premuda una tecla executa l’eina o l’ordre de la seva columna Mantén a Dreceres de teclat; una pulsació breu executa la seva drecera habitual. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Quants segons cal mantenir premuda una tecla perquè s’executi la seva drecera de pulsació llarga en lloc de la drecera habitual. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Suprimir elimina els punts d’ancoratge seleccionats i reajusta la corba al voltant de cadascun, en lloc d’obrir-hi el camí. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quan moveu punts d’ancoratge, cada corba amb un extrem desplaçat conserva la forma respecte dels seus extrems. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantenir premuda la drecera d’una eina la tria fins que la deixeu anar, i després es torna a triar l’eina anterior. Shows the bounding box while you move the selection or draw a shape. Mostra el quadre delimitador mentre moveu la selecció o dibuixeu una forma. @@ -7714,6 +7726,8 @@ variable-list-end {0}, {1} {0} i {1} @msg needs approval: it asks for {0}, which the user grants when installing it on its own cal aprovació: demana {0}, que l’usuari concedeix en instal·lar-lo per separat @msg not JSON: {e} no és JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) no és un binari WebAssembly (falta la capçalera \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un tipus de funció supera el límit de {MAX_FUNC_TYPE_VALUES} paràmetres +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un tipus de funció supera el límit de {MAX_FUNC_TYPE_VALUES} resultats @msg parameter `{k}`: {what} paràmetre `{k}`: {what} @msg parameter `{name}`: {what} paràmetre `{name}`: {what} @msg plug-in parameters must be a JSON object els paràmetres del complement han de ser un objecte JSON @@ -7751,6 +7765,11 @@ variable-list-end {0}, {1} {0} i {1} @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` i `maxItems` han de ser 0-{MAX_LIST}, `maxItems` com a mínim 1, i el valor predeterminat ha de tenir aquesta quantitat @msg `name` must be a string `name` ha de ser una cadena @msg `opacity` must be a number `opacity` ha de ser un nombre +@msg `opacity` must be a number from 0 to 100 `opacity` ha de ser un nombre del 0 al 100 +@msg `opacity` must be true or false `opacity` ha de ser true o false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke els caràcters de text no tenen opacitat pròpia: afegiu un farciment o un traç amb Afegeix un farciment nou o Afegeix un traç nou del tauler Aparença +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un objecte seleccionat en una instància de símbol no té opacitat pròpia de farciment ni de traç +@msg no target has that fill or stroke to take the opacity cap objectiu no té aquest farciment o traç per rebre l'opacitat @msg `type` must be "path" or "compound" `type` ha de ser "path" o "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` ha de tenir 1-{MAX_UNIT} caràcters imprimibles @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` ha d’indicar d’1 a {MAX_CONDITION_VALUES} valors per a `{other}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 217fc9161f..2d9793cc53 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -351,6 +351,9 @@ Artboards Pracovní plochy Convert to Artboards Převést na pracovní plochy Rearrange All Artboards… Přeuspořádat všechny pracovní plochy… + Rearrange… Přeuspořádat… + Selected Artboards: {n} Vybrané pracovní plochy: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kliknutím na plátno umístíte pracovní plochy (Esc zruší) Fit to Artwork Bounds Přizpůsobit hranicím kresby Fit to Selected Art Přizpůsobit vybrané kresbě Graph Graf @@ -518,6 +521,7 @@ Fill & Stroke Výplň a tah Fill Color Barva výplně Opacity Krytí + Show Opacity Zobrazit krytí Stroke Color Barva tahu Fill Gradient Přechod výplně Stroke Gradient Přechod tahu @@ -3778,6 +3782,12 @@ theme Appearance Motiv {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable rozlišení není k dispozici + estimated memory {memory} odhadovaná paměť {memory} + memory unavailable paměť není k dispozici + Unknown format Neznámý formát {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4232,6 +4242,7 @@ theme Appearance Motiv Data Recovery Obnovení dat Default Language Výchozí jazyk Disable Auto Add/Delete Vypnout automatické přidávání/odstraňování + Delete Removes Anchor Points and Keeps Paths Joined Delete odstraní kotevní body a ponechá cesty spojené Interpolate Control Points When Moving Anchors Interpolovat směrové úchyty při přesouvání kotevních bodů Display All Blacks Accurately Zobrazovat všechny černé přesně Display All Blacks as Rich Black Zobrazovat všechny černé jako sytou černou @@ -4817,6 +4828,7 @@ font-technology Variable Variabilní A two-finger rotate gesture on a trackpad rotates the canvas view. Gesto otočení dvěma prsty na trackpadu otáčí zobrazení plátna. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Podržení klávesy spustí nástroj nebo příkaz ze sloupce Podržení v Klávesových zkratkách; krátký stisk spustí její obvyklou zkratku. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Jak dlouho v sekundách je nutné klávesu podržet, než se místo obvyklé zkratky spustí její zkratka podržením. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete odstraní vybrané kotevní body a znovu přizpůsobí křivku kolem každého z nich, místo aby tam cestu otevřel. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Když přesouváte kotvové body, každá křivka s jedním přesunutým koncem si zachová tvar vůči svým koncům. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Podržení zkratky nástroje vybere nástroj, dokud ji nepustíte, a pak se znovu vybere předchozí nástroj. Shows the bounding box while you move the selection or draw a shape. Zobrazí ohraničovací rámeček, když přesouváte výběr nebo kreslíte tvar. @@ -7325,6 +7337,8 @@ axis Y Axis osa Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own vyžaduje schválení: žádá o {0}, což uživatel povolí, když ho instaluje samostatně @msg not JSON: {e} není JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) není binární soubor WebAssembly (chybí hlavička \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters typ funkce má více parametrů, než dovoluje limit ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results typ funkce má více výsledků, než dovoluje limit ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} parametr `{k}`: {what} @msg parameter `{name}`: {what} parametr `{name}`: {what} @msg plug-in parameters must be a JSON object parametry zásuvného modulu musí být objekt JSON @@ -7361,6 +7375,11 @@ axis Y Axis osa Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` a `maxItems` musí být 0-{MAX_LIST}, `maxItems` alespoň 1 a výchozí hodnota musí mít tolik položek @msg `name` must be a string `name` musí být řetězec @msg `opacity` must be a number `opacity` musí být číslo +@msg `opacity` must be a number from 0 to 100 `opacity` musí být číslo od 0 do 100 +@msg `opacity` must be true or false `opacity` musí být true nebo false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke znaky textu nemají vlastní krytí: přidejte výplň nebo tah příkazem Přidat novou výplň nebo Přidat nový tah v panelu Vzhled +@msg an object selected in a symbol instance has no fill or stroke opacity of its own objekt vybraný v instanci symbolu nemá vlastní krytí výplně ani tahu +@msg no target has that fill or stroke to take the opacity žádný cíl nemá tuto výplň nebo tah, který by převzal krytí @msg `type` must be "path" or "compound" `type` musí být "path" nebo "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` musí mít 1-{MAX_UNIT} tisknutelných znaků @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` musí uvádět 1 až {MAX_CONDITION_VALUES} hodnot pro `{other}` @@ -9666,6 +9685,7 @@ breakText Glyphs Glyfy @msg give a pattern name or select an object painted with a pattern zadejte název vzorku nebo vyberte objekt vybarvený vzorkem @msg give at least one of clip, invert, disabled, linked zadejte alespoň jedno z clip, invert, disabled, linked @msg give color, none, swatch or gradient zadejte color, none, swatch nebo gradient +@msg give color, none, swatch, gradient or opacity zadejte color, none, swatch, gradient nebo opacity @msg give dataBase64 zadejte dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) zadejte buď at (kliknutí), nebo area (cestu nakreslenou kolem překryvů) @msg give exactly one of `at`, `rect` and `points` zadejte právě jedno z `at`, `rect` a `points` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9eba4ff3ad..1ba2c16b0a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -555,6 +555,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg needs approval: it asks for {0}, which the user grants when installing it on its own kræver godkendelse: det beder om {0}, som brugeren tildeler, når det installeres for sig selv @msg not JSON: {e} ikke JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) ikke en WebAssembly-binærfil (headeren \\0asm mangler) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters en funktionstype overskrider grænsen på {MAX_FUNC_TYPE_VALUES} parametre +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results en funktionstype overskrider grænsen på {MAX_FUNC_TYPE_VALUES} resultater @msg parameter `{k}`: {what} parameteren `{k}`: {what} @msg parameter `{name}`: {what} parameteren `{name}`: {what} @msg plug-in parameters must be a JSON object plug-in-parametrene skal være et JSON-objekt @@ -592,6 +594,11 @@ liquify-list-end {0}, {1} {0} og {1} @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` og `maxItems` skal være 0-{MAX_LIST}, `maxItems` mindst 1, og standardværdien skal have så mange @msg `name` must be a string `name` skal være en streng @msg `opacity` must be a number `opacity` skal være et tal +@msg `opacity` must be a number from 0 to 100 `opacity` skal være et tal fra 0 til 100 +@msg `opacity` must be true or false `opacity` skal være true eller false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tegn i tekst har ingen egen opacitet: tilføj en udfyldning eller kontur med Tilføj ny udfyldning eller Tilføj ny kontur i panelet Udseende +@msg an object selected in a symbol instance has no fill or stroke opacity of its own et objekt, der er markeret i en symbolforekomst, har ingen egen opacitet for udfyldning eller kontur +@msg no target has that fill or stroke to take the opacity intet mål har den udfyldning eller kontur, der kan modtage opaciteten @msg `type` must be "path" or "compound" `type` skal være "path" eller "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` skal være 1-{MAX_UNIT} tegn, der kan udskrives @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` angiver 1 til {MAX_CONDITION_VALUES} værdier for `{other}` @@ -3093,6 +3100,9 @@ liquify-list-end {0}, {1} {0} og {1} Artboards Tegneflader Convert to Artboards Konvertér til tegneflader Rearrange All Artboards… Omarrangér alle tegneflader… + Rearrange… Omarrangér… + Selected Artboards: {n} Markerede tegneflader: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klik på lærredet for at placere tegnefladerne (Esc annullerer) Fit to Artwork Bounds Tilpas til grafikkens grænser Fit to Selected Art Tilpas til valgt grafik Graph Diagram @@ -3244,6 +3254,7 @@ liquify-list-end {0}, {1} {0} og {1} Fill & Stroke Fyld og streg Fill Color Fyldfarve Opacity Opacitet + Show Opacity Vis opacitet Stroke Color Stregfarve Fill Gradient Fyldgradient Stroke Gradient Streggradient @@ -6269,6 +6280,12 @@ theme Appearance Udseende {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable opløsning ikke tilgængelig + estimated memory {memory} anslået hukommelse {memory} + memory unavailable hukommelse ikke tilgængelig + Unknown format Ukendt format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -6716,6 +6733,7 @@ theme Appearance Udseende Data Recovery Datgendannelse Default Language Standardsprog Disable Auto Add/Delete Deaktivér automatisk tilføjelse/sletning + Delete Removes Anchor Points and Keeps Paths Joined Delete fjerner ankerpunkter og holder stier samlet Interpolate Control Points When Moving Anchors Interpolér retningshåndtag ved flytning af ankerpunkter Display All Blacks Accurately Vis alle sorte nøjagtigt Display All Blacks as Rich Black Vis alle sorte som rich black @@ -7276,6 +7294,7 @@ font-technology Variable Variable A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsbevægelse med to fingre på en pegeplade roterer visningen af lærredet. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Når du holder en tast nede, køres værktøjet eller kommandoen i dens Hold-kolonne i Tastaturgenveje; et kort tryk kører dens sædvanlige genvej. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hvor mange sekunder en tast skal holdes nede, før dens holdegenvej køres i stedet for dens sædvanlige genvej. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete fjerner de markerede ankerpunkter og tilpasser kurven omkring hvert af dem i stedet for at åbne stien der. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Når du flytter ankerpunkter, beholder hver kurve med ét flyttet endepunkt sin form i forhold til sine endepunkter. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Når du holder et værktøjs genvejstast nede, er værktøjet valgt, indtil du slipper, og derefter vælges det forrige værktøj igen. Shows the bounding box while you move the selection or draw a shape. Viser afgrænsningsboksen, mens du flytter markeringen eller tegner en form. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index abb89c6dc7..76070280e6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -909,6 +909,7 @@ font-technology Variable Variabel Direct Selection Tool Direktauswahl-Werkzeug Direction Handles Richtungsgriffe Disable Auto Add/Delete Automatisches Hinzufügen/Löschen deaktivieren + Delete Removes Anchor Points and Keeps Paths Joined Entf entfernt Ankerpunkte und lässt Pfade verbunden Interpolate Control Points When Moving Anchors Richtungsgriffe beim Verschieben von Ankerpunkten interpolieren Disable Opacity Mask Deckkraftmaske deaktivieren Discard Verwerfen @@ -2436,6 +2437,12 @@ file-filter Templates Vorlagen {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable Auflösung nicht verfügbar + estimated memory {memory} geschätzter Speicher {memory} + memory unavailable Speicher nicht verfügbar + Unknown format Unbekanntes Format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2584,6 +2591,7 @@ file-filter Templates Vorlagen One Point Perspective Preset 5 Einpunktperspektive – Vorgabe 5 Only Web Colors Nur Webfarben Opacity Deckkraft + Show Opacity Deckkraft einblenden Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform Opacity Mask Deckkraftmaske Opacity Mask Info Informationen zur Deckkraftmaske @@ -3038,6 +3046,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Grafik mit Zeichenfläche skalieren Artboards: {n} Zeichenflächen: {n} Rearrange All Artboards… Alle Zeichenflächen neu anordnen… + Rearrange… Neu anordnen… + Selected Artboards: {n} Ausgewählte Zeichenflächen: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klicken Sie auf die Arbeitsfläche, um die Zeichenflächen zu platzieren (Esc bricht ab) Recall Selection Auswahl abrufen RECENT ZULETZT VERWENDET Recent Zuletzt verwendet @@ -3291,6 +3302,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. Eine Drehgeste mit zwei Fingern auf einem Trackpad dreht die Ansicht der Arbeitsfläche. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Halten Sie eine Taste, wird das Werkzeug oder der Befehl aus ihrer Spalte „Halten“ unter „Tastaturbefehle“ ausgeführt; ein kurzer Druck führt ihren üblichen Tastaturbefehl aus. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Wie viele Sekunden eine Taste gehalten werden muss, bevor statt ihres üblichen Tastaturbefehls ihr Halte-Tastaturbefehl ausgeführt wird. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Entf entfernt die ausgewählten Ankerpunkte und passt die Kurve um jeden davon neu an, statt den Pfad dort zu öffnen. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Wenn Sie Ankerpunkte verschieben, behält jede Kurve mit einem verschobenen Ende ihre Form relativ zu ihren Enden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Solange Sie das Tastaturkürzel eines Werkzeugs gedrückt halten, ist dieses Werkzeug gewählt; danach wird wieder das vorherige gewählt. Shows the bounding box while you move the selection or draw a shape. Zeigt den Begrenzungsrahmen an, während Sie die Auswahl verschieben oder eine Form zeichnen. @@ -6908,6 +6920,8 @@ axis Y Axis Y-Achse @msg needs approval: it asks for {0}, which the user grants when installing it on its own muss genehmigt werden: Es verlangt {0}, was der Benutzer gewährt, wenn er es einzeln installiert @msg not JSON: {e} kein JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) keine WebAssembly-Binärdatei (der Header \\0asm fehlt) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters ein Funktionstyp überschreitet die Grenze von {MAX_FUNC_TYPE_VALUES} Parametern +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results ein Funktionstyp überschreitet die Grenze von {MAX_FUNC_TYPE_VALUES} Ergebnissen @msg parameter `{k}`: {what} Parameter `{k}`: {what} @msg parameter `{name}`: {what} Parameter `{name}`: {what} @msg plug-in parameters must be a JSON object die Plug-in-Parameter müssen ein JSON-Objekt sein @@ -6944,6 +6958,11 @@ axis Y Axis Y-Achse @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` und `maxItems` müssen 0-{MAX_LIST} sein, `maxItems` mindestens 1, und der Standardwert muss so viele Einträge haben @msg `name` must be a string `name` muss eine Zeichenkette sein @msg `opacity` must be a number `opacity` muss eine Zahl sein +@msg `opacity` must be a number from 0 to 100 `opacity` muss eine Zahl von 0 bis 100 sein +@msg `opacity` must be true or false `opacity` muss true oder false sein +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke Textzeichen haben keine eigene Deckkraft: Fügen Sie mit „Neue Fläche hinzufügen“ oder „Neue Kontur hinzufügen“ im Bedienfeld „Aussehen“ eine Fläche oder Kontur hinzu +@msg an object selected in a symbol instance has no fill or stroke opacity of its own ein in einer Symbolinstanz ausgewähltes Objekt hat keine eigene Flächen- oder Konturdeckkraft +@msg no target has that fill or stroke to take the opacity kein Ziel hat diese Fläche oder Kontur, die die Deckkraft übernehmen könnte @msg `type` must be "path" or "compound" `type` muss "path" oder "compound" sein @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` muss 1-{MAX_UNIT} druckbare Zeichen haben @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` muss 1 bis {MAX_CONDITION_VALUES} Werte für `{other}` nennen @@ -9373,6 +9392,7 @@ breakText Glyphs Glyphen @msg give a pattern name or select an object painted with a pattern geben Sie einen Musternamen an, oder wählen Sie ein mit einem Muster gefärbtes Objekt aus @msg give at least one of clip, invert, disabled, linked geben Sie mindestens eines von clip, invert, disabled, linked an @msg give color, none, swatch or gradient geben Sie color, none, swatch oder gradient an +@msg give color, none, swatch, gradient or opacity geben Sie color, none, swatch, gradient oder opacity an @msg give dataBase64 geben Sie dataBase64 an @msg give either at (a click) or area (a path drawn around the overlaps) geben Sie entweder at (einen Klick) oder area (einen um die Überlappungen gezeichneten Pfad) an @msg give formats or a preset, not both geben Sie formats oder eine Vorgabe an, nicht beides diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ea7eb53703..b86986da49 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -881,6 +881,7 @@ font-technology Variable Μεταβλητές Direct Selection Tool Άμεση επιλογή (Direct Selection Tool) Direction Handles Λαβές κατεύθυνσης Disable Auto Add/Delete Απενεργοποίηση αυτόματης προσθήκης/διαγραφής + Delete Removes Anchor Points and Keeps Paths Joined Το Delete αφαιρεί σημεία αγκύρωσης και διατηρεί τις διαδρομές ενωμένες Interpolate Control Points When Moving Anchors Παρεμβολή λαβών κατεύθυνσης κατά τη μετακίνηση σημείων αγκύρωσης Disable Opacity Mask Απενεργοποίηση μάσκας αδιαφάνειας Discard Απόρριψη @@ -2089,6 +2090,12 @@ font-technology Variable Μεταβλητές {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}· {size}· {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable η ανάλυση δεν είναι διαθέσιμη + estimated memory {memory} εκτιμώμενη μνήμη {memory} + memory unavailable η μνήμη δεν είναι διαθέσιμη + Unknown format Άγνωστη μορφή {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2142,6 +2149,7 @@ font-technology Variable Μεταβλητές On Ενεργό Only Web Colors Μόνο χρώματα ιστού Opacity Αδιαφάνεια + Show Opacity Εμφάνιση αδιαφάνειας Opacity Mask Μάσκα αδιαφάνειας Opacity: Αδιαφάνεια: Open Άνοιγμα @@ -3940,6 +3948,9 @@ digits Malayalam Μαλαγιάλαμ Scale Artwork with Artboard Κλιμάκωση σχεδίου μαζί με τον πίνακα σχεδίασης Artboards: {n} Πίνακες σχεδίασης: {n} Rearrange All Artboards… Αναδιάταξη όλων των πινάκων σχεδίασης… + Rearrange… Αναδιάταξη… + Selected Artboards: {n} Επιλεγμένοι πίνακες σχεδίασης: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Κάντε κλικ στον καμβά για να τοποθετήσετε τους πίνακες σχεδίασης (Esc για ακύρωση) Recall Selection Ανάκληση επιλογής RECENT ΠΡΟΣΦΑΤΑ Recent Colors Πρόσφατα χρώματα @@ -4144,6 +4155,7 @@ digits Malayalam Μαλαγιάλαμ A two-finger rotate gesture on a trackpad rotates the canvas view. Μια κίνηση περιστροφής με δύο δάχτυλα σε επιφάνεια αφής περιστρέφει την προβολή του καμβά. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Το παρατεταμένο πάτημα ενός πλήκτρου εκτελεί το εργαλείο ή την εντολή της στήλης «Κρατήστε πατημένο» στις Συντομεύσεις πληκτρολογίου· ένα σύντομο πάτημα εκτελεί τη συνηθισμένη συντόμευσή του. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Πόσα δευτερόλεπτα πρέπει να μένει πατημένο ένα πλήκτρο πριν εκτελεστεί η συντόμευση παρατεταμένου πατήματος αντί για τη συνηθισμένη συντόμευσή του. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Το Delete αφαιρεί τα επιλεγμένα σημεία αγκύρωσης και προσαρμόζει ξανά την καμπύλη γύρω από το καθένα, αντί να ανοίγει τη διαδρομή εκεί. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Όταν μετακινείτε σημεία αγκύρωσης, κάθε καμπύλη με ένα μετακινημένο άκρο διατηρεί το σχήμα της σε σχέση με τα άκρα της. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Όσο κρατάτε πατημένη τη συντόμευση ενός εργαλείου, το εργαλείο είναι επιλεγμένο, και μετά επιλέγεται ξανά το προηγούμενο εργαλείο. Shows the bounding box while you move the selection or draw a shape. Εμφανίζει το πλαίσιο οριοθέτησης όσο μετακινείτε την επιλογή ή σχεδιάζετε ένα σχήμα. @@ -7314,6 +7326,8 @@ axis Y Axis Άξονας Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own χρειάζεται έγκριση: ζητά {0}, που ο χρήστης παραχωρεί όταν το εγκαθιστά μόνο του @msg not JSON: {e} δεν είναι JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) δεν είναι δυαδικό αρχείο WebAssembly (λείπει η κεφαλίδα \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters ένας τύπος συνάρτησης υπερβαίνει το όριο των {MAX_FUNC_TYPE_VALUES} παραμέτρων +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results ένας τύπος συνάρτησης υπερβαίνει το όριο των {MAX_FUNC_TYPE_VALUES} αποτελεσμάτων @msg parameter `{k}`: {what} παράμετρος `{k}`: {what} @msg parameter `{name}`: {what} παράμετρος `{name}`: {what} @msg plug-in parameters must be a JSON object οι παράμετροι του προσθέτου πρέπει να είναι αντικείμενο JSON @@ -7351,6 +7365,11 @@ axis Y Axis Άξονας Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many τα `minItems` και `maxItems` πρέπει να είναι 0-{MAX_LIST}, το `maxItems` τουλάχιστον 1 και η προεπιλογή να έχει τόσα στοιχεία @msg `name` must be a string το `name` πρέπει να είναι συμβολοσειρά @msg `opacity` must be a number το `opacity` πρέπει να είναι αριθμός +@msg `opacity` must be a number from 0 to 100 το `opacity` πρέπει να είναι αριθμός από 0 έως 100 +@msg `opacity` must be true or false το `opacity` πρέπει να είναι true ή false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke οι χαρακτήρες κειμένου δεν έχουν δική τους αδιαφάνεια: προσθέστε γέμισμα ή περίγραμμα με την Προσθήκη νέου γεμίσματος ή την Προσθήκη νέου περιγράμματος του πίνακα Εμφάνιση +@msg an object selected in a symbol instance has no fill or stroke opacity of its own ένα αντικείμενο επιλεγμένο σε στιγμιότυπο συμβόλου δεν έχει δική του αδιαφάνεια γεμίσματος ή περιγράμματος +@msg no target has that fill or stroke to take the opacity κανένας στόχος δεν έχει αυτό το γέμισμα ή περίγραμμα για να λάβει την αδιαφάνεια @msg `type` must be "path" or "compound" το `type` πρέπει να είναι "path" ή "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters το `unit` πρέπει να έχει 1-{MAX_UNIT} εκτυπώσιμους χαρακτήρες @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` το `visibleWhen` πρέπει να αναφέρει 1 έως {MAX_CONDITION_VALUES} τιμές για το `{other}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 586c53d87e..8982605040 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -927,6 +927,7 @@ font-technology Variable Variables Direct Selection Tool Herramienta Selección directa Direction Handles Manejadores de dirección Disable Auto Add/Delete Desactivar agregar/eliminar automático + Delete Removes Anchor Points and Keeps Paths Joined Suprimir quita puntos de ancla y mantiene los trazados unidos Interpolate Control Points When Moving Anchors Interpolar manejadores de dirección al mover puntos de ancla Disable Opacity Mask Desactivar máscara de opacidad Discard Descartar @@ -2479,6 +2480,12 @@ font-technology Variable Variables {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable resolución no disponible + estimated memory {memory} memoria estimada {memory} + memory unavailable memoria no disponible + Unknown format Formato desconocido {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2627,6 +2634,7 @@ font-technology Variable Variables One Point Perspective Preset 5 Preajuste de perspectiva de un punto 5 Only Web Colors Solo colores web Opacity Opacidad + Show Opacity Mostrar opacidad Opacity & Mask Define Knockout Shape La opacidad y la máscara definen la forma de exclusión Opacity Mask Máscara de opacidad Opacity Mask Info Información de máscara de opacidad @@ -3075,6 +3083,9 @@ digits Malayalam Malayálam Scale Artwork with Artboard Escalar la ilustración con la mesa de trabajo Artboards: {n} Mesas de trabajo: {n} Rearrange All Artboards… Reorganizar todas las mesas de trabajo… + Rearrange… Reorganizar… + Selected Artboards: {n} Mesas de trabajo seleccionadas: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Haz clic en el lienzo para colocar las mesas de trabajo (Esc cancela) Recall Selection Recuperar selección RECENT RECIENTES Recent Recientes @@ -3327,6 +3338,7 @@ digits Malayalam Malayálam A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto de giro con dos dedos en un trackpad gira la vista del lienzo. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Mantener pulsada una tecla ejecuta la herramienta o el comando de su columna Mantener pulsado en Métodos abreviados de teclado; una pulsación breve ejecuta su método abreviado habitual. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Cuántos segundos hay que mantener pulsada una tecla para que se ejecute su método abreviado de pulsación larga en lugar del habitual. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Suprimir quita los puntos de ancla seleccionados y reajusta la curva alrededor de cada uno, en lugar de abrir el trazado ahí. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Al mover puntos de ancla, cada curva con un extremo movido conserva su forma respecto a sus extremos. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantener pulsado el atajo de una herramienta la elige hasta que lo suelta, y después vuelve a elegirse la herramienta anterior. Shows the bounding box while you move the selection or draw a shape. Muestra el cuadro delimitador mientras mueve la selección o dibuja una forma. @@ -7300,6 +7312,8 @@ axis Y Axis Eje Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own requiere aprobación: pide {0}, que el usuario concede al instalarlo por separado @msg not JSON: {e} no es JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) no es un binario WebAssembly (falta el encabezado \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un tipo de función supera el límite de {MAX_FUNC_TYPE_VALUES} parámetros +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un tipo de función supera el límite de {MAX_FUNC_TYPE_VALUES} resultados @msg parameter `{k}`: {what} parámetro `{k}`: {what} @msg parameter `{name}`: {what} parámetro `{name}`: {what} @msg plug-in parameters must be a JSON object los parámetros del plugin deben ser un objeto JSON @@ -7337,6 +7351,11 @@ axis Y Axis Eje Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` y `maxItems` deben ser 0-{MAX_LIST}, `maxItems` al menos 1, y el valor predeterminado debe tener esa cantidad @msg `name` must be a string `name` debe ser una cadena @msg `opacity` must be a number `opacity` debe ser un número +@msg `opacity` must be a number from 0 to 100 `opacity` debe ser un número de 0 a 100 +@msg `opacity` must be true or false `opacity` debe ser true o false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke los caracteres de texto no tienen opacidad propia: agregue un relleno o un trazo con Agregar nuevo relleno o Agregar nuevo trazo del panel Apariencia +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un objeto seleccionado en una instancia de símbolo no tiene opacidad propia de relleno ni de trazo +@msg no target has that fill or stroke to take the opacity ningún destino tiene ese relleno o trazo para recibir la opacidad @msg `type` must be "path" or "compound" `type` debe ser "path" o "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` debe tener 1-{MAX_UNIT} caracteres imprimibles @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` debe indicar de 1 a {MAX_CONDITION_VALUES} valores para `{other}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 9dda197d2e..ea2ac9ecbd 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -358,6 +358,9 @@ Artboards Piirtoalustat Convert to Artboards Muunna piirtoalustoiksi Rearrange All Artboards… Järjestä kaikki piirtoalustat uudelleen… + Rearrange… Järjestä uudelleen… + Selected Artboards: {n} Valitut piirtoalustat: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Sijoita piirtoalustat napsauttamalla kangasta (Esc peruuttaa) Fit to Artwork Bounds Sovita kuvituksen rajoihin Fit to Selected Art Sovita valittuun kuvitukseen Graph Kaavio @@ -515,6 +518,7 @@ Fill & Stroke Täyttö ja viiva Fill Color Täyttöväri Opacity Peittävyys + Show Opacity Näytä peittävyys Stroke Color Viivan väri Fill Gradient Täytön liukuväri Stroke Gradient Viivan liukuväri @@ -3715,6 +3719,12 @@ theme Appearance Ulkoasu {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable tarkkuus ei saatavilla + estimated memory {memory} arvioitu muisti {memory} + memory unavailable muisti ei saatavilla + Unknown format Tuntematon muoto {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4163,6 +4173,7 @@ theme Appearance Ulkoasu Data Recovery Tietojen palautus Default Language Oletuskieli Disable Auto Add/Delete Poista automaattinen lisäys/poisto käytöstä + Delete Removes Anchor Points and Keeps Paths Joined Delete poistaa ankkuripisteet ja pitää polut yhtenäisinä Interpolate Control Points When Moving Anchors Interpoloi suuntakahvat siirrettäessä ankkuripisteitä Display All Blacks Accurately Näytä kaikki mustat tarkasti Display All Blacks as Rich Black Näytä kaikki mustat syvämustina @@ -4727,6 +4738,7 @@ font-technology Variable Muuttuvat A two-finger rotate gesture on a trackpad rotates the canvas view. Kahden sormen kiertoele kosketuslevyllä kiertää piirtopinnan näkymää. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Näppäimen pitäminen painettuna suorittaa työkalun tai komennon sen Pidä pohjassa -sarakkeesta Pikanäppäimissä; lyhyt painallus suorittaa sen tavallisen pikanäppäimen. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Kuinka monta sekuntia näppäintä on pidettävä painettuna, ennen kuin tavallisen pikanäppäimen sijaan suoritetaan sen pitkän painalluksen pikanäppäin. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete poistaa valitut ankkuripisteet ja sovittaa käyrän uudelleen kunkin ympärille sen sijaan, että avaisi polun siitä kohdasta. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kun siirrät ankkuripisteitä, jokainen käyrä, jonka toinen pää siirtyy, säilyttää muotonsa suhteessa päihinsä. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Työkalun pikanäppäimen pitäminen painettuna valitsee työkalun, kunnes päästät irti, ja sitten edellinen työkalu valitaan uudelleen. Shows the bounding box while you move the selection or draw a shape. Näyttää rajausruudun, kun siirrät valintaa tai piirrät muotoa. @@ -7391,6 +7403,8 @@ axis Y Axis Y-akseli @msg needs approval: it asks for {0}, which the user grants when installing it on its own vaatii hyväksynnän: se pyytää {0}, jotka käyttäjä myöntää asentaessaan sen erikseen @msg not JSON: {e} ei JSON-muotoa: {e} @msg not a WebAssembly binary (missing \\0asm header) ei WebAssembly-binääri (\\0asm-otsake puuttuu) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters funktiotyyppi ylittää {MAX_FUNC_TYPE_VALUES} parametrin rajan +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results funktiotyyppi ylittää {MAX_FUNC_TYPE_VALUES} tuloksen rajan @msg parameter `{k}`: {what} parametri `{k}`: {what} @msg parameter `{name}`: {what} parametri `{name}`: {what} @msg plug-in parameters must be a JSON object laajennuksen parametrien on oltava JSON-objekti @@ -7428,6 +7442,11 @@ axis Y Axis Y-akseli @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` ja `maxItems` on oltava 0-{MAX_LIST}, `maxItems` vähintään 1, ja oletusarvossa on oltava niin monta kohdetta @msg `name` must be a string `name` on oltava merkkijono @msg `opacity` must be a number `opacity` on oltava luku +@msg `opacity` must be a number from 0 to 100 `opacity` on oltava luku 0:sta 100:aan +@msg `opacity` must be true or false `opacity` on oltava true tai false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tekstin merkeillä ei ole omaa peittävyyttä: lisää täyttö tai viiva Ulkoasu-paneelin komennolla Lisää uusi täyttö tai Lisää uusi viiva +@msg an object selected in a symbol instance has no fill or stroke opacity of its own symbolin ilmentymästä valitulla objektilla ei ole omaa täytön tai viivan peittävyyttä +@msg no target has that fill or stroke to take the opacity millään kohteella ei ole tätä täyttöä tai viivaa, joka ottaisi peittävyyden @msg `type` must be "path" or "compound" `type` on oltava "path" tai "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit`-kentässä on oltava 1-{MAX_UNIT} tulostettavaa merkkiä @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`-kentässä on lueteltava 1-{MAX_CONDITION_VALUES} arvoa parametrille `{other}` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 34583f51fd..42789bcbdc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -930,6 +930,7 @@ font-technology Variable Variables Direct Selection Tool Outil Sélection directe Direction Handles Poignées de direction Disable Auto Add/Delete Désactiver l’ajout/suppression automatique + Delete Removes Anchor Points and Keeps Paths Joined Suppr supprime les points d’ancrage et garde les tracés joints Interpolate Control Points When Moving Anchors Interpoler les poignées de direction lors du déplacement des points d’ancrage Disable Opacity Mask Désactiver le masque d’opacité Discard Ignorer @@ -2467,6 +2468,12 @@ font-technology Variable Variables {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}, {size}, {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable résolution indisponible + estimated memory {memory} mémoire estimée {memory} + memory unavailable mémoire indisponible + Unknown format Format inconnu {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2615,6 +2622,7 @@ font-technology Variable Variables One Point Perspective Preset 5 Paramètre prédéfini de perspective à un point 5 Only Web Colors Couleurs Web uniquement Opacity Opacité + Show Opacity Afficher l’opacité Opacity & Mask Define Knockout Shape L’opacité et le masque définissent la forme de masquage Opacity Mask Masque d’opacité Opacity Mask Info Infos sur le masque d’opacité @@ -3063,6 +3071,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Mettre à l’échelle l’illustration avec le plan de travail Artboards: {n} Plans de travail : {n} Rearrange All Artboards… Réorganiser tous les plans de travail… + Rearrange… Réorganiser… + Selected Artboards: {n} Plans de travail sélectionnés ({n}) +@msg Click on the canvas to place the artboards (Esc cancels) Cliquez sur la zone de travail pour placer les plans de travail (Échap pour annuler) Recall Selection Rappeler la sélection RECENT RÉCENTS Recent Récents @@ -3315,6 +3326,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. Un geste de rotation à deux doigts sur un pavé tactile fait pivoter la vue de la zone de travail. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Maintenir une touche exécute l’outil ou la commande de sa colonne Maintenir dans Raccourcis clavier. Un appui bref exécute son raccourci habituel. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Durée, en secondes, pendant laquelle une touche doit être maintenue pour que son raccourci de maintien s’exécute à la place de son raccourci habituel. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Suppr supprime les points d’ancrage sélectionnés et réajuste la courbe autour de chacun, au lieu d’ouvrir le tracé à cet endroit. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quand vous déplacez des points d’ancrage, chaque courbe dont une extrémité bouge garde sa forme par rapport à ses extrémités. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Maintenir le raccourci d’un outil choisit cet outil jusqu’à ce que vous le relâchiez, puis l’outil précédent est de nouveau choisi. Shows the bounding box while you move the selection or draw a shape. Affiche le cadre de sélection pendant que vous déplacez la sélection ou dessinez une forme. @@ -7321,6 +7333,8 @@ axis Y Axis Axe Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own approbation requise : il demande {0}, que l’utilisateur accorde en l’installant seul @msg not JSON: {e} pas du JSON : {e} @msg not a WebAssembly binary (missing \\0asm header) pas un binaire WebAssembly (en-tête \\0asm absent) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un type de fonction dépasse la limite de {MAX_FUNC_TYPE_VALUES} paramètres +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un type de fonction dépasse la limite de {MAX_FUNC_TYPE_VALUES} résultats @msg parameter `{k}`: {what} paramètre `{k}` : {what} @msg parameter `{name}`: {what} paramètre `{name}` : {what} @msg plug-in parameters must be a JSON object les paramètres du plug-in doivent être un objet JSON @@ -7357,6 +7371,11 @@ axis Y Axis Axe Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` et `maxItems` doivent valoir 0-{MAX_LIST}, `maxItems` au moins 1, et la valeur par défaut doit en compter autant @msg `name` must be a string `name` doit être une chaîne @msg `opacity` must be a number `opacity` doit être un nombre +@msg `opacity` must be a number from 0 to 100 `opacity` doit être un nombre compris entre 0 et 100 +@msg `opacity` must be true or false `opacity` doit valoir true ou false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un objet sélectionné dans une occurrence de symbole n’a pas d’opacité de fond ou de contour propre +@msg no target has that fill or stroke to take the opacity aucune cible n’a ce fond ou ce contour pour recevoir l’opacité @msg `type` must be "path" or "compound" `type` doit valoir "path" ou "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` doit compter 1-{MAX_UNIT} caractères imprimables @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` doit indiquer 1 à {MAX_CONDITION_VALUES} valeurs pour `{other}` @@ -9527,6 +9546,7 @@ breakText Glyphs Glyphes @msg give a pattern name or select an object painted with a pattern indiquez un nom de motif ou sélectionnez un objet peint avec un motif @msg give at least one of clip, invert, disabled, linked indiquez au moins l’un des paramètres clip, invert, disabled, linked @msg give color, none, swatch or gradient indiquez color, none, swatch ou gradient +@msg give color, none, swatch, gradient or opacity indiquez color, none, swatch, gradient ou opacity @msg give dataBase64 indiquez dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) indiquez soit at (un clic), soit area (un tracé dessiné autour des chevauchements) @msg give exactly one of `path`, `data` and `dataBase64` indiquez exactement un paramètre parmi `path`, `data` et `dataBase64` diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 8ffa9de307..a23fcb4c42 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1073,6 +1073,7 @@ Direction: દિશા: Directives નિર્દેશો Disable Auto Add/Delete ઑટો ઍડ/ડિલીટ બંધ કરો + Delete Removes Anchor Points and Keeps Paths Joined Delete એન્કર બિંદુઓ દૂર કરે છે અને પાથને જોડાયેલા રાખે છે Interpolate Control Points When Moving Anchors એન્કર બિંદુઓ ખસેડતી વખતે દિશા હેન્ડલ્સ ઇન્ટરપોલેટ કરો Disable Opacity Mask ઓપેસિટી માસ્ક બંધ કરો Disable and Continue બંધ કરો અને ચાલુ રાખો @@ -2623,6 +2624,7 @@ One page per artboard. દરેક આર્ટબોર્ડ માટે એક પેજ. Only Web Colors માત્ર વેબ રંગો Opacity અપારદર્શકતા + Show Opacity અપારદર્શકતા બતાવો Opacity & Mask Define Knockout Shape અપારદર્શકતા અને માસ્ક નૉકઆઉટ આકાર વ્યાખ્યાયિત કરે છે Opacity Mask Info અપારદર્શકતા માસ્ક માહિતી Opacity Mask Options અપારદર્શકતા માસ્ક વિકલ્પો @@ -3081,6 +3083,9 @@ Rearrange All બધું ફરીથી ગોઠવો Rearrange All Artboards બધા આર્ટબોર્ડ ફરીથી ગોઠવો Rearrange All Artboards… બધા આર્ટબોર્ડ ફરીથી ગોઠવો… + Rearrange… ફરીથી ગોઠવો… + Selected Artboards: {n} પસંદ કરેલા આર્ટબોર્ડ: {n} +@msg Click on the canvas to place the artboards (Esc cancels) આર્ટબોર્ડ મૂકવા કેનવાસ પર ક્લિક કરો (Esc રદ કરે છે) Rearrange Artboards આર્ટબોર્ડ ફરીથી ગોઠવો Recall Selection પસંદગી યાદ કરો Recent Colors તાજેતરના રંગો @@ -3382,6 +3387,7 @@ arrowhead Feather પીંછું A two-finger rotate gesture on a trackpad rotates the canvas view. ટ્રેકપેડ પર બે આંગળીથી ફેરવવાનો હાવભાવ કેનવાસનું દૃશ્ય ફેરવે છે. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. કી દબાવી રાખવાથી કીબોર્ડ શૉર્ટકટમાં તેની હોલ્ડ કૉલમનું ટૂલ અથવા કમાન્ડ ચાલે છે; ટૂંકું દબાણ તેનો સામાન્ય શોર્ટકટ ચલાવે છે. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. કીનો હોલ્ડ શોર્ટકટ તેના સામાન્ય શોર્ટકટને બદલે ચાલે તે પહેલાં કીને કેટલી સેકન્ડ દબાવી રાખવી પડે. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete પસંદ કરેલા એન્કર પોઇન્ટ દૂર કરે છે અને ત્યાં પાથ ખોલવાને બદલે દરેકની આસપાસ વળાંકને ફરી ગોઠવે છે. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. જ્યારે તમે એન્કર પોઇન્ટ ખસેડો છો, ત્યારે એક ખસેલા છેડાવાળો દરેક વળાંક તેના છેડાઓની સાપેક્ષે પોતાનો આકાર જાળવે છે. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ટૂલની શોર્ટકટ કી દબાવી રાખવાથી છોડો ત્યાં સુધી તે ટૂલ પસંદ રહે છે, પછી અગાઉનું ટૂલ ફરી પસંદ થાય છે. Shows the bounding box while you move the selection or draw a shape. તમે પસંદગી ખસેડો કે આકાર દોરો ત્યારે બાઉન્ડિંગ બોક્સ બતાવે છે. @@ -5206,6 +5212,12 @@ antiAlias Sharp શાર્પ {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable રિઝોલ્યુશન ઉપલબ્ધ નથી + estimated memory {memory} અંદાજિત મેમરી {memory} + memory unavailable મેમરી ઉપલબ્ધ નથી + Unknown format અજ્ઞાત ફોર્મેટ {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0cf6ac8ac8..c9f163a38e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1746,6 +1746,7 @@ arrowhead Feather पंख Direction: दिशा: Directives निर्देश Disable Auto Add/Delete ऑटो जोड़ना/हटाना अक्षम करें + Delete Removes Anchor Points and Keeps Paths Joined Delete एंकर पॉइंट हटाता है और पाथ को जुड़ा रखता है Interpolate Control Points When Moving Anchors एंकर पॉइंट खिसकाते समय निर्देशन हैंडल इंटरपोलेट करें Disable Opacity Mask ओपेसिटी मास्क अक्षम करें Discard डिस्कर्ड @@ -3734,6 +3735,7 @@ arrowhead Feather पंख One Point Perspective Preset 5 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 5 Only Web Colors केवल वेब रंग Opacity ओपेसिटी + Show Opacity ओपेसिटी दिखाएँ Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप Opacity Mask ओपेसिटी मास्क Opacity Mask Info ओपेसिटी मास्क की जानकारी @@ -3980,6 +3982,12 @@ arrowhead Feather पंख {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable रिज़ॉल्यूशन उपलब्ध नहीं + estimated memory {memory} अनुमानित मेमोरी {memory} + memory unavailable मेमोरी उपलब्ध नहीं + Unknown format अज्ञात फ़ॉर्मेट {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4390,6 +4398,9 @@ arrowhead Feather पंख Rearrange All सभी को फिर से व्यवस्थित करें Rearrange All Artboards सभी आर्टबोर्ड को फिर से व्यवस्थित करें Rearrange All Artboards… सभी आर्टबोर्ड को पुनर्व्यवस्थित करें… + Rearrange… फिर से व्यवस्थित करें… + Selected Artboards: {n} चुने गए आर्टबोर्ड: {n} +@msg Click on the canvas to place the artboards (Esc cancels) आर्टबोर्ड प्लेस करने के लिए कैनवास पर क्लिक करें (Esc से कैंसल करें) Rearrange Artboards रीरेंज आर्टबोर्ड Recall Selection सिलेक्शन वापस लाएँ Recent हाल के @@ -4710,6 +4721,7 @@ arrowhead Feather पंख A two-finger rotate gesture on a trackpad rotates the canvas view. ट्रैकपैड पर दो उंगलियों से घुमाने का जेस्चर कैनवास के व्यू को घुमाता है। Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. किसी कुंजी को दबाए रखने पर कीबोर्ड शॉर्टकट में उसके होल्ड कॉलम का टूल या कमांड चलता है; जल्दी दबाने पर उसका सामान्य शॉर्टकट चलता है। How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. किसी कुंजी को कितने सेकंड दबाए रखना होगा, ताकि उसके सामान्य शॉर्टकट के बजाय उसका होल्ड शॉर्टकट चले। + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete चुने गए एंकर पॉइंट हटाता है और वहाँ पाथ खोलने के बजाय हर एक के आसपास वक्र को फिर से फिट करता है। When you move anchor points, each curve with one moved end keeps its shape relative to its ends. जब आप एंकर पॉइंट हिलाते हैं, तो एक हिले हुए सिरे वाला हर वक्र अपने सिरों के सापेक्ष अपना आकार बनाए रखता है। Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. किसी टूल की शॉर्टकट कुंजी दबाए रखने पर वह टूल छोड़ने तक चुना रहता है, फिर पिछला टूल दोबारा चुना जाता है। Shows the bounding box while you move the selection or draw a shape. सिलेक्शन खिसकाते या आकार ड्रॉ करते समय बाउंडिंग बॉक्स दिखाता है। @@ -6538,6 +6550,11 @@ arrowhead Feather पंख @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` और `maxItems` 0-{MAX_LIST} होने चाहिए, `maxItems` कम से कम 1, और डिफ़ॉल्ट में उतने ही आइटम होने चाहिए @msg `name` must be a string `name` एक स्ट्रिंग होना चाहिए @msg `opacity` must be a number `opacity` एक संख्या होना चाहिए +@msg `opacity` must be a number from 0 to 100 `opacity` 0 से 100 तक की संख्या होना चाहिए +@msg `opacity` must be true or false `opacity` true या false होना चाहिए +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke टेक्स्ट के कैरेक्टर्स की अपनी ओपेसिटी नहीं होती: अपीयरेंस पैनल के नया फ़िल जोड़ें या नया स्ट्रोक जोड़ें से फ़िल या स्ट्रोक जोड़ें +@msg an object selected in a symbol instance has no fill or stroke opacity of its own सिंबल इंस्टेंस में सिलेक्ट किए गए ऑब्जेक्ट की अपनी फ़िल या स्ट्रोक ओपेसिटी नहीं होती +@msg no target has that fill or stroke to take the opacity किसी भी टारगेट में वह फ़िल या स्ट्रोक नहीं है जो ओपेसिटी ले सके @msg `type` must be "path" or "compound" `type` "path" या "compound" होना चाहिए @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` में 1-{MAX_UNIT} प्रिंट करने योग्य वर्ण होने चाहिए @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` में `{other}` के लिए 1 से {MAX_CONDITION_VALUES} मान होने चाहिए @@ -7989,6 +8006,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg give at least one of clip, invert, disabled, linked कम से कम एक क्लिप, उलटा, विकलांग, लिंक्ड देना @msg give both `start` and `end` [x, y] (or neither) `start` और `end` दोनों [x, y] दें (या दोनों न दें) @msg give color, none, swatch or gradient color, none, swatch या gradient दें +@msg give color, none, swatch, gradient or opacity color, none, swatch, gradient या opacity दें @msg give corners of the path: anchors between two straight sides पाथ के कोने: दो सीधे पक्षों के बीच एंकर @msg give corners of the path: anchors where its sides meet at an angle पाथ के कोने: एंकर जहां इसके पक्ष एक कोण पर मिलते हैं @msg give dataBase64 dataBase64 दें @@ -8632,6 +8650,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg not a VectorCraft file: {0} एक वेक्टर क्रेफ्ट फ़ाइल नहीं: {0} @msg not a VectorCraft shortcut set (missing `overrides`) एक VectorCraft शॉर्टकट सेट नहीं है ( `overrides`) @msg not a WebAssembly binary (missing \\0asm header) WebAssembly बाइनरी नहीं है (\\0asm हेडर नहीं है) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters एक फ़ंक्शन टाइप में {MAX_FUNC_TYPE_VALUES} पैरामीटर की सीमा से अधिक पैरामीटर हैं +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results एक फ़ंक्शन टाइप में {MAX_FUNC_TYPE_VALUES} परिणामों की सीमा से अधिक परिणाम हैं @msg not a Word document: its compound file has no WordDocument stream एक वर्ड डॉक्यूमेंट नहीं: इसकी यौगिक फ़ाइल में WordDocument स्ट्रीम नहीं है @msg not a Word document: its main part is not a WordprocessingML document वर्ड डॉक्यूमेंट नहीं: इसका मुख्य हिस्सा वर्डप्रोसेसिंगएमएल डॉक्यूमेंट नहीं है @msg not a Word document: its package has no main document part नहीं एक वर्ड डॉक्यूमेंट: इसके पैकेज में कोई मुख्य डॉक्यूमेंट हिस्सा नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2cd00f0257..3db25083fc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1196,6 +1196,7 @@ arrowhead Target Céltábla Direction Handles Iránykezelő fogantyúk Direction: Irány: Disable Auto Add/Delete Automatikus hozzáadás és törlés kikapcsolása + Delete Removes Anchor Points and Keeps Paths Joined A Delete eltávolítja a horgonypontokat, és egyben tartja az útvonalakat Interpolate Control Points When Moving Anchors Iránykezelő fogantyúk interpolálása horgonypontok mozgatásakor Disable Opacity Mask Átlátszósági maszk kikapcsolása Discard Elvetés @@ -3107,6 +3108,7 @@ file-filter Templates Sablonok One Point Perspective Preset 5 Egypontos perspektíva, 5. előbeállítás Only Web Colors Csak webes színek Opacity Átlátszatlanság + Show Opacity Átlátszatlanság megjelenítése Opacity & Mask Define Knockout Shape Az átlátszatlanság és a maszk adja a kiütés alakját Opacity Mask Átlátszósági maszk Opacity Mask Info Átlátszósági maszk adatai @@ -3317,6 +3319,12 @@ file-filter Templates Sablonok {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable a felbontás nem érhető el + estimated memory {memory} becsült memória {memory} + memory unavailable a memória nem érhető el + Unknown format Ismeretlen formátum {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -3640,6 +3648,9 @@ mark-style Japanese Japán Rearrange All Összes átrendezése Rearrange All Artboards Összes rajztábla átrendezése Rearrange All Artboards… Összes rajztábla átrendezése… + Rearrange… Átrendezés… + Selected Artboards: {n} Kijelölt rajztáblák: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kattints a vászonra a rajztáblák elhelyezéséhez (Esc: mégse) Recall Selection Kijelölés visszahívása Recent Legutóbbi RECENT LEGUTÓBBI @@ -3915,6 +3926,7 @@ mark-style Japanese Japán A two-finger rotate gesture on a trackpad rotates the canvas view. Az érintőpadon végzett kétujjas forgató kézmozdulat elforgatja a vászon nézetét. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Egy billentyű nyomva tartása a Billentyűparancsok Nyomva tartás oszlopában lévő eszközt vagy parancsot futtatja; egy rövid lenyomás a szokásos billentyűparancsát futtatja. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hány másodpercig kell nyomva tartani egy billentyűt, hogy a szokásos billentyűparancsa helyett a nyomva tartásos billentyűparancsa fusson. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. A Delete eltávolítja a kijelölt horgonypontokat, és mindegyik körül újraigazítja a görbét ahelyett, hogy ott megnyitná az útvonalat. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Horgonypontok mozgatásakor minden olyan görbe, amelynek egyik vége elmozdul, megtartja az alakját a végeihez képest. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Egy eszköz billentyűparancsát lenyomva tartva az eszköz a felengedésig ki van választva, utána ismét az előző eszköz lesz kiválasztva. Shows the bounding box while you move the selection or draw a shape. Megjeleníti a befoglaló keretet, miközben a kijelölést mozgatja vagy alakzatot rajzol. @@ -7310,6 +7322,8 @@ axis Y Axis Y tengely @msg needs approval: it asks for {0}, which the user grants when installing it on its own jóváhagyás szükséges: ezt kéri: {0}, amit a felhasználó a külön telepítéskor ad meg @msg not JSON: {e} nem JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) nem WebAssembly bináris (hiányzik a \\0asm fejléc) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters egy függvénytípus paramétereinek száma meghaladja a korlátot ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results egy függvénytípus eredményeinek száma meghaladja a korlátot ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} `{k}` paraméter: {what} @msg parameter `{name}`: {what} `{name}` paraméter: {what} @msg plug-in parameters must be a JSON object a bővítmény paraméterei JSON-objektumot alkossanak @@ -7346,6 +7360,11 @@ axis Y Axis Y tengely @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many a `minItems` és a `maxItems` 0-{MAX_LIST} legyen, a `maxItems` legalább 1, és az alapértelmezett érték ennyi elemből álljon @msg `name` must be a string `name`: karakterlánc kell @msg `opacity` must be a number `opacity`: szám kell +@msg `opacity` must be a number from 0 to 100 `opacity`: 0 és 100 közötti szám kell +@msg `opacity` must be true or false `opacity`: true vagy false kell +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke a szöveg karaktereinek nincs saját átlátszatlansága: adjon hozzá kitöltést vagy körvonalat a Megjelenés panel Új kitöltés hozzáadása vagy Új körvonal hozzáadása parancsával +@msg an object selected in a symbol instance has no fill or stroke opacity of its own a szimbólumpéldányban kijelölt objektumnak nincs saját kitöltési vagy körvonal-átlátszatlansága +@msg no target has that fill or stroke to take the opacity egyik célnak sincs olyan kitöltése vagy körvonala, amely felvehetné az átlátszatlanságot @msg `type` must be "path" or "compound" `type`: "path" vagy "compound" kell @msg `unit` must be 1-{MAX_UNIT} printable characters a `unit` 1-{MAX_UNIT} nyomtatható karakter legyen @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` a `visibleWhen` 1-{MAX_CONDITION_VALUES} értéket adjon meg ehhez: `{other}` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7f832ee024..d603863507 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -438,6 +438,8 @@ @msg needs approval: it asks for {0}, which the user grants when installing it on its own memerlukan persetujuan: plug-in meminta {0}, yang diberikan pengguna saat memasangnya sendiri @msg not JSON: {e} bukan JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) bukan biner WebAssembly (header \\0asm tidak ada) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters sebuah tipe fungsi melampaui batas {MAX_FUNC_TYPE_VALUES} parameter +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results sebuah tipe fungsi melampaui batas {MAX_FUNC_TYPE_VALUES} hasil @msg parameter `{k}`: {what} parameter `{k}`: {what} @msg parameter `{name}`: {what} parameter `{name}`: {what} @msg plug-in parameters must be a JSON object parameter plug-in harus berupa objek JSON @@ -474,6 +476,11 @@ @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` dan `maxItems` harus 0-{MAX_LIST}, `maxItems` setidaknya 1, dan nilai default sebanyak itu @msg `name` must be a string `name` harus berupa string @msg `opacity` must be a number `opacity` harus berupa angka +@msg `opacity` must be a number from 0 to 100 `opacity` harus berupa angka dari 0 sampai 100 +@msg `opacity` must be true or false `opacity` harus true atau false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke karakter teks tidak memiliki opasitas sendiri: tambahkan isian atau guratan dengan Tambahkan isian baru atau Tambahkan guratan baru di panel Tampilan +@msg an object selected in a symbol instance has no fill or stroke opacity of its own objek yang dipilih dalam instans simbol tidak memiliki opasitas isian atau guratan sendiri +@msg no target has that fill or stroke to take the opacity tidak ada target yang memiliki isian atau guratan tersebut untuk menerima opasitas @msg `type` must be "path" or "compound" `type` harus "path" atau "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` harus berupa 1-{MAX_UNIT} karakter yang dapat dicetak @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` mencantumkan 1 sampai {MAX_CONDITION_VALUES} nilai untuk `{other}` @@ -968,6 +975,9 @@ Artboards Artboard Convert to Artboards Konversi ke artboard Rearrange All Artboards… Atur ulang semua artboard… + Rearrange… Atur ulang… + Selected Artboards: {n} Artboard terpilih: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klik kanvas untuk menempatkan artboard (Esc membatalkan) Fit to Artwork Bounds Sesuaikan ke batas karya seni Fit to Selected Art Sesuaikan ke karya seni terseleksi Graph Grafik @@ -1119,6 +1129,7 @@ Fill & Stroke Isian & stroke Fill Color Warna isian Opacity Opasitas + Show Opacity Tampilkan opasitas Stroke Color Warna stroke Fill Gradient Gradien isian Stroke Gradient Gradien stroke @@ -4135,6 +4146,12 @@ theme Appearance Tampilan {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable resolusi tidak tersedia + estimated memory {memory} perkiraan memori {memory} + memory unavailable memori tidak tersedia + Unknown format Format tidak dikenal {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4582,6 +4599,7 @@ theme Appearance Tampilan Data Recovery Pemulihan data Default Language Bahasa standar Disable Auto Add/Delete Nonaktifkan tambah/hapus otomatis + Delete Removes Anchor Points and Keeps Paths Joined Delete menghapus titik jangkar dan menjaga jalur tetap tersambung Interpolate Control Points When Moving Anchors Interpolasikan gagang arah saat memindahkan titik jangkar Display All Blacks Accurately Tampilkan semua warna hitam secara akurat Display All Blacks as Rich Black Tampilkan semua warna hitam sebagai rich black @@ -5140,6 +5158,7 @@ font-technology Variable Variabel A two-finger rotate gesture on a trackpad rotates the canvas view. Gerakan putar dua jari pada trackpad memutar tampilan kanvas. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Menahan tombol menjalankan alat atau perintah di kolom Tahan pada Pintasan papan ketik; tekanan singkat menjalankan pintasan biasanya. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Berapa detik tombol harus ditahan sebelum pintasan tahannya berjalan sebagai ganti pintasan biasanya. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete menghapus titik jangkar yang dipilih dan menyesuaikan ulang kurva di sekitar masing-masing, alih-alih membuka jalur di sana. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Saat Anda memindahkan titik jangkar, setiap kurva dengan satu ujung yang dipindahkan mempertahankan bentuknya terhadap ujung-ujungnya. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Menahan tombol pintasan alat memilih alat itu sampai Anda melepasnya, lalu alat sebelumnya dipilih lagi. Shows the bounding box while you move the selection or draw a shape. Menampilkan kotak pembatas saat Anda memindahkan seleksi atau menggambar bentuk. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b79d6dfa31..ad8c036109 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -930,6 +930,7 @@ font-technology Variable Variabili Direct Selection Tool Strumento Selezione diretta Direction Handles Maniglie di direzione Disable Auto Add/Delete Disattiva aggiunta/eliminazione automatica + Delete Removes Anchor Points and Keeps Paths Joined Canc rimuove i punti di ancoraggio e mantiene i tracciati uniti Interpolate Control Points When Moving Anchors Interpola le maniglie di direzione durante lo spostamento dei punti di ancoraggio Disable Opacity Mask Disattiva maschera di opacità Discard Scarta @@ -2521,6 +2522,12 @@ file-filter Templates Modelli {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable risoluzione non disponibile + estimated memory {memory} memoria stimata {memory} + memory unavailable memoria non disponibile + Unknown format Formato sconosciuto {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2669,6 +2676,7 @@ file-filter Templates Modelli One Point Perspective Preset 5 Preset prospettiva a un punto 5 Only Web Colors Solo colori web Opacity Opacità + Show Opacity Mostra opacità Opacity & Mask Define Knockout Shape Opacità e maschera definiscono la forma di foratura Opacity Mask Maschera di opacità Opacity Mask Info Informazioni maschera di opacità @@ -3123,6 +3131,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Scala la grafica con la tavola da disegno Artboards: {n} Tavole da disegno: {n} Rearrange All Artboards… Ridisponi tutte le tavole da disegno… + Rearrange… Ridisponi… + Selected Artboards: {n} Tavole da disegno selezionate: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Fai clic sull'area di lavoro per posizionare le tavole da disegno (Esc annulla) Recall Selection Richiama selezione RECENT RECENTI Recent Recenti @@ -3376,6 +3387,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto di rotazione con due dita sul trackpad ruota la vista dell'area di lavoro. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Tenere premuto un tasto esegue lo strumento o il comando della sua colonna Tieni premuto in Scelte rapide da tastiera; una pressione breve esegue la sua scorciatoia abituale. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Per quanti secondi va tenuto premuto un tasto prima che venga eseguita la sua scorciatoia a pressione prolungata invece di quella abituale. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Canc rimuove i punti di ancoraggio selezionati e riadatta la curva attorno a ciascuno, invece di aprire lì il tracciato. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quando sposti i punti di ancoraggio, ogni curva con un’estremità spostata mantiene la propria forma rispetto alle sue estremità. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Tenere premuta la scorciatoia di uno strumento lo sceglie finché non la rilasci, poi viene scelto di nuovo lo strumento precedente. Shows the bounding box while you move the selection or draw a shape. Mostra il riquadro di delimitazione mentre sposti la selezione o disegni una forma. @@ -6947,6 +6959,8 @@ axis Y Axis Asse Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own richiede approvazione: chiede {0}, che l’utente concede installandolo da solo @msg not JSON: {e} non è JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) non è un binario WebAssembly (manca l’intestazione \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un tipo di funzione supera il limite di {MAX_FUNC_TYPE_VALUES} parametri +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un tipo di funzione supera il limite di {MAX_FUNC_TYPE_VALUES} risultati @msg parameter `{k}`: {what} parametro `{k}`: {what} @msg parameter `{name}`: {what} parametro `{name}`: {what} @msg plug-in parameters must be a JSON object i parametri del plug-in devono essere un oggetto JSON @@ -6983,6 +6997,11 @@ axis Y Axis Asse Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` e `maxItems` devono essere 0-{MAX_LIST}, `maxItems` almeno 1, e il valore predefinito deve averne altrettanti @msg `name` must be a string `name` deve essere una stringa @msg `opacity` must be a number `opacity` deve essere un numero +@msg `opacity` must be a number from 0 to 100 `opacity` deve essere un numero compreso tra 0 e 100 +@msg `opacity` must be true or false `opacity` deve essere true o false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke i caratteri del testo non hanno un'opacità propria: aggiungi un riempimento o una traccia con Aggiungi nuovo riempimento o Aggiungi nuova traccia del pannello Aspetto +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un oggetto selezionato in un'istanza di simbolo non ha un'opacità propria di riempimento o di traccia +@msg no target has that fill or stroke to take the opacity nessuna destinazione ha quel riempimento o quella traccia per ricevere l'opacità @msg `type` must be "path" or "compound" `type` deve essere "path" o "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` deve avere 1-{MAX_UNIT} caratteri stampabili @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` deve elencare da 1 a {MAX_CONDITION_VALUES} valori per `{other}` @@ -9426,6 +9445,7 @@ breakText Glyphs Glifi @msg give a pattern name or select an object painted with a pattern indica il nome di un motivo o seleziona un oggetto dipinto con un motivo @msg give at least one of clip, invert, disabled, linked indica almeno uno tra clip, invert, disabled, linked @msg give color, none, swatch or gradient indica color, none, swatch o gradient +@msg give color, none, swatch, gradient or opacity indica color, none, swatch, gradient o opacity @msg give dataBase64 indica dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) indica at (un clic) o area (un tracciato disegnato attorno alle sovrapposizioni) @msg give formats or a preset, not both indica formats o un predefinito, non entrambi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a86b292640..4d3c6c5ee9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -413,6 +413,9 @@ digits Malayalam マラヤーラム数字 Artboards アートボード Convert to Artboards アートボードに変換 Rearrange All Artboards… すべてのアートボードを再配置… + Rearrange… 再配置… + Selected Artboards: {n} 選択したアートボード: {n} +@msg Click on the canvas to place the artboards (Esc cancels) キャンバスをクリックしてアートボードを配置します (Esc でキャンセル) Fit to Artwork Bounds アートワーク境界に合わせる Fit to Selected Art 選択オブジェクトに合わせる Graph グラフ @@ -583,6 +586,7 @@ digits Malayalam マラヤーラム数字 Side Length: 辺の長さ: Make Sides Equal 辺の長さをそろえる Opacity 不透明度 + Show Opacity 不透明度を表示 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: Stroke Color カラー (線) @@ -1694,6 +1698,7 @@ antiAlias Sharp シャープ Dimensions 寸法 Direct Selection Tool ダイレクト選択ツール Disable Auto Add/Delete 自動追加/削除機能を使用しない + Delete Removes Anchor Points and Keeps Paths Joined Delete でアンカーポイントを削除してパスをつなげたままにする Interpolate Control Points When Moving Anchors アンカーポイントの移動時に方向線ハンドルを補間 Disable Opacity Mask 不透明マスクを無効にする Discard 破棄 @@ -2704,6 +2709,12 @@ antiAlias Sharp シャープ {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}、{size}、{detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 解像度を取得できません + estimated memory {memory} 推定メモリ {memory} + memory unavailable メモリを取得できません + Unknown format 不明な形式 {kind}, {instances} {kind}、{instances} {kind}, {rows} × {cols} {kind}、{rows} × {cols} {grid}, {instances} {grid}、{instances} @@ -3344,6 +3355,7 @@ mark-style Japanese 日本式 A two-finger rotate gesture on a trackpad rotates the canvas view. トラックパッドで 2 本指の回転ジェスチャーをすると、カンバスの表示が回転します。 Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. キーを長押しすると、キーボードショートカットの長押し列にあるツールまたはコマンドを実行します。短く押すと通常のショートカットを実行します。 How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 通常のショートカットの代わりに長押しショートカットを実行するまで、キーを押し続ける秒数です。 + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete キーで選択したアンカーポイントを削除し、パスをそこで開かずに、各ポイントの周りの曲線を合わせ直します。 When you move anchor points, each curve with one moved end keeps its shape relative to its ends. アンカーポイントを移動すると、一方の端が移動した各曲線は、両端に対する形状を保ちます。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ツールのショートカットキーを押している間はそのツールを選び、離すと前のツールに戻ります。 Shows the bounding box while you move the selection or draw a shape. 選択範囲の移動中や図形の描画中にバウンディングボックスを表示します。 @@ -7022,6 +7034,8 @@ axis Y Axis Y 軸 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 承認が必要です: {0} を要求しています。これはユーザーが単独でインストールするときに許可します @msg not JSON: {e} JSON ではありません: {e} @msg not a WebAssembly binary (missing \\0asm header) WebAssembly バイナリではありません (\\0asm ヘッダーがありません) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 関数型のパラメーター数が上限の {MAX_FUNC_TYPE_VALUES} 個を超えています +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 関数型の結果の数が上限の {MAX_FUNC_TYPE_VALUES} 個を超えています @msg parameter `{k}`: {what} パラメーター `{k}`: {what} @msg parameter `{name}`: {what} パラメーター `{name}`: {what} @msg plug-in parameters must be a JSON object プラグインのパラメーターは JSON オブジェクトにしてください @@ -7058,6 +7072,11 @@ axis Y Axis Y 軸 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` と `maxItems` は 0-{MAX_LIST}、`maxItems` は 1 以上にし、デフォルト値の項目数をその範囲にしてください @msg `name` must be a string `name` は文字列にしてください @msg `opacity` must be a number `opacity` には数値を指定してください +@msg `opacity` must be a number from 0 to 100 `opacity` には 0 から 100 までの数値を指定してください +@msg `opacity` must be true or false `opacity` には true または false を指定してください +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 文字には独自の不透明度がありません。アピアランスパネルの「新規塗りを追加」または「新規線を追加」で塗りまたは線を追加してください +@msg an object selected in a symbol instance has no fill or stroke opacity of its own シンボルインスタンス内で選択したオブジェクトには、塗りや線の独自の不透明度がありません +@msg no target has that fill or stroke to take the opacity 不透明度を適用できる塗りまたは線を持つ対象がありません @msg `type` must be "path" or "compound" `type` は "path" または "compound" にしてください @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` は印刷可能な 1-{MAX_UNIT} 文字にしてください @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` には `{other}` の値を 1 から {MAX_CONDITION_VALUES} 個指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8a5b40ecc3..2372e72693 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2496,6 +2496,9 @@ Artboards სამუშაო დაფები Convert to Artboards სამუშაო დაფებად გარდაქმნა Rearrange All Artboards… ყველა სამუშაო დაფის გადალაგება… + Rearrange… გადალაგება… + Selected Artboards: {n} მონიშნული სამუშაო დაფები: {n} +@msg Click on the canvas to place the artboards (Esc cancels) დაწკაპეთ ტილოზე სამუშაო დაფების განსათავსებლად (Esc აუქმებს) Fit to Artwork Bounds ნახატის საზღვრებზე მორგება Fit to Selected Art მონიშნულ ნახატზე მორგება Graph დიაგრამა @@ -2650,6 +2653,7 @@ Fill & Stroke შევსება და კონტური Fill Color შევსების ფერი Opacity გაუმჭვირვალობა + Show Opacity გაუმჭვირვალობის ჩვენება Stroke Color კონტურის ფერი Fill Gradient შევსების გრადიენტი Stroke Gradient კონტურის გრადიენტი @@ -5538,6 +5542,12 @@ theme Appearance იერსახე {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable გარჩევადობა მიუწვდომელია + estimated memory {memory} სავარაუდო მეხსიერება {memory} + memory unavailable მეხსიერება მიუწვდომელია + Unknown format უცნობი ფორმატი {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -5986,6 +5996,7 @@ theme Appearance იერსახე Data Recovery მონაცემების აღდგენა Default Language ნაგულისხმევი ენა Disable Auto Add/Delete ავტომატური დამატება/წაშლის გამორთვა + Delete Removes Anchor Points and Keeps Paths Joined Delete შლის ღუზის წერტილებს და ინარჩუნებს კონტურებს შეერთებულად Interpolate Control Points When Moving Anchors სახელურების ინტერპოლაცია საყრდენი წერტილების გადაადგილებისას Display All Blacks Accurately ყველა შავის ზუსტად ჩვენება Display All Blacks as Rich Black ყველა შავის მდიდარ შავად ჩვენება @@ -6521,6 +6532,7 @@ font-technology Variable ცვლადი A two-finger rotate gesture on a trackpad rotates the canvas view. ტრეკპადზე ორი თითით მობრუნების ჟესტი ტილოს ხედს აბრუნებს. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. კლავიშის ხანგრძლივი დაჭერა უშვებს ხელსაწყოს ან ბრძანებას კლავიატურის მალსახმობების დაჭერის სვეტიდან; მოკლე დაჭერა უშვებს მის ჩვეულ მალსახმობს. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. რამდენი წამი უნდა იყოს კლავიში დაჭერილი, სანამ ჩვეული მალსახმობის ნაცვლად მისი ხანგრძლივი დაჭერის მალსახმობი გაეშვება. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete შლის არჩეულ ღუზის წერტილებს და თითოეულის გარშემო მრუდს ხელახლა არგებს, ნაცვლად იმისა, რომ იქ კონტური გახსნას. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. როცა ღუზის წერტილებს გადაადგილებთ, ყოველი მრუდი, რომლის ერთი ბოლოც გადაადგილდა, ინარჩუნებს ფორმას თავის ბოლოებთან მიმართებით. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. სანამ ხელსაწყოს მალსახმობ კლავიშს დაჭერილს გიჭირავთ, ეს ხელსაწყოა არჩეული; კლავიშის აშვების შემდეგ ისევ წინა ხელსაწყო აირჩევა. Shows the bounding box while you move the selection or draw a shape. აჩვენებს შემომსაზღვრელ ჩარჩოს, სანამ მონიშნულს გადაადგილებთ ან ფიგურას ხატავთ. @@ -9429,6 +9441,8 @@ axis Y Axis Y ღერძი @msg needs approval: it asks for {0}, which the user grants when installing it on its own საჭიროებს დამტკიცებას: ითხოვს {0}-ს, რასაც მომხმარებელი მისი ცალკე დაყენებისას აძლევს @msg not JSON: {e} არ არის JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) არ არის WebAssembly-ის ბინარული ფაილი (აკლია \\0asm სათაური) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters ფუნქციის ტიპი აჭარბებს {MAX_FUNC_TYPE_VALUES} პარამეტრის ლიმიტს +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results ფუნქციის ტიპი აჭარბებს {MAX_FUNC_TYPE_VALUES} შედეგის ლიმიტს @msg parameter `{k}`: {what} პარამეტრი `{k}`: {what} @msg parameter `{name}`: {what} პარამეტრი `{name}`: {what} @msg plug-in parameters must be a JSON object პლაგინის პარამეტრები JSON ობიექტი უნდა იყოს @@ -9466,6 +9480,11 @@ axis Y Axis Y ღერძი @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` და `maxItems` უნდა იყოს 0-{MAX_LIST}, `maxItems` მინიმუმ 1, ხოლო ნაგულისხმევ მნიშვნელობაში უნდა იყოს ამდენი ელემენტი @msg `name` must be a string `name` უნდა იყოს სტრიქონი @msg `opacity` must be a number `opacity` უნდა იყოს რიცხვი +@msg `opacity` must be a number from 0 to 100 `opacity` უნდა იყოს რიცხვი 0-დან 100-მდე +@msg `opacity` must be true or false `opacity` უნდა იყოს true ან false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke ტექსტის სიმბოლოებს საკუთარი გაუმჭვირვალობა არ აქვთ: დაამატეთ შევსება ან კონტური იერსახის პანელის ბრძანებით ახალი შევსების დამატება ან ახალი კონტურის დამატება +@msg an object selected in a symbol instance has no fill or stroke opacity of its own სიმბოლოს ეგზემპლარში არჩეულ ობიექტს შევსების ან კონტურის საკუთარი გაუმჭვირვალობა არ აქვს +@msg no target has that fill or stroke to take the opacity არცერთ სამიზნეს არ აქვს ის შევსება ან კონტური, რომელიც გაუმჭვირვალობას მიიღებს @msg `type` must be "path" or "compound" `type` უნდა იყოს "path" ან "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` უნდა შედგებოდეს 1-{MAX_UNIT} დასაბეჭდი სიმბოლოსგან @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`-ში `{other}`-ისთვის უნდა იყოს 1-დან {MAX_CONDITION_VALUES}-მდე მნიშვნელობა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a39c8bbc27..e1fbe138cf 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -406,6 +406,9 @@ digits Malayalam 말라얄람어 Artboards 아트보드 Convert to Artboards 아트보드로 변환 Rearrange All Artboards… 모든 아트보드 재정렬… + Rearrange… 재정렬… + Selected Artboards: {n} 선택한 아트보드: {n} +@msg Click on the canvas to place the artboards (Esc cancels) 캔버스를 클릭하여 아트보드를 배치하세요(Esc로 취소) Fit to Artwork Bounds 아트워크 경계에 맞추기 Fit to Selected Art 선택한 아트에 맞추기 Graph 그래프 @@ -576,6 +579,7 @@ digits Malayalam 말라얄람어 Side Length: 변 길이: Make Sides Equal 변 길이 같게 Opacity 불투명도 + Show Opacity 불투명도 표시 Pie End Angle: 파이 끝 각도: Pie Start Angle: 파이 시작 각도: Stroke Color 선 색상 @@ -1684,6 +1688,7 @@ antiAlias Sharp 날카롭게 Dimensions 치수 Direct Selection Tool 직접 선택 도구 Disable Auto Add/Delete 자동 추가/삭제 사용 안 함 + Delete Removes Anchor Points and Keeps Paths Joined Delete로 고정점을 제거하고 패스를 연결된 상태로 유지 Interpolate Control Points When Moving Anchors 앵커 포인트 이동 시 방향 핸들 보간 Disable Opacity Mask 불투명 마스크 사용 안 함 Discard 삭제 @@ -2694,6 +2699,12 @@ antiAlias Sharp 날카롭게 {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 해상도를 알 수 없음 + estimated memory {memory} 예상 메모리 {memory} + memory unavailable 메모리를 알 수 없음 + Unknown format 알 수 없는 형식 {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -3333,6 +3344,7 @@ mark-style Japanese 일본식 A two-finger rotate gesture on a trackpad rotates the canvas view. 트랙패드에서 두 손가락으로 회전하는 동작을 하면 캔버스 보기가 회전합니다. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. 키를 누르고 있으면 키보드 단축키의 누르고 있기 열에 있는 도구나 명령이 실행되고, 짧게 누르면 평소 단축키가 실행됩니다. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 평소 단축키 대신 길게 누르기 단축키가 실행되기 전까지 키를 누르고 있어야 하는 시간(초)입니다. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete는 선택한 고정점을 제거하고 각 점 주위의 곡선을 다시 맞추며, 그 위치에서 패스를 열지 않습니다. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 고정점을 이동하면 한쪽 끝이 이동한 각 곡선은 양 끝을 기준으로 모양을 유지합니다. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 도구의 바로 가기 키를 누르고 있는 동안 그 도구가 선택되고, 키를 놓으면 이전 도구가 다시 선택됩니다. Shows the bounding box while you move the selection or draw a shape. 선택 영역을 이동하거나 모양을 그리는 동안 테두리 상자를 표시합니다. @@ -6919,6 +6931,8 @@ axis Y Axis Y축 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 승인이 필요합니다. {0}을(를) 요청하며, 사용자가 따로 설치할 때 허용합니다 @msg not JSON: {e} JSON이 아닙니다: {e} @msg not a WebAssembly binary (missing \\0asm header) WebAssembly 바이너리가 아닙니다(\\0asm 헤더 없음) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 함수 형식의 매개변수가 한도인 {MAX_FUNC_TYPE_VALUES}개를 초과합니다 +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 함수 형식의 결과가 한도인 {MAX_FUNC_TYPE_VALUES}개를 초과합니다 @msg parameter `{k}`: {what} 매개변수 `{k}`: {what} @msg parameter `{name}`: {what} 매개변수 `{name}`: {what} @msg plug-in parameters must be a JSON object 플러그인 매개변수는 JSON 개체여야 합니다 @@ -6955,6 +6969,11 @@ axis Y Axis Y축 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems`와 `maxItems`는 0-{MAX_LIST}, `maxItems`는 1 이상이어야 하며 기본값의 항목 수도 그 범위여야 합니다 @msg `name` must be a string `name`은(는) 문자열이어야 합니다 @msg `opacity` must be a number `opacity`은(는) 숫자여야 합니다 +@msg `opacity` must be a number from 0 to 100 `opacity`은(는) 0에서 100 사이의 숫자여야 합니다 +@msg `opacity` must be true or false `opacity`은(는) true 또는 false여야 합니다 +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 문자에는 자체 불투명도가 없습니다. 모양새 패널의 새 칠 추가 또는 새 선 추가로 칠이나 선을 추가하세요 +@msg an object selected in a symbol instance has no fill or stroke opacity of its own 심볼 인스턴스에서 선택한 개체에는 자체 칠 또는 선 불투명도가 없습니다 +@msg no target has that fill or stroke to take the opacity 불투명도를 적용할 해당 칠 또는 선이 있는 대상이 없습니다 @msg `type` must be "path" or "compound" `type`은(는) "path" 또는 "compound"여야 합니다 @msg `unit` must be 1-{MAX_UNIT} printable characters `unit`은(는) 인쇄 가능한 문자 1-{MAX_UNIT}자여야 합니다 @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`에는 `{other}`의 값을 1-{MAX_CONDITION_VALUES}개 나열해야 합니다 @@ -9306,6 +9325,7 @@ breakText Glyphs 글리프 @msg give a pattern name or select an object painted with a pattern 패턴 이름을 지정하거나 패턴으로 칠한 개체를 선택하세요 @msg give at least one of clip, invert, disabled, linked clip, invert, disabled, linked 중 하나 이상을 지정하세요 @msg give color, none, swatch or gradient color, none, swatch 또는 gradient를 지정하세요 +@msg give color, none, swatch, gradient or opacity color, none, swatch, gradient 또는 opacity를 지정하세요 @msg give dataBase64 dataBase64를 지정하세요 @msg give either at (a click) or area (a path drawn around the overlaps) at(클릭) 또는 area(겹친 부분 둘레에 그린 패스) 중 하나를 지정하세요 @msg give exactly one of `at`, `rect` and `points` `at`, `rect`, `points` 중 정확히 하나를 지정하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 02d65423c0..e89b75cdf0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -401,6 +401,8 @@ liquify-list-end {0}, {1} {0} en {1} @msg needs approval: it asks for {0}, which the user grants when installing it on its own goedkeuring nodig: de plug-in vraagt om {0}, wat de gebruiker toestaat wanneer hij die afzonderlijk installeert @msg not JSON: {e} geen JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) geen WebAssembly-binair bestand (de header \\0asm ontbreekt) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters een functietype overschrijdt de limiet van {MAX_FUNC_TYPE_VALUES} parameters +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results een functietype overschrijdt de limiet van {MAX_FUNC_TYPE_VALUES} resultaten @msg parameter `{k}`: {what} parameter `{k}`: {what} @msg parameter `{name}`: {what} parameter `{name}`: {what} @msg plug-in parameters must be a JSON object plug-in-parameters moeten een JSON-object zijn @@ -437,6 +439,11 @@ liquify-list-end {0}, {1} {0} en {1} @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` en `maxItems` moeten 0-{MAX_LIST} zijn, `maxItems` minstens 1, en de standaardwaarde zoveel items @msg `name` must be a string `name` moet een string zijn @msg `opacity` must be a number `opacity` moet een getal zijn +@msg `opacity` must be a number from 0 to 100 `opacity` moet een getal van 0 tot 100 zijn +@msg `opacity` must be true or false `opacity` moet true of false zijn +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tekens van tekst hebben geen eigen dekking: voeg een vulling of streek toe met Nieuwe vulling toevoegen of Nieuwe streek toevoegen in het deelvenster Uiterlijk +@msg an object selected in a symbol instance has no fill or stroke opacity of its own een object dat in een symboolinstantie is geselecteerd, heeft geen eigen dekking voor vulling of streek +@msg no target has that fill or stroke to take the opacity geen enkel doel heeft die vulling of streek om de dekking te krijgen @msg `type` must be "path" or "compound" `type` moet "path" of "compound" zijn @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` moet uit 1-{MAX_UNIT} afdrukbare tekens bestaan @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` noemt 1 tot {MAX_CONDITION_VALUES} waarden voor `{other}` @@ -954,6 +961,9 @@ liquify-list-end {0}, {1} {0} en {1} Artboards Tekengebieden Convert to Artboards Converteren naar tekengebieden Rearrange All Artboards… Alle tekengebieden herschikken… + Rearrange… Herschikken… + Selected Artboards: {n} Geselecteerde tekengebieden: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klik op het canvas om de tekengebieden te plaatsen (Esc annuleert) Fit to Artwork Bounds Op artworkgrenzen passend maken Fit to Selected Art Op geselecteerd artwork passend maken Graph Grafiek @@ -1105,6 +1115,7 @@ liquify-list-end {0}, {1} {0} en {1} Fill & Stroke Vulling en contour Fill Color Vulkleur Opacity Dekking + Show Opacity Dekking tonen Stroke Color Contourkleur Fill Gradient Vulverloop Stroke Gradient Contourverloop @@ -4132,6 +4143,12 @@ theme Appearance Vormgeving {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable resolutie niet beschikbaar + estimated memory {memory} geschat geheugen {memory} + memory unavailable geheugen niet beschikbaar + Unknown format Onbekend formaat {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4579,6 +4596,7 @@ theme Appearance Vormgeving Data Recovery Gegevensherstel Default Language Standaardtaal Disable Auto Add/Delete Automatisch toevoegen/verwijderen uitschakelen + Delete Removes Anchor Points and Keeps Paths Joined Delete verwijdert ankerpunten en houdt paden verbonden Interpolate Control Points When Moving Anchors Richtingsgrepen interpoleren bij het verplaatsen van ankerpunten Display All Blacks Accurately Alle zwarttinten nauwkeurig weergeven Display All Blacks as Rich Black Alle zwarttinten weergeven als rijk zwart @@ -5139,6 +5157,7 @@ font-technology Variable Variabel A two-finger rotate gesture on a trackpad rotates the canvas view. Een draaigebaar met twee vingers op een trackpad draait de weergave van het canvas. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Als u een toets vasthoudt, wordt het gereedschap of de opdracht uit de kolom Houd in Sneltoetsen uitgevoerd; kort drukken voert de gewone sneltoets uit. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hoeveel seconden u een toets moet vasthouden voordat de vasthoudsneltoets wordt uitgevoerd in plaats van de gewone sneltoets. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete verwijdert de geselecteerde ankerpunten en past de curve rond elk ervan opnieuw aan, in plaats van het pad daar te openen. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Als u ankerpunten verplaatst, behoudt elke curve met één verplaatst uiteinde zijn vorm ten opzichte van zijn uiteinden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Als u de sneltoets van een gereedschap ingedrukt houdt, is dat gereedschap gekozen tot u loslaat, en daarna wordt het vorige gereedschap weer gekozen. Shows the bounding box while you move the selection or draw a shape. Toont het begrenzingskader terwijl u de selectie verplaatst of een vorm tekent. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1a802a143c..815b7ee6e1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -311,6 +311,9 @@ Artboards Obszary kompozycji Convert to Artboards Konwertuj na obszary kompozycji Rearrange All Artboards… Przestaw wszystkie obszary kompozycji… + Rearrange… Przestaw… + Selected Artboards: {n} Zaznaczone obszary kompozycji: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kliknij obszar roboczy, aby umieścić obszary kompozycji (Esc anuluje) Fit to Artwork Bounds Dopasuj do granic kompozycji Fit to Selected Art Dopasuj do zaznaczonej kompozycji Graph Wykres @@ -477,6 +480,7 @@ Fill & Stroke Wypełnienie i obrys Fill Color Kolor wypełnienia Opacity Krycie + Show Opacity Pokaż krycie Stroke Color Kolor obrysu Fill Gradient Gradient wypełnienia Stroke Gradient Gradient obrysu @@ -3657,6 +3661,12 @@ theme Appearance Wygląd {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable rozdzielczość niedostępna + estimated memory {memory} szacowana pamięć {memory} + memory unavailable pamięć niedostępna + Unknown format Nieznany format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -4111,6 +4121,7 @@ theme Appearance Wygląd Data Recovery Odzyskiwanie danych Default Language Język domyślny Disable Auto Add/Delete Wyłącz automatyczne dodawanie/usuwanie + Delete Removes Anchor Points and Keeps Paths Joined Delete usuwa punkty kontrolne i zachowuje ścieżki połączone Interpolate Control Points When Moving Anchors Interpoluj uchwyty kierunkowe podczas przesuwania punktów kontrolnych Display All Blacks Accurately Wyświetlaj wszystkie czernie dokładnie Display All Blacks as Rich Black Wyświetlaj wszystkie czernie jako czerń głęboką @@ -4660,6 +4671,7 @@ font-technology Variable Zmienne A two-finger rotate gesture on a trackpad rotates the canvas view. Gest obrotu dwoma palcami na gładziku obraca widok obszaru roboczego. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Przytrzymanie klawisza uruchamia narzędzie lub polecenie z jego kolumny Przytrzymaj w Skrótach klawiaturowych; krótkie naciśnięcie uruchamia jego zwykły skrót. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Ile sekund trzeba przytrzymać klawisz, zanim zamiast zwykłego skrótu zostanie uruchomiony jego skrót przytrzymania. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete usuwa zaznaczone punkty kontrolne i ponownie dopasowuje krzywą wokół każdego z nich, zamiast otwierać tam ścieżkę. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Podczas przesuwania punktów kontrolnych każda krzywa z jednym przesuniętym końcem zachowuje kształt względem swoich końców. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Przytrzymanie skrótu narzędzia wybiera je do momentu puszczenia klawisza, a potem ponownie wybierane jest poprzednie narzędzie. Shows the bounding box while you move the selection or draw a shape. Pokazuje obwiednię podczas przesuwania zaznaczenia lub rysowania kształtu. @@ -7180,6 +7192,8 @@ axis Y Axis Oś Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own wymaga zatwierdzenia: prosi o {0}, na co użytkownik zezwala, instalując ją osobno @msg not JSON: {e} to nie jest JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) to nie jest plik binarny WebAssembly (brak nagłówka \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters typ funkcji ma więcej parametrów, niż pozwala limit ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results typ funkcji ma więcej wyników, niż pozwala limit ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} parametr `{k}`: {what} @msg parameter `{name}`: {what} parametr `{name}`: {what} @msg plug-in parameters must be a JSON object parametry wtyczki muszą być obiektem JSON @@ -7216,6 +7230,11 @@ axis Y Axis Oś Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` i `maxItems` muszą wynosić 0-{MAX_LIST}, `maxItems` co najmniej 1, a wartość domyślna musi mieć tyle elementów @msg `name` must be a string `name` musi być ciągiem znaków @msg `opacity` must be a number `opacity` musi być liczbą +@msg `opacity` must be a number from 0 to 100 `opacity` musi być liczbą od 0 do 100 +@msg `opacity` must be true or false `opacity` musi mieć wartość true lub false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke znaki tekstu nie mają własnego krycia: dodaj wypełnienie lub obrys poleceniem Dodaj nowe wypełnienie lub Dodaj nowy obrys w panelu Wygląd +@msg an object selected in a symbol instance has no fill or stroke opacity of its own obiekt zaznaczony w wystąpieniu symbolu nie ma własnego krycia wypełnienia ani obrysu +@msg no target has that fill or stroke to take the opacity żaden cel nie ma tego wypełnienia ani obrysu, które przyjęłoby krycie @msg `type` must be "path" or "compound" `type` musi mieć wartość "path" lub "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` musi mieć 1-{MAX_UNIT} drukowalnych znaków @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` musi podawać od 1 do {MAX_CONDITION_VALUES} wartości dla `{other}` @@ -9633,6 +9652,7 @@ breakText Glyphs Glify @msg give a pattern name or select an object painted with a pattern podaj nazwę wzorka albo zaznacz obiekt pomalowany wzorkiem @msg give at least one of clip, invert, disabled, linked podaj co najmniej jedno z: clip, invert, disabled, linked @msg give color, none, swatch or gradient podaj color, none, swatch lub gradient +@msg give color, none, swatch, gradient or opacity podaj color, none, swatch, gradient lub opacity @msg give dataBase64 podaj dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) podaj at (kliknięcie) albo area (ścieżkę narysowaną wokół nakładających się obszarów) @msg give formats or a preset, not both podaj formats albo ustawienie, nie oba naraz diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 108484d046..e08a9d24ea 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -854,6 +854,7 @@ antiAlias Sharp Nítido Direct Selection Tool Ferramenta Seleção Direta Direction Handles Alças de Direção Disable Auto Add/Delete Desativar Adicionar/Excluir Automático + Delete Removes Anchor Points and Keeps Paths Joined Delete Remove Pontos de Ancoragem e Mantém os Demarcadores Unidos Interpolate Control Points When Moving Anchors Interpolar Alças de Direção ao Mover Pontos de Ancoragem Disable Opacity Mask Desativar Máscara de Opacidade Discard Descartar @@ -2016,6 +2017,12 @@ antiAlias Sharp Nítido {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable resolução indisponível + estimated memory {memory} memória estimada {memory} + memory unavailable memória indisponível + Unknown format Formato desconhecido {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2149,6 +2156,7 @@ antiAlias Sharp Nítido One page per artboard. Uma página por mesa de trabalho. Only Web Colors Apenas Cores da Web Opacity Opacidade + Show Opacity Mostrar Opacidade Opacity & Mask Define Knockout Shape Opacidade e Máscara Definem Forma de Isolamento Opacity Mask Máscara de Opacidade Opacity Mask Info Informações da Máscara de Opacidade @@ -2555,6 +2563,9 @@ digits Malayalam Malaiala Scale Artwork with Artboard Dimensionar Arte com a Mesa de Trabalho Artboards: {n} Mesas de Trabalho: {n} Rearrange All Artboards… Reorganizar Todas as Mesas de Trabalho… + Rearrange… Reorganizar… + Selected Artboards: {n} Mesas de Trabalho Selecionadas: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Clique na tela para posicionar as mesas de trabalho (Esc cancela) Recall Selection Relembrar Seleção Recent Colors Cores Recentes Recent Files Arquivos Recentes @@ -2782,6 +2793,7 @@ digits Malayalam Malaiala A two-finger rotate gesture on a trackpad rotates the canvas view. Um gesto de rotação com dois dedos no trackpad gira a visualização da tela. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Manter uma tecla pressionada executa a ferramenta ou o comando da coluna Manter pressionado em Atalhos de Teclado; um toque rápido executa o atalho habitual. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Quantos segundos uma tecla precisa ficar pressionada até que seu atalho de pressionamento longo seja executado no lugar do atalho habitual. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete remove os pontos de ancoragem selecionados e reajusta a curva em torno de cada um, em vez de abrir o demarcador ali. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Ao mover pontos de ancoragem, cada curva com uma extremidade movida mantém sua forma em relação às extremidades. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Manter pressionado o atalho de uma ferramenta a escolhe até você soltar, e então a ferramenta anterior é escolhida de novo. Shows the bounding box while you move the selection or draw a shape. Mostra a caixa delimitadora enquanto você move a seleção ou desenha uma forma. @@ -7224,6 +7236,8 @@ axis Y Axis Eixo Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own precisa de aprovação: pede {0}, que o usuário concede ao instalá-lo separadamente @msg not JSON: {e} não é JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) não é um binário WebAssembly (falta o cabeçalho \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters um tipo de função excede o limite de {MAX_FUNC_TYPE_VALUES} parâmetros +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results um tipo de função excede o limite de {MAX_FUNC_TYPE_VALUES} resultados @msg parameter `{k}`: {what} parâmetro `{k}`: {what} @msg parameter `{name}`: {what} parâmetro `{name}`: {what} @msg plug-in parameters must be a JSON object os parâmetros do plug-in devem ser um objeto JSON @@ -7260,6 +7274,11 @@ axis Y Axis Eixo Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` e `maxItems` devem ser 0-{MAX_LIST}, `maxItems` pelo menos 1, e o valor padrão deve ter essa quantidade @msg `name` must be a string `name` deve ser uma string @msg `opacity` must be a number `opacity` deve ser um número +@msg `opacity` must be a number from 0 to 100 `opacity` deve ser um número de 0 a 100 +@msg `opacity` must be true or false `opacity` deve ser true ou false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke os caracteres do texto não têm opacidade própria: adicione um preenchimento ou traçado com Adicionar Novo Preenchimento ou Adicionar Novo Traçado do painel Aparência +@msg an object selected in a symbol instance has no fill or stroke opacity of its own um objeto selecionado em uma instância de símbolo não tem opacidade própria de preenchimento ou traçado +@msg no target has that fill or stroke to take the opacity nenhum destino tem esse preenchimento ou traçado para receber a opacidade @msg `type` must be "path" or "compound" `type` deve ser "path" ou "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` deve ter 1-{MAX_UNIT} caracteres imprimíveis @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` deve listar de 1 a {MAX_CONDITION_VALUES} valores para `{other}` @@ -9728,6 +9747,7 @@ swatch Yellow Green Verde-amarelado @msg give a pattern name or select an object painted with a pattern informe o nome de um padrão ou selecione um objeto pintado com um padrão @msg give at least one of clip, invert, disabled, linked informe pelo menos um de clip, invert, disabled, linked @msg give color, none, swatch or gradient informe color, none, swatch ou gradient +@msg give color, none, swatch, gradient or opacity informe color, none, swatch, gradient ou opacity @msg give dataBase64 informe dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) informe at (um clique) ou area (um caminho desenhado em volta das sobreposições) @msg give exactly one of `at`, `rect` and `points` informe exatamente um de `at`, `rect` e `points` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1a6def9fd3..75c8498cdb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -925,6 +925,7 @@ font-technology Variable Вариативные Direct Selection Tool Инструмент «Прямое выделение» Direction Handles Маркеры направления Disable Auto Add/Delete Отключить авто-добавление/удаление + Delete Removes Anchor Points and Keeps Paths Joined Delete удаляет опорные точки и оставляет контуры соединёнными Interpolate Control Points When Moving Anchors Интерполировать маркеры направления при перемещении опорных точек Disable Opacity Mask Отключить непрозрачную маску Discard Отменить @@ -2505,6 +2506,12 @@ file-filter Templates Шаблоны {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable разрешение недоступно + estimated memory {memory} оценка памяти {memory} + memory unavailable память недоступна + Unknown format Неизвестный формат {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2653,6 +2660,7 @@ file-filter Templates Шаблоны One Point Perspective Preset 5 Набор одноточечной перспективы 5 Only Web Colors Только web-цвета Opacity Непрозрачность + Show Opacity Показать непрозрачность Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания Opacity Mask Непрозрачная маска Opacity Mask Info Сведения о непрозрачной маске @@ -3105,6 +3113,9 @@ digits Malayalam Малаялам Scale Artwork with Artboard Масштабировать иллюстрацию вместе с монтажной областью Artboards: {n} Монтажные области: {n} Rearrange All Artboards… Переставить все монтажные области… + Rearrange… Переставить… + Selected Artboards: {n} Выбранные монтажные области: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Щёлкните холст, чтобы разместить монтажные области (Esc отменяет) Recall Selection Восстановить выделение RECENT ПОСЛЕДНИЕ Recent Последние @@ -3358,6 +3369,7 @@ digits Malayalam Малаялам A two-finger rotate gesture on a trackpad rotates the canvas view. Жест поворота двумя пальцами на трекпаде поворачивает вид холста. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Удержание клавиши запускает инструмент или команду из её столбца «Удерживать» в «Сочетаниях клавиш»; короткое нажатие запускает её обычное сочетание. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Сколько секунд нужно удерживать клавишу, прежде чем вместо её обычного сочетания сработает сочетание удержания. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete удаляет выбранные опорные точки и заново подгоняет кривую вокруг каждой из них, вместо того чтобы размыкать контур в этом месте. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. При перемещении опорных точек каждая кривая с одним перемещённым концом сохраняет форму относительно своих концов. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Пока вы удерживаете клавишу инструмента, он остаётся выбранным, а после отпускания снова выбирается предыдущий инструмент. Shows the bounding box while you move the selection or draw a shape. Показывает ограничивающую рамку, пока вы перемещаете выделение или рисуете фигуру. @@ -6946,6 +6958,8 @@ axis Y Axis Ось Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own требуется одобрение: он запрашивает {0}, что пользователь разрешает при отдельной установке @msg not JSON: {e} не JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) не двоичный файл WebAssembly (нет заголовка \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters у типа функции больше параметров, чем допускает предел ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results у типа функции больше результатов, чем допускает предел ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} параметр `{k}`: {what} @msg parameter `{name}`: {what} параметр `{name}`: {what} @msg plug-in parameters must be a JSON object параметры модуля должны быть объектом JSON @@ -6983,6 +6997,11 @@ axis Y Axis Ось Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` и `maxItems` должны быть 0-{MAX_LIST}, `maxItems` не меньше 1, а значение по умолчанию должно содержать столько элементов @msg `name` must be a string `name` должно быть строкой @msg `opacity` must be a number `opacity` должно быть числом +@msg `opacity` must be a number from 0 to 100 `opacity` должно быть числом от 0 до 100 +@msg `opacity` must be true or false `opacity` должно быть true или false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke у символов текста нет собственной непрозрачности: добавьте заливку или обводку командой «Добавить новую заливку» или «Добавить новую обводку» на панели «Оформление» +@msg an object selected in a symbol instance has no fill or stroke opacity of its own у объекта, выбранного в экземпляре символа, нет собственной непрозрачности заливки или обводки +@msg no target has that fill or stroke to take the opacity ни у одного объекта нет такой заливки или обводки, чтобы задать непрозрачность @msg `type` must be "path" or "compound" `type` должно быть "path" или "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` должно содержать 1-{MAX_UNIT} печатаемых символов @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` должно перечислять от 1 до {MAX_CONDITION_VALUES} значений для `{other}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ca7693019c..38d18adce4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -910,6 +910,7 @@ font-technology Variable Variabla Direct Selection Tool Direktmarkeringsverktyg Direction Handles Riktningshandtag Disable Auto Add/Delete Inaktivera Lägg till/radera automatiskt + Delete Removes Anchor Points and Keeps Paths Joined Delete tar bort ankarpunkter och håller banor sammanhängande Interpolate Control Points When Moving Anchors Interpolera riktningshandtag vid flyttning av ankarpunkter Disable Opacity Mask Inaktivera opacitetsmask Discard Släng @@ -2407,6 +2408,12 @@ font-technology Variable Variabla {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable upplösning inte tillgänglig + estimated memory {memory} uppskattat minne {memory} + memory unavailable minne inte tillgängligt + Unknown format Okänt format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2555,6 +2562,7 @@ font-technology Variable Variabla One Point Perspective Preset 5 Förinställning 5 för enpunktsperspektiv Only Web Colors Endast webbfärger Opacity Opacitet + Show Opacity Visa opacitet Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform Opacity Mask Opacitetsmask Opacity Mask Info Info om opacitetsmask @@ -2996,6 +3004,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Skala grafik med rityta Artboards: {n} Ritytor: {n} Rearrange All Artboards… Ordna om alla ritytor… + Rearrange… Ordna om… + Selected Artboards: {n} Markerade ritytor: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klicka på arbetsytan för att placera ritytorna (Esc avbryter) Recall Selection Hämta markering RECENT SENASTE Recent Senaste @@ -3247,6 +3258,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsgest med två fingrar på en styrplatta roterar arbetsytans vy. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Om du håller ned en tangent körs verktyget eller kommandot i dess Håll-kolumn i Kortkommandon; ett kort tryck kör dess vanliga kortkommando. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hur många sekunder en tangent måste hållas ned innan dess hållkortkommando körs i stället för dess vanliga kortkommando. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete tar bort de markerade ankarpunkterna och anpassar om kurvan runt var och en i stället för att öppna banan där. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. När du flyttar ankarpunkter behåller varje kurva med en flyttad ände sin form i förhållande till sina ändar. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. När du håller ned ett verktygs kortkommando är verktyget valt tills du släpper, och sedan väljs det föregående verktyget igen. Shows the bounding box while you move the selection or draw a shape. Visar avgränsningsramen medan du flyttar markeringen eller ritar en form. @@ -7367,6 +7379,11 @@ axis Y Axis Y-axel @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` och `maxItems` måste vara 0-{MAX_LIST}, `maxItems` minst 1, och standardvärdet måste ha så många poster @msg `name` must be a string `name` måste vara en sträng @msg `opacity` must be a number `opacity` måste vara ett tal +@msg `opacity` must be a number from 0 to 100 `opacity` måste vara ett tal från 0 till 100 +@msg `opacity` must be true or false `opacity` måste vara true eller false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tecken i text har ingen egen opacitet: lägg till en fyllning eller kontur med Lägg till ny fyllning eller Lägg till ny kontur i panelen Utseende +@msg an object selected in a symbol instance has no fill or stroke opacity of its own ett objekt som är markerat i en symbolinstans har ingen egen opacitet för fyllning eller kontur +@msg no target has that fill or stroke to take the opacity inget mål har den fyllningen eller konturen som kan ta emot opaciteten @msg `type` must be "path" or "compound" `type` måste vara "path" eller "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` måste ha 1-{MAX_UNIT} utskrivbara tecken @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` måste ange 1 till {MAX_CONDITION_VALUES} värden för `{other}` @@ -9327,6 +9344,7 @@ digits Hindi Hindi @msg give a pattern name or select an object painted with a pattern ange ett mönsternamn eller markera ett objekt som är målat med ett mönster @msg give at least one of clip, invert, disabled, linked ange minst en av clip, invert, disabled, linked @msg give color, none, swatch or gradient ange color, none, swatch eller gradient +@msg give color, none, swatch, gradient or opacity ange color, none, swatch, gradient eller opacity @msg give dataBase64 ange dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) ange antingen at (ett klick) eller area (en bana ritad runt överlappningarna) @msg give formats or a preset, not both ange formats eller en förinställning, inte båda @@ -9623,6 +9641,8 @@ digits Hindi Hindi @msg not a stored or deflated central record inte en central katalogpost av typen stored eller deflated @msg not a valid SVGZ file: {e} inte en giltig SVGZ-fil: {e} @msg not a WebAssembly binary (missing \\0asm header) inte en WebAssembly-binärfil (huvudet \\0asm saknas) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters en funktionstyp överskrider gränsen på {MAX_FUNC_TYPE_VALUES} parametrar +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results en funktionstyp överskrider gränsen på {MAX_FUNC_TYPE_VALUES} resultat @msg not a Word document: its compound file has no WordDocument stream inte ett Word-dokument: dess sammansatta fil saknar WordDocument-ström @msg not a Word document: its main part is not a WordprocessingML document inte ett Word-dokument: dess huvuddel är inte ett WordprocessingML-dokument @msg not a Word document: its package has no main document part inte ett Word-dokument: dess paket saknar huvuddokumentdel diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 24c452f944..30b27e0069 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -76,6 +76,17 @@ const UI_STRINGS: &[(&str, &[&str])] = &[ ), ("nature icons library", &["Nature Icons", "Leaf", "Flower", "Tree", "Mountain", "Wave"]), ("objects on path", &["Detach", "Detach Object from Path"]), + ( + "document info image details", + &[ + "{format}; {size}; {detail}", + "{x} × {y} ppi", + "resolution unavailable", + "estimated memory {memory}", + "memory unavailable", + "Unknown format", + ], + ), ( "type preferences", &[ @@ -86,6 +97,7 @@ const UI_STRINGS: &[(&str, &[&str])] = &[ "Low-Latency Drawing", ], ), + ("rearrange selected artboards", &["Rearrange…", "Selected Artboards: {n}"]), ]; #[test] @@ -104,6 +116,7 @@ fn strings_the_ui_shows_are_in_every_complete_catalog() { const MESSAGES: &[(&str, &[&str], &str, &str)] = &[ ("Packaged 1 file in /out/card Folder", &[], "/out/card", "Packaged"), ("Packaged 3 files", &[], "", "Packaged"), + (crate::dialogs::rearrange_artboards::PLACE_HINT, &[], "", "Click on the canvas"), ("Packaged 1 file (fonts not copied: Mono) in /out/card (draft) v2", &[], "Mono", "Packaged"), ("command `object.group` is not available right now: nothing selected", &["es"], "`object.group`", "nothing selected"), ]; @@ -199,6 +212,51 @@ fn bundled_catalogs_are_consistent() { } } +/// A catalog column with its `\n`, `\t` and `\\` escapes read. +fn unescaped(column: &str) -> String { + let mut out = String::with_capacity(column.len()); + let mut chars = column.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } + out +} + +/// A translated message starts and ends with whitespace only where its English does, so a status +/// message is not shown with a stray space. +#[test] +fn message_translations_keep_their_english_edges() { + let mut wrong = Vec::new(); + for (code, _, catalog) in EMBEDDED { + for line in catalog.lines() { + let mut columns = line.splitn(3, '\t'); + let (Some(ctx @ ("@msg" | "@msgplural")), Some(src), Some(tr)) = (columns.next(), columns.next(), columns.next()) else { continue }; + let (src, tr) = (unescaped(src), unescaped(tr)); + let plural = ctx == "@msgplural"; + let sources: Vec<&str> = if plural { src.split('|').collect() } else { vec![src.as_str()] }; + let forms: Vec<&str> = if plural { tr.split('|').collect() } else { vec![tr.as_str()] }; + for (i, form) in forms.into_iter().enumerate() { + let english = sources.get(i).or(sources.last()).copied().unwrap_or_default(); + let lead = form.starts_with(char::is_whitespace) && !english.starts_with(char::is_whitespace); + let trail = form.ends_with(char::is_whitespace) && !english.ends_with(char::is_whitespace); + if lead || trail { + wrong.push(format!("{code}: {src:?} -> {form:?}")); + } + } + } + } + assert!(wrong.is_empty(), "{} message translations add whitespace at an edge:\n{}", wrong.len(), wrong.join("\n")); +} + /// The engine learns the language the UI is drawn in each frame: new type takes the Japanese /// defaults while it is Japanese (#432). A Japanese frame draws in Japanese on this test's thread /// only: the tests running beside it on other threads still draw in English. @@ -747,7 +805,7 @@ fn menu_labels() -> Vec<(String, String, serde_json::Value)> { fn walk(items: &[Node], out: &mut Vec<(String, String, serde_json::Value)>) { for i in items { match i { - Node::Item(it) if it.command.id == crate::menus::TODO => out.push((it.label.clone(), String::new(), serde_json::Value::Null)), + Node::Item(it) if crate::menus::unbound(&it.command.id) => out.push((it.label.clone(), String::new(), serde_json::Value::Null)), Node::Item(it) => out.push((it.label.clone(), it.command.id.clone(), it.command.params.clone())), Node::Heading(l) => out.push((l.clone(), String::new(), serde_json::Value::Null)), Node::Submenu { label, children, .. } => { @@ -773,11 +831,11 @@ fn menu_item_effect<'a>(id: &str, p: &'a serde_json::Value) -> Option<&'a str> { /// The label a menu item shows in `lang`, as the menus resolve it: an Effect menu item by its /// effect's `@id` row when the catalog has one, any other command by its id's row or its English -/// label, and a submenu or an unbuilt item by its English label. +/// label, and a submenu, an unbuilt item or a placeholder by its English label. fn shown_menu_label(lang: Lang, item: &crate::menus::Node) -> Option<&str> { use crate::menus::Node; match item { - Node::Item(it) if it.command.id == crate::menus::TODO => Some(tr(lang, &it.label)), + Node::Item(it) if crate::menus::unbound(&it.command.id) => Some(tr(lang, &it.label)), Node::Item(it) => { let (id, p) = (it.command.id.as_str(), &it.command.params); let by_effect = menu_item_effect(id, p).map(|e| tr_id(lang, e, "")).filter(|s| !s.is_empty()); @@ -799,7 +857,7 @@ fn menu_items_side_by_side_have_different_labels() { for item in items { let Some(shown) = shown_menu_label(lang, item) else { continue }; let (english, what) = match item { - Node::Item(it) if it.command.id == crate::menus::TODO => (it.label.as_str(), "submenu or unbuilt item"), + Node::Item(it) if crate::menus::unbound(&it.command.id) => (it.label.as_str(), "submenu, unbuilt item or placeholder"), Node::Item(it) => (it.label.as_str(), menu_item_effect(&it.command.id, &it.command.params).unwrap_or(it.command.id.as_str())), Node::Submenu { label, .. } => (label.as_str(), "submenu or unbuilt item"), _ => continue, @@ -854,7 +912,7 @@ fn menu_items_never_show_an_id() { fn walk(lang: Lang, items: &[crate::menus::Node], out: &mut Vec) { for item in items { match item { - crate::menus::Node::Item(it) if it.command.id != crate::menus::TODO => { + crate::menus::Node::Item(it) if !crate::menus::unbound(&it.command.id) => { let (l, id) = (&it.label, it.command.id.as_str()); let key = menu_item_effect(id, &it.command.params).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); @@ -1624,7 +1682,7 @@ fn command_ids(s: &str) -> Vec<&str> { /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca", - "nl", "da", "id", + "nl", "da", "id", "bg", ]; /// Crates whose error and status messages reach the status bar, the crates whose errors the diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 87a2998316..6c74b05f0c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -906,6 +906,7 @@ font-technology Variable Değişken Direct Selection Tool Doğrudan Seçim Aracı Direction Handles Yön Kolları Disable Auto Add/Delete Otomatik Ekleme/Silmeyi Devre Dışı Bırak + Delete Removes Anchor Points and Keeps Paths Joined Delete Bağlantı Noktalarını Kaldırır ve Yolları Birleşik Tutar Interpolate Control Points When Moving Anchors Bağlantı Noktalarını Taşırken Yön Kollarını Enterpole Et Disable Opacity Mask Opaklık Maskesini Devre Dışı Bırak Discard At @@ -2397,6 +2398,7 @@ font-technology Variable Değişken One Point Perspective Preset 5 Tek Noktalı Perspektif Ön Ayarı 5 Only Web Colors Yalnızca Web Renkleri Opacity Opaklık + Show Opacity Opaklığı Göster Opacity & Mask Define Knockout Shape Opaklık ve Maske Tanımlama Nakavt Şekli Opacity Mask Opaklık Maskesi Opacity Mask Info Opaklık Maskesi Bilgisi @@ -2844,6 +2846,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Çalışma Yüzeyi ile Resmi Ölçeklendirin Artboards: {n} Çalışma yüzeyleri: {n} Rearrange All Artboards… Tüm Çalışma Yüzeylerini Yeniden Düzenleme… + Rearrange… Yeniden Düzenle… + Selected Artboards: {n} Seçili çalışma yüzeyleri: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Çalışma yüzeylerini yerleştirmek için tuvale tıklayın (Esc iptal eder) Recall Selection Seçimi Geri Çağır RECENT SON Recent Son @@ -3092,6 +3097,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. İzleme dörtgeninde iki parmakla döndürme hareketi tuvalin görünümünü döndürür. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Bir tuşu basılı tutmak, Klavye Kısayolları'ndaki Basılı tutun sütununda bulunan aracı veya komutu çalıştırır; kısa basış olağan kısayolunu çalıştırır. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Olağan kısayolu yerine basılı tutma kısayolunun çalışması için bir tuşun kaç saniye basılı tutulması gerektiği. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete, seçili bağlantı noktalarını kaldırır ve yolu orada açmak yerine her birinin çevresindeki eğriyi yeniden uydurur. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Bağlantı noktalarını taşıdığınızda, bir ucu taşınan her eğri uçlarına göre şeklini korur. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Bir aracın kısayol tuşunu basılı tutmak, tuşu bırakana kadar o aracı seçer, ardından önceki araç yeniden seçilir. Shows the bounding box while you move the selection or draw a shape. Seçimi taşırken veya bir şekil çizerken sınırlayıcı kutuyu gösterir. @@ -7180,6 +7186,12 @@ theme Appearance Görünüm {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable çözünürlük kullanılamıyor + estimated memory {memory} tahmini bellek {memory} + memory unavailable bellek kullanılamıyor + Unknown format Bilinmeyen biçim {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -7397,6 +7409,8 @@ axis Y Axis Y ekseni @msg needs approval: it asks for {0}, which the user grants when installing it on its own onay gerekiyor: {0} istiyor; kullanıcı bunu eklentiyi tek başına yüklerken verir @msg not JSON: {e} JSON değil: {e} @msg not a WebAssembly binary (missing \\0asm header) WebAssembly ikili dosyası değil (\\0asm üst bilgisi eksik) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters bir işlev türü {MAX_FUNC_TYPE_VALUES} parametre sınırını aşıyor +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results bir işlev türü {MAX_FUNC_TYPE_VALUES} sonuç sınırını aşıyor @msg parameter `{k}`: {what} `{k}` parametresi: {what} @msg parameter `{name}`: {what} `{name}` parametresi: {what} @msg plug-in parameters must be a JSON object eklenti parametreleri bir JSON nesnesi olmalıdır @@ -7433,6 +7447,11 @@ axis Y Axis Y ekseni @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` ve `maxItems` 0-{MAX_LIST} olmalı, `maxItems` en az 1 olmalı ve varsayılan değer bu kadar öğe içermelidir @msg `name` must be a string `name` bir dize olmalıdır @msg `opacity` must be a number `opacity` bir sayı olmalıdır +@msg `opacity` must be a number from 0 to 100 `opacity` 0 ile 100 arasında bir sayı olmalıdır +@msg `opacity` must be true or false `opacity` true veya false olmalıdır +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke metin karakterlerinin kendi opaklığı yoktur: Görünüm panelindeki Yeni Dolgu Ekle veya Yeni Kontur Ekle ile bir dolgu veya kontur ekleyin +@msg an object selected in a symbol instance has no fill or stroke opacity of its own bir sembol örneğinde seçilen nesnenin kendi dolgu veya kontur opaklığı yoktur +@msg no target has that fill or stroke to take the opacity hiçbir hedefte opaklığı alacak o dolgu veya kontur yok @msg `type` must be "path" or "compound" `type` "path" veya "compound" olmalıdır @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` 1-{MAX_UNIT} yazdırılabilir karakter olmalıdır @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`, `{other}` için 1 ile {MAX_CONDITION_VALUES} arasında değer listelemelidir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e21d744908..424e52d8b2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -924,6 +924,7 @@ font-technology Variable Варіативні Direct Selection Tool Інструмент «Пряме виділення» Direction Handles Маркери напряму Disable Auto Add/Delete Вимкнути авто-додавання/видалення + Delete Removes Anchor Points and Keeps Paths Joined Delete вилучає опорні точки й залишає контури з’єднаними Interpolate Control Points When Moving Anchors Інтерполювати маркери напряму під час переміщення опорних точок Disable Opacity Mask Вимкнути маску непрозорості Discard Відкинути @@ -2513,6 +2514,12 @@ file-filter Templates Шаблони {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable роздільна здатність недоступна + estimated memory {memory} орієнтовна пам’ять {memory} + memory unavailable пам’ять недоступна + Unknown format Невідомий формат {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -2661,6 +2668,7 @@ file-filter Templates Шаблони One Point Perspective Preset 5 Набір одноточкової перспективи 5 Only Web Colors Тільки web-кольору Opacity Непрозорість + Show Opacity Показати непрозорість Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування Opacity Mask Маска непрозорості Opacity Mask Info Відомості про маску непрозорості @@ -3115,6 +3123,9 @@ digits Malayalam Малаялам Scale Artwork with Artboard Масштабувати ілюстрацію разом із монтажною областю Artboards: {n} Монтажні області: {n} Rearrange All Artboards… Переставити всі монтажні області… + Rearrange… Переставити… + Selected Artboards: {n} Вибрані монтажні області: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Клацніть полотно, щоб розмістити монтажні області (Esc скасовує) Recall Selection Відновити виділення RECENT ОСТАННІ Recent Останні @@ -3368,6 +3379,7 @@ digits Malayalam Малаялам A two-finger rotate gesture on a trackpad rotates the canvas view. Жест обертання двома пальцями на трекпаді обертає вигляд полотна. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Утримання клавіші запускає інструмент або команду з її стовпця «Утримувати» в «Поєднаннях клавіш»; коротке натискання запускає її звичайне поєднання. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Скільки секунд потрібно утримувати клавішу, перш ніж замість її звичайного поєднання спрацює поєднання утримання. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete вилучає вибрані опорні точки й заново припасовує криву навколо кожної з них, замість розмикати контур у цьому місці. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Коли ви переміщуєте опорні точки, кожна крива з одним переміщеним кінцем зберігає форму відносно своїх кінців. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Поки ви утримуєте клавішу інструмента, його вибрано, а після відпускання знову вибирається попередній інструмент. Shows the bounding box while you move the selection or draw a shape. Показує обмежувальну рамку, поки ви переміщуєте виділення або малюєте фігуру. @@ -6929,6 +6941,8 @@ axis Y Axis Вісь Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own потрібне схвалення: він запитує {0}, що користувач дозволяє під час окремого встановлення @msg not JSON: {e} не JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) не двійковий файл WebAssembly (немає заголовка \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters тип функції має більше параметрів, ніж дозволяє межа ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results тип функції має більше результатів, ніж дозволяє межа ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} параметр `{k}`: {what} @msg parameter `{name}`: {what} параметр `{name}`: {what} @msg plug-in parameters must be a JSON object параметри модуля мають бути об’єктом JSON @@ -6965,6 +6979,11 @@ axis Y Axis Вісь Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` і `maxItems` мають бути 0-{MAX_LIST}, `maxItems` щонайменше 1, а типове значення має містити стільки елементів @msg `name` must be a string `name` має бути рядком @msg `opacity` must be a number `opacity` має бути числом +@msg `opacity` must be a number from 0 to 100 `opacity` має бути числом від 0 до 100 +@msg `opacity` must be true or false `opacity` має бути true або false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke символи тексту не мають власної непрозорості: додайте заливку або обведення командою «Додати нову заливку» або «Додати нове обведення» на панелі «Оформлення» +@msg an object selected in a symbol instance has no fill or stroke opacity of its own об’єкт, виділений в екземплярі символу, не має власної непрозорості заливки чи обведення +@msg no target has that fill or stroke to take the opacity жодна ціль не має такої заливки чи обведення, щоб задати непрозорість @msg `type` must be "path" or "compound" `type` має бути "path" або "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` має містити 1-{MAX_UNIT} друкованих символів @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` має перелічувати від 1 до {MAX_CONDITION_VALUES} значень для `{other}` @@ -9308,6 +9327,7 @@ breakText Glyphs Гліфи @msg give a pattern name or select an object painted with a pattern укажіть ім’я візерунка або виділіть об’єкт, зафарбований візерунком @msg give at least one of clip, invert, disabled, linked укажіть принаймні одне з: clip, invert, disabled, linked @msg give color, none, swatch or gradient укажіть color, none, swatch або gradient +@msg give color, none, swatch, gradient or opacity укажіть color, none, swatch, gradient або opacity @msg give dataBase64 укажіть dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) укажіть at (клацання) або area (контур, намальований навколо перекриттів) @msg give exactly one of `path`, `data` and `dataBase64` укажіть рівно одне з: `path`, `data`, `dataBase64` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 69cec087fc..891b1bc1ce 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1089,6 +1089,7 @@ font-technology Variable Biến thiên Direction Handles Tay nắm hướng Direction: Hướng: Disable Auto Add/Delete Tắt tự động thêm/xóa + Delete Removes Anchor Points and Keeps Paths Joined Delete xóa điểm neo và giữ các đường dẫn liền mạch Interpolate Control Points When Moving Anchors Nội suy tay nắm hướng khi di chuyển điểm neo Disable Opacity Mask Tắt mặt nạ độ mờ Discard Loại bỏ @@ -2932,6 +2933,7 @@ digits Hindi Hindi One Point Perspective Preset 5 Thiết lập sẵn phối cảnh một điểm 5 Only Web Colors Chỉ màu web Opacity Độ mờ + Show Opacity Hiện độ mờ Opacity & Mask Define Knockout Shape Độ mờ & Mặt nạ xác định hình dạng Knockout Opacity Mask Mặt nạ độ mờ Opacity Mask Info Thông tin mặt nạ độ mờ @@ -3140,6 +3142,12 @@ digits Hindi Hindi {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable không có độ phân giải + estimated memory {memory} bộ nhớ ước tính {memory} + memory unavailable không có thông tin bộ nhớ + Unknown format Định dạng không xác định {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} @@ -3432,6 +3440,9 @@ mark-style Japanese Kiểu Nhật Rearrange All Sắp xếp lại tất cả Rearrange All Artboards Sắp xếp lại tất cả bảng vẽ Rearrange All Artboards… Sắp xếp lại tất cả bảng vẽ… + Rearrange… Sắp xếp lại… + Selected Artboards: {n} Bảng vẽ đã chọn: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Bấm vào khung vẽ để đặt các bảng vẽ (Esc để hủy) Recall Selection Khôi phục vùng chọn RECENT GẦN ĐÂY Recent Gần đây @@ -3688,6 +3699,7 @@ mark-style Japanese Kiểu Nhật A two-finger rotate gesture on a trackpad rotates the canvas view. Cử chỉ xoay bằng hai ngón trên bàn di chuột sẽ xoay khung nhìn của khung vẽ. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Giữ một phím sẽ chạy công cụ hoặc lệnh trong cột Giữ của Phím tắt; nhấn nhanh sẽ chạy phím tắt thông thường của phím đó. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Số giây phải giữ một phím trước khi phím tắt nhấn giữ của nó chạy thay cho phím tắt thông thường. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete xóa các điểm neo đã chọn và khớp lại đường cong quanh từng điểm, thay vì mở đường dẫn tại đó. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Khi bạn di chuyển điểm neo, mỗi đường cong có một đầu bị di chuyển sẽ giữ hình dạng so với các đầu của nó. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Giữ phím tắt của một công cụ sẽ chọn công cụ đó cho đến khi bạn thả ra, rồi công cụ trước đó được chọn lại. Shows the bounding box while you move the selection or draw a shape. Hiển thị hộp giới hạn khi bạn di chuyển vùng chọn hoặc vẽ một hình. @@ -6975,6 +6987,8 @@ axis Y Axis Trục Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own cần phê duyệt: plug-in yêu cầu {0}, quyền mà người dùng cấp khi cài đặt riêng plug-in đó @msg not JSON: {e} không phải JSON: {e} @msg not a WebAssembly binary (missing \\0asm header) không phải tệp nhị phân WebAssembly (thiếu phần đầu \\0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters một kiểu hàm vượt quá giới hạn {MAX_FUNC_TYPE_VALUES} tham số +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results một kiểu hàm vượt quá giới hạn {MAX_FUNC_TYPE_VALUES} kết quả @msg parameter `{k}`: {what} tham số `{k}`: {what} @msg parameter `{name}`: {what} tham số `{name}`: {what} @msg plug-in parameters must be a JSON object tham số plug-in phải là một đối tượng JSON @@ -7012,6 +7026,11 @@ axis Y Axis Trục Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` và `maxItems` phải là 0-{MAX_LIST}, `maxItems` ít nhất là 1, và giá trị mặc định phải có đúng số mục đó @msg `name` must be a string `name` phải là một chuỗi @msg `opacity` must be a number `opacity` phải là một số +@msg `opacity` must be a number from 0 to 100 `opacity` phải là một số từ 0 đến 100 +@msg `opacity` must be true or false `opacity` phải là true hoặc false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke ký tự văn bản không có độ mờ riêng: hãy thêm tô hoặc nét bằng Thêm tô mới hoặc Thêm nét mới trong bảng Diện mạo +@msg an object selected in a symbol instance has no fill or stroke opacity of its own đối tượng được chọn trong một phiên bản biểu tượng không có độ mờ tô hoặc nét riêng +@msg no target has that fill or stroke to take the opacity không đối tượng nào có tô hoặc nét đó để nhận độ mờ @msg `type` must be "path" or "compound" `type` phải là "path" hoặc "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` phải có 1-{MAX_UNIT} ký tự in được @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` phải liệt kê 1 đến {MAX_CONDITION_VALUES} giá trị cho `{other}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 41a08fbef9..e357db7596 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -870,6 +870,7 @@ antiAlias Sharp 锐利 Direct Selection Tool 直接选择工具 Direction Handles 方向手柄 Disable Auto Add/Delete 禁用自动添加/删除锚点 + Delete Removes Anchor Points and Keeps Paths Joined Delete 删除锚点并保持路径连接 Interpolate Control Points When Moving Anchors 移动锚点时插值方向手柄 Disable Opacity Mask 禁用不透明度蒙版 Discard 不存储 @@ -2368,6 +2369,12 @@ file-filter Templates 模板 {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format};{size};{detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 分辨率不可用 + estimated memory {memory} 估计内存 {memory} + memory unavailable 内存不可用 + Unknown format 未知格式 {kind}, {instances} {kind},{instances} {kind}, {rows} × {cols} {kind},{rows} × {cols} {grid}, {instances} {grid},{instances} @@ -2514,6 +2521,7 @@ file-filter Templates 模板 One Point Perspective Preset 5 一点透视预设 5 Only Web Colors 仅 Web 颜色 Opacity 不透明度 + Show Opacity 显示不透明度 Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状 Opacity Mask 不透明度蒙版 Opacity Mask Info 不透明度蒙版信息 @@ -2967,6 +2975,9 @@ digits Malayalam 马拉雅拉姆数字 Scale Artwork with Artboard 随画板缩放图稿 Artboards: {n} 画板:{n} Rearrange All Artboards… 重新排列所有画板… + Rearrange… 重新排列… + Selected Artboards: {n} 选定的画板:{n} +@msg Click on the canvas to place the artboards (Esc cancels) 单击画布以放置画板 (Esc 取消) Recall Selection 召回选区 RECENT 最近使用 Recent 最近使用 @@ -3217,6 +3228,7 @@ digits Malayalam 马拉雅拉姆数字 A two-finger rotate gesture on a trackpad rotates the canvas view. 在触控板上用双指旋转手势可旋转画布视图。 Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. 按住某个键会运行键盘快捷键中其按住列的工具或命令;快速按下则运行其常规快捷键。 How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 按住某个键多少秒后,运行其按住快捷键而不是常规快捷键。 + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete 会删除所选锚点并重新拟合每个锚点周围的曲线,而不会在该处断开路径。 When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移动锚点时,只有一端移动的每条曲线都会保持其相对于两端的形状。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快捷键时选择该工具,松开后重新选择之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移动所选对象或绘制形状时显示定界框。 @@ -7157,6 +7169,8 @@ axis Y Axis Y 轴 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 需要批准:它请求 {0},用户单独安装它时授予这些权限 @msg not JSON: {e} 不是 JSON:{e} @msg not a WebAssembly binary (missing \\0asm header) 不是 WebAssembly 二进制文件(缺少 \\0asm 头) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 函数类型的参数数目超过上限({MAX_FUNC_TYPE_VALUES} 个) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 函数类型的结果数目超过上限({MAX_FUNC_TYPE_VALUES} 个) @msg parameter `{k}`: {what} 参数 `{k}`:{what} @msg parameter `{name}`: {what} 参数 `{name}`:{what} @msg plug-in parameters must be a JSON object 增效工具参数必须是 JSON 对象 @@ -7193,6 +7207,11 @@ axis Y Axis Y 轴 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` 和 `maxItems` 必须是 0-{MAX_LIST},`maxItems` 至少为 1,且默认值的项数在此范围内 @msg `name` must be a string `name` 必须是字符串 @msg `opacity` must be a number `opacity` 必须是数字 +@msg `opacity` must be a number from 0 to 100 `opacity` 必须是 0 到 100 之间的数字 +@msg `opacity` must be true or false `opacity` 必须是 true 或 false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 文字字符没有自己的不透明度:请用“外观”面板的“添加新填色”或“添加新描边”添加填色或描边 +@msg an object selected in a symbol instance has no fill or stroke opacity of its own 在符号实例中选中的对象没有自己的填色或描边不透明度 +@msg no target has that fill or stroke to take the opacity 没有目标具有可接受该不透明度的填色或描边 @msg `type` must be "path" or "compound" `type` 必须是 "path" 或 "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` 必须是 1-{MAX_UNIT} 个可打印字符 @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` 必须为 `{other}` 列出 1 到 {MAX_CONDITION_VALUES} 个值 @@ -9644,6 +9663,7 @@ breakText Glyphs 字形 @msg give a pattern name or select an object painted with a pattern 请给出图案名称,或选择用图案上色的对象 @msg give at least one of clip, invert, disabled, linked 请至少给出 clip、invert、disabled、linked 之一 @msg give color, none, swatch or gradient 请给出 color、none、swatch 或 gradient +@msg give color, none, swatch, gradient or opacity 请给出 color、none、swatch、gradient 或 opacity @msg give dataBase64 请给出 dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) 请给出 at (一次单击) 或 area (围绕重叠处绘制的路径) @msg give formats or a preset, not both 请给出 formats 或一个预设,不能两者都给 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e2beda57c7..0f96102880 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -892,6 +892,7 @@ font-technology Variable 可變 Direct Selection Tool 直接選取工具 Direction Handles 控制把手 Disable Auto Add/Delete 停用自動增加/刪除 + Delete Removes Anchor Points and Keeps Paths Joined Delete 刪除錨點並保持路徑連接 Interpolate Control Points When Moving Anchors 移動錨點時內插控制把手 Disable Opacity Mask 停用不透明度遮色片 Discard 捨棄 @@ -3806,6 +3807,12 @@ liquify-list-end {0}, {1} {0}和{1} {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format};{size};{detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 解析度無法使用 + estimated memory {memory} 估計記憶體 {memory} + memory unavailable 記憶體無法使用 + Unknown format 未知格式 {kind}, {instances} {kind},{instances} {kind}, {rows} × {cols} {kind},{rows} × {cols} {grid}, {instances} {grid},{instances} @@ -3954,6 +3961,7 @@ liquify-list-end {0}, {1} {0}和{1} One Point Perspective Preset 5 一點透視預設集 5 Only Web Colors 僅限網頁色彩 Opacity 不透明度 + Show Opacity 顯示不透明度 Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀 Opacity Mask 不透明度遮色片 Opacity Mask Info 不透明度遮色片資訊 @@ -4413,6 +4421,9 @@ digits Malayalam 馬來亞拉姆數字 Scale Artwork with Artboard 隨工作區域縮放圖稿 Artboards: {n} 工作區域:{n} Rearrange All Artboards… 重新排列所有工作區域… + Rearrange… 重新排列… + Selected Artboards: {n} 選取的工作區域:{n} +@msg Click on the canvas to place the artboards (Esc cancels) 按一下畫布以放置工作區域 (Esc 取消) Recall Selection 叫出選取範圍 RECENT 最近使用 Recent 最近使用 @@ -4666,6 +4677,7 @@ digits Malayalam 馬來亞拉姆數字 A two-finger rotate gesture on a trackpad rotates the canvas view. 在觸控式軌跡板上以雙指旋轉手勢可旋轉畫布檢視。 Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. 按住某個鍵會執行鍵盤快速鍵中其按住欄的工具或命令;快速按下則執行其一般快速鍵。 How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 按住某個鍵多少秒後,執行其按住快速鍵而不是一般快速鍵。 + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete 會刪除所選錨點並重新擬合每個錨點周圍的曲線,而不會在該處斷開路徑。 When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移動錨點時,只有一端移動的每條曲線都會保持其相對於兩端的形狀。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快速鍵時選擇該工具,放開後重新選擇之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移動選取範圍或繪製形狀時顯示邊框。 @@ -6978,6 +6990,8 @@ axis Y Axis Y 軸 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 需要核准:它要求 {0},使用者單獨安裝它時授予這些權限 @msg not JSON: {e} 不是 JSON:{e} @msg not a WebAssembly binary (missing \\0asm header) 不是 WebAssembly 二進位檔(沒有 \\0asm 標頭) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 函式型別的參數數目超過上限({MAX_FUNC_TYPE_VALUES} 個) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 函式型別的結果數目超過上限({MAX_FUNC_TYPE_VALUES} 個) @msg parameter `{k}`: {what} 參數 `{k}`:{what} @msg parameter `{name}`: {what} 參數 `{name}`:{what} @msg plug-in parameters must be a JSON object 增效模組參數必須是 JSON 物件 @@ -7014,6 +7028,11 @@ axis Y Axis Y 軸 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` 和 `maxItems` 必須是 0-{MAX_LIST},`maxItems` 至少為 1,且預設值的項目數須在此範圍內 @msg `name` must be a string `name` 必須是字串 @msg `opacity` must be a number `opacity` 必須是數字 +@msg `opacity` must be a number from 0 to 100 `opacity` 必須是 0 到 100 之間的數字 +@msg `opacity` must be true or false `opacity` 必須是 true 或 false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 文字字元沒有自己的不透明度:請用「外觀」面板的「新增填色」或「新增筆畫」新增填色或筆畫 +@msg an object selected in a symbol instance has no fill or stroke opacity of its own 在符號實體中選取的物件沒有自己的填色或筆畫不透明度 +@msg no target has that fill or stroke to take the opacity 沒有目標具有可接受該不透明度的填色或筆畫 @msg `type` must be "path" or "compound" `type` 必須是 "path" 或 "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` 必須是 1-{MAX_UNIT} 個可列印字元 @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` 必須為 `{other}` 列出 1 到 {MAX_CONDITION_VALUES} 個值 @@ -9580,6 +9599,7 @@ breakText Glyphs 字符 @msg give a pattern name or select an object painted with a pattern 請提供圖樣名稱,或選取以圖樣上色的物件 @msg give at least one of clip, invert, disabled, linked clip、invert、disabled、linked 請至少提供一個 @msg give color, none, swatch or gradient 請提供 color、none、swatch 或 gradient +@msg give color, none, swatch, gradient or opacity 請提供 color、none、swatch、gradient 或 opacity @msg give dataBase64 請提供 dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) 請提供 at (一次點按) 或 area (圍繞重疊處繪製的路徑) 其中之一 @msg give formats or a preset, not both 請提供 formats 或預設集,不要兩者都提供 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index bf76005b9e..8c8962dd50 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -66,6 +66,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), + ("dc-corner-tool", include_bytes!("../../../assets/icons/dc-corner-tool.svg")), ("dc-crystallize", include_bytes!("../../../assets/icons/dc-crystallize.svg")), ("dc-cube", include_bytes!("../../../assets/icons/dc-cube.svg")), ("dc-curvature-circle", include_bytes!("../../../assets/icons/dc-curvature-circle.svg")), @@ -106,6 +107,15 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-grad-stroke-along", include_bytes!("../../../assets/icons/dc-grad-stroke-along.svg")), ("dc-grad-stroke-within", include_bytes!("../../../assets/icons/dc-grad-stroke-within.svg")), ("dc-gradient", include_bytes!("../../../assets/icons/dc-gradient.svg")), + ("dc-graph-area", include_bytes!("../../../assets/icons/dc-graph-area.svg")), + ("dc-graph-bar", include_bytes!("../../../assets/icons/dc-graph-bar.svg")), + ("dc-graph-column", include_bytes!("../../../assets/icons/dc-graph-column.svg")), + ("dc-graph-line", include_bytes!("../../../assets/icons/dc-graph-line.svg")), + ("dc-graph-pie", include_bytes!("../../../assets/icons/dc-graph-pie.svg")), + ("dc-graph-radar", include_bytes!("../../../assets/icons/dc-graph-radar.svg")), + ("dc-graph-scatter", include_bytes!("../../../assets/icons/dc-graph-scatter.svg")), + ("dc-graph-stacked-bar", include_bytes!("../../../assets/icons/dc-graph-stacked-bar.svg")), + ("dc-graph-stacked-column", include_bytes!("../../../assets/icons/dc-graph-stacked-column.svg")), ("dc-graphic-styles", include_bytes!("../../../assets/icons/dc-graphic-styles.svg")), ("dc-grid-view", include_bytes!("../../../assets/icons/dc-grid-view.svg")), ("dc-group-select", include_bytes!("../../../assets/icons/dc-group-select.svg")), @@ -115,6 +125,9 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-join-miter", include_bytes!("../../../assets/icons/dc-join-miter.svg")), ("dc-join-round", include_bytes!("../../../assets/icons/dc-join-round.svg")), ("dc-knife", include_bytes!("../../../assets/icons/dc-knife.svg")), + ("dc-lasso", include_bytes!("../../../assets/icons/dc-lasso.svg")), + ("dc-lasso-enclosing", include_bytes!("../../../assets/icons/dc-lasso-enclosing.svg")), + ("dc-lasso-polygonal", include_bytes!("../../../assets/icons/dc-lasso-polygonal.svg")), ("dc-line", include_bytes!("../../../assets/icons/dc-line.svg")), ("dc-line-cut", include_bytes!("../../../assets/icons/dc-line-cut.svg")), ("dc-list-view", include_bytes!("../../../assets/icons/dc-list-view.svg")), @@ -143,6 +156,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-path-eraser", include_bytes!("../../../assets/icons/dc-path-eraser.svg")), ("dc-pathfinder", include_bytes!("../../../assets/icons/dc-pathfinder.svg")), ("dc-perspective", include_bytes!("../../../assets/icons/dc-perspective.svg")), + ("dc-perspective-select", include_bytes!("../../../assets/icons/dc-perspective-select.svg")), ("dc-pf-crop", include_bytes!("../../../assets/icons/dc-pf-crop.svg")), ("dc-pf-divide", include_bytes!("../../../assets/icons/dc-pf-divide.svg")), ("dc-pf-exclude", include_bytes!("../../../assets/icons/dc-pf-exclude.svg")), @@ -160,6 +174,8 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-puppet", include_bytes!("../../../assets/icons/dc-puppet.svg")), ("dc-quick-pen", include_bytes!("../../../assets/icons/dc-quick-pen.svg")), ("dc-rearrange", include_bytes!("../../../assets/icons/dc-rearrange.svg")), + ("dc-recolor-arrow", include_bytes!("../../../assets/icons/dc-recolor-arrow.svg")), + ("dc-recolor-arrow-off", include_bytes!("../../../assets/icons/dc-recolor-arrow-off.svg")), ("dc-rect-cut", include_bytes!("../../../assets/icons/dc-rect-cut.svg")), ("dc-rect-grid", include_bytes!("../../../assets/icons/dc-rect-grid.svg")), ("dc-reference-point", include_bytes!("../../../assets/icons/dc-reference-point.svg")), @@ -174,7 +190,11 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-screen-mode", include_bytes!("../../../assets/icons/dc-screen-mode.svg")), ("dc-selection", include_bytes!("../../../assets/icons/dc-selection.svg")), ("dc-shape-builder", include_bytes!("../../../assets/icons/dc-shape-builder.svg")), + ("dc-shared-edge", include_bytes!("../../../assets/icons/dc-shared-edge.svg")), ("dc-shear", include_bytes!("../../../assets/icons/dc-shear.svg")), + ("dc-slice", include_bytes!("../../../assets/icons/dc-slice.svg")), + ("dc-slice-select", include_bytes!("../../../assets/icons/dc-slice-select.svg")), + ("dc-slide-anchor", include_bytes!("../../../assets/icons/dc-slide-anchor.svg")), ("dc-smooth", include_bytes!("../../../assets/icons/dc-smooth.svg")), ("dc-stroke", include_bytes!("../../../assets/icons/dc-stroke.svg")), ("dc-stroke-center", include_bytes!("../../../assets/icons/dc-stroke-center.svg")), @@ -185,7 +205,14 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-swatch-kinds", include_bytes!("../../../assets/icons/dc-swatch-kinds.svg")), ("dc-swatch-process", include_bytes!("../../../assets/icons/dc-swatch-process.svg")), ("dc-swatch-spot", include_bytes!("../../../assets/icons/dc-swatch-spot.svg")), + ("dc-symbol-screener", include_bytes!("../../../assets/icons/dc-symbol-screener.svg")), + ("dc-symbol-scruncher", include_bytes!("../../../assets/icons/dc-symbol-scruncher.svg")), + ("dc-symbol-shifter", include_bytes!("../../../assets/icons/dc-symbol-shifter.svg")), + ("dc-symbol-sizer", include_bytes!("../../../assets/icons/dc-symbol-sizer.svg")), + ("dc-symbol-spinner", include_bytes!("../../../assets/icons/dc-symbol-spinner.svg")), ("dc-symbol-sprayer", include_bytes!("../../../assets/icons/dc-symbol-sprayer.svg")), + ("dc-symbol-stainer", include_bytes!("../../../assets/icons/dc-symbol-stainer.svg")), + ("dc-symbol-styler", include_bytes!("../../../assets/icons/dc-symbol-styler.svg")), ("dc-touch-type", include_bytes!("../../../assets/icons/dc-touch-type.svg")), ("dc-transform-panel", include_bytes!("../../../assets/icons/dc-transform-panel.svg")), ("dc-transparency", include_bytes!("../../../assets/icons/dc-transparency.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 85f8a5e701..46b96ae2c1 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -18,7 +18,8 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-direct" => "dc-direct", "tool-group-select" => "dc-group-select", "tool-magic-wand" => "wand_sparkles", - "tool-lasso" => "lasso", + "tool-lasso" => "dc-lasso", + "tool-lasso-enclosing" => "dc-lasso-enclosing", "tool-pen" => "pen-tool", "tool-pen-add" => "pen-tool-add", "tool-pen-delete" => "pen-tool-delete", @@ -79,7 +80,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-fill-area" => "dc-fill-area", "tool-live-select" => "dc-live-select", "tool-perspective" => "dc-perspective", - "tool-perspective-select" => "dc-perspective", + "tool-perspective-select" => "dc-perspective-select", "tool-mesh" => "dc-mesh", "tool-gradient" => "dc-gradient", "tool-eyedropper" => "eyedropper", @@ -89,9 +90,25 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-blend" => "dc-blend", "tool-objects-on-path" => "dc-objects-on-path", "tool-symbol" => "dc-symbol-sprayer", - "tool-graph" => "chart-column", + "tool-symbol-shifter" => "dc-symbol-shifter", + "tool-symbol-scruncher" => "dc-symbol-scruncher", + "tool-symbol-sizer" => "dc-symbol-sizer", + "tool-symbol-spinner" => "dc-symbol-spinner", + "tool-symbol-stainer" => "dc-symbol-stainer", + "tool-symbol-screener" => "dc-symbol-screener", + "tool-symbol-styler" => "dc-symbol-styler", + "tool-graph" => "dc-graph-column", + "tool-graph-stacked-column" => "dc-graph-stacked-column", + "tool-graph-bar" => "dc-graph-bar", + "tool-graph-stacked-bar" => "dc-graph-stacked-bar", + "tool-graph-line" => "dc-graph-line", + "tool-graph-area" => "dc-graph-area", + "tool-graph-scatter" => "dc-graph-scatter", + "tool-graph-pie" => "dc-graph-pie", + "tool-graph-radar" => "dc-graph-radar", "tool-artboard" => "artboard", - "tool-slice" => "slice_knife", + "tool-slice" => "dc-slice", + "tool-slice-select" => "dc-slice-select", "tool-hand" => "hand", "tool-rotate-view" => "dc-rotate-view", "tool-print-tiling" => "printer", @@ -114,6 +131,72 @@ mod tests { has_icon(&IconId::new(name)) } + /// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`. + const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""]; + + /// The id a `const NAME: &str = ""` line declares, when `NAME` ends in `ICON` or `code` passes it to + /// `IconId::new(NAME)`. + fn const_icon<'a>(line: &'a str, code: &str) -> Option<&'a str> { + let rest = line.trim_start().trim_start_matches("pub ").trim_start_matches("pub(crate) ").strip_prefix("const ")?; + let (name, after) = rest.split_once(':')?; + if name.is_empty() || !name.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') { + return None; + } + if !name.ends_with("ICON") && !code.contains(&format!("IconId::new({name})")) { + return None; + } + after.trim_start().strip_prefix("&str")?.split_once("= \"")?.1.split('"').next() + } + + /// An id that no set has draws nothing and raises no error at build time. Every icon id this crate's code + /// writes as a literal or a `const`, and every icon panel's and dock tab's icon, resolves in the catalog or the + /// app's set. Other ids built in match arms and tuple tables are not scanned. + #[test] + fn every_icon_id_literal_and_panel_icon_resolves() { + register_app_icons(&APP_ICONS); + let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned()))); + let (mut seen, mut unknown) = (0, Vec::new()); + let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; + while let Some(dir) = stack.pop() { + let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + for entry in entries { + let path = entry.unwrap_or_else(|e| panic!("{}: {e}", dir.display())).path(); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if path.is_dir() { + if name != "tests" { + stack.push(path); + } + continue; + } + if !name.ends_with(".rs") || name.starts_with("tests") { + continue; + } + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + // Code up to the test module: a test harness's `icon("..")` names a panel, not an icon. + let code = text.find("#[cfg(test)]\nmod ").map_or(text.as_str(), |at| &text[..at]); + for (number, line) in code.lines().enumerate().filter(|(_, l)| !l.trim_start().starts_with("//")) { + let literal = |form: &&str| { + line.match_indices(*form).filter_map(|(at, form)| line[at + form.len()..].split('"').next()).collect::>() + }; + for id in FORMS.iter().flat_map(literal).chain(const_icon(line, code)) { + seen += 1; + if !resolves(id) { + unknown.push(format!("{}:{}: {id:?}", path.display(), number + 1)); + } + } + } + } + } + assert!(seen > 50, "the source scan found only {seen} icon ids"); + let tabs = crate::state::DockTab::ALL.map(crate::state::DockTab::info); + for (panel, _, icon) in crate::state::ICON_PANELS.iter().chain(tabs.iter()) { + if !resolves(icon) { + unknown.push(format!("panel {panel}: {icon:?}")); + } + } + assert!(unknown.is_empty(), "icon ids that no set has: {unknown:#?}"); + } + /// Appearance (effects) and Pathfinder both lived in the icon column; they used the same /// overlapping-squares motif (storytold/vectorcraft#2681). #[test] @@ -163,6 +246,20 @@ mod tests { } } + /// Every cataloged tool, the add-ons' included, maps to an existing icon that is not the + /// dashed placeholder and that no other tool uses. + #[test] + fn every_tool_has_an_icon_no_other_tool_uses() { + let mut users: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new(); + for tool in vectorcraft_tools::catalog::all_tools() { + let name = tool_icon(tool.icon); + assert!(resolves(name) && name != "rect_dashed", "{} maps to {name}, which isn't an icon of its own", tool.id); + users.entry(name).or_default().push(tool.id); + } + let shared: Vec<_> = users.iter().filter(|(_, tools)| tools.len() > 1).collect(); + assert!(shared.is_empty(), "tools that share an icon: {shared:?}"); + } + /// An unresolved name draws the fallback square silently, and the registration only logs a refused /// icon: this is what notices either. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 59aa12e06c..4fc00a0a78 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -340,8 +340,9 @@ pub struct VectorcraftApp { pub(crate) pen_end: stylus::PenEnd, /// The window pass whose [`Self::tick`] ran last: work started in that pass, before its end, waits for the next. pub(crate) ticked_pass: Option, - /// A test's clock for [`Self::tick`], replacing the monotonic clock so idle scheduling can be - /// driven one simulated frame at a time (production always leaves this `None`). + /// A test's clock for [`Self::tick`] and the progress window's delay, replacing the monotonic + /// clock so idle scheduling can be driven one simulated frame at a time (production always + /// leaves this `None`). #[cfg(test)] pub(crate) now_override: Option, /// An error the next tool choice returns before the engine sees it ([`Self::try_select_tool`]), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7d003be560..8ea8726bf1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -23,6 +23,16 @@ pub(crate) use craft::menu::Node::Separator as Sep; /// The command id of an item that is not built yet; its state is always disabled. pub(crate) const TODO: &str = "todo"; +/// The command id of a placeholder row that stands for an empty list (File › Open With's "No +/// importer plug-ins installed"); it runs nothing and its state is always disabled. +pub(crate) const PLACEHOLDER: &str = "placeholder"; + +/// Whether a row bound to command `id` runs nothing: a Coming Soon row ([`TODO`]) or a placeholder +/// ([`PLACEHOLDER`]). +pub(crate) fn unbound(id: &str) -> bool { + id == TODO || id == PLACEHOLDER +} + /// An item that runs command `id` with `params`, labelled `label` (the English source label for /// tree rows, the shown name for rows that list names). pub(crate) fn named(label: impl Into, id: &str, params: Value) -> Node { @@ -38,6 +48,11 @@ pub(crate) fn cp(label: &'static str, id: &'static str, params: Value) -> Node { pub(crate) fn todo(label: &'static str) -> Node { named(label, TODO, json!({ "label": label })) } +/// A disabled row that stands for an empty list, so its submenu stays in the menu: the layout +/// drops a heading with no item after it, and with it a submenu left empty. +pub(crate) fn placeholder(label: &'static str) -> Node { + named(label, PLACEHOLDER, json!({ "label": label })) +} pub(crate) fn sub(label: &'static str, children: Vec) -> Node { Node::submenu(label, children) } @@ -66,9 +81,9 @@ use entries::flatten; pub use entries::{InsertableItem, MenuEntry, context_entries, insertable, insertable_items, menu_entries, plays_in_app, shown_label}; pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke}; -pub(crate) use labels::lists_plugin; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; +pub(crate) use labels::{holds_plugin_commands, lists_plugin}; pub(crate) use model::{MAC_LABELS, home_key, home_showing}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 9ff6f3c9c0..212cffd703 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -237,8 +237,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec { } } v.push(Sep); - if n > 1 { - v.push(c("Rearrange", "artboard.rearrange")); + // Rearrange lays out the selected artboards: a click on the item opens its dialog + // (`menus::invoke`), whose OK waits for a click on the canvas. + if !sel.is_empty() { + v.push(cp("Rearrange", "artboard.rearrange", json!({ "indices": sel }))); } if facts.map_or_else(|| boards::fit_has_art(app, &free), |f| f.any_art) { v.push(c("Fit to Artwork Bounds", "artboard.fitToArt")); diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 6524edfd21..09513fb538 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -3,7 +3,7 @@ use super::labels::{display_label, dynamic_label, effect_item_label, item_shortc use super::slots::{recent_readable, recent_slot}; use super::state::{shortcut_of, shown_state}; use super::tree::{Listed, menu_tree_named}; -use super::{Node, Serialize, TODO, Value, VectorcraftApp}; +use super::{Node, Serialize, Value, VectorcraftApp, unbound}; /// The label of the menu item that runs `id` with `p` and reads `label` in English, as the menus /// draw it in the UI language: an effect's own name (Pathfinder › Add), an object's name, a @@ -169,7 +169,7 @@ pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec, shown: Vec, nodes: &[Node], out: &mut Vec) { for node in nodes { match node { - Node::Item(it) if it.command.id == TODO => out.push(MenuEntry { + Node::Item(it) if unbound(&it.command.id) => out.push(MenuEntry { path: path.clone(), label: it.label.clone(), command: None, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 09195e00c3..0a3dc862b5 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -90,6 +90,14 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { { return; } + // The Artboard tool's Rearrange (its canvas menu) opens Rearrange for the artboards it lists, + // whose OK waits for a click on the canvas. + if id == "artboard.rearrange" + && let Some(indices) = crate::dialogs::rearrange_artboards::menu_indices(&p) + { + crate::dialogs::rearrange_artboards::open_selected(app, &indices); + return; + } // Params first: some dialogs' fields take a look through the session (Move's last move). if p.as_object().is_none_or(|o| o.is_empty()) && let Some(opened) = open_menu_dialog(app, id) diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 030eb40b98..db65b9cbae 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -2,7 +2,7 @@ use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_se use super::state::{hidden_when_disabled, shortcut_of}; use super::tree::menu_tree; use super::ui_commands::UI_COMMANDS; -use super::{Node, TODO, Value, VectorcraftApp}; +use super::{Node, Value, VectorcraftApp, unbound}; use craft::keymap::Chord; /// Label for toggles whose text flips (Outline/Preview, Hide/Show …). @@ -344,9 +344,14 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Advanced", ]; -/// Is `children` a plug-in's submenu: does it hold a command the plug-in declares? +/// Is `children` a plug-in's submenu: does it hold a command the plug-in declares, and only items +/// that list plug-ins? A built-in submenu that a plug-in's manifest places a command in is not. pub(crate) fn holds_plugin_commands(children: &[Node]) -> bool { children.iter().any(|c| matches!(c, Node::Item(i) if vectorcraft_engine::cmd::plugin::is_command_id(&i.command.id))) + && children.iter().all(|c| match c { + Node::Item(i) => lists_plugin(&i.command.id, &i.command.params), + _ => true, + }) } /// Every English string the menus, the command palette, the panel registry, the toolbar and the @@ -366,7 +371,7 @@ pub fn menu_strings() -> std::collections::BTreeSet { fn walk(nodes: &[Node], under: &str, out: &mut BTreeSet) { for node in nodes { match node { - Node::Item(it) if it.command.id == TODO => { + Node::Item(it) if unbound(&it.command.id) => { out.insert(it.label.clone()); } Node::Item(it) => { diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 9fdbeb7d84..1ff1ce27e0 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -18,7 +18,7 @@ use craft::ui::runtime::windows::WindowHost; use serde_json::{Value, json}; use super::labels::holds_plugin_commands; -use super::{Listed, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off}; +use super::{Listed, PLACEHOLDER, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off}; use crate::i18n::LangExt as _; use crate::{UiState, VectorcraftApp}; @@ -432,6 +432,16 @@ impl Build<'_> { let tip = crate::i18n::tr(self.lang, TODO_TOOLTIP).to_string(); return Some(item.tooltip(tip)); } + // A placeholder shows its text in the UI language, as a heading does, and runs nothing. + if command.id == PLACEHOLDER { + self.states.set(command, CommandState::new().enabled(false)); + let mut item = item.enabled(false); + let shown = self.title(&item.label, true); + if shown != item.label { + item.english = Some(std::mem::replace(&mut item.label, shown)); + } + return Some(item); + } let (id, params) = (command.id.as_str(), &command.params); let (enabled, checked) = shown_state(self.app, id, params)?; let mut state = CommandState::new().enabled(enabled).title(self.item_title(id, params, &item.label)); diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 9a15431858..62fbc97da3 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -5,8 +5,8 @@ use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac, use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder}; use crate::VectorcraftApp; -use crate::menus::TODO; use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label}; +use crate::menus::unbound; /// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its /// translation of the labels the layout writes itself. @@ -63,7 +63,7 @@ fn stated(app: &VectorcraftApp) -> MenuBar { fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, nodes: &mut [Node]) { for node in nodes { match node { - Node::Item(it) if it.command.id == TODO => it.enabled = false, + Node::Item(it) if unbound(&it.command.id) => it.enabled = false, Node::Item(it) => { let (id, params) = (it.command.id.as_str(), &it.command.params); if let Some((enabled, checked)) = crate::menus::shown_state(app, id, params) { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 7d1dd037e5..2433cc0e25 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1237,8 +1237,8 @@ fn every_bound_menu_command_exists() { match n { Node::Item(it) => { let id = it.command.id.as_str(); - // A Coming Soon row (`TODO`) is bound to no command. - if id != TODO + // A Coming Soon row (`TODO`) or a placeholder is bound to no command. + if !unbound(id) && vectorcraft_engine::find_command(id).is_none() && !UI_COMMANDS.iter().any(|c| c.0 == id) && !id.starts_with("object.path.") @@ -1258,6 +1258,56 @@ fn every_bound_menu_command_exists() { assert!(bad.is_empty(), "menu items bound to unknown commands: {bad:?}"); } +/// File › Open With and Object › Plug-ins stay in the laid-out bar with nothing of their kind installed, showing a +/// disabled row that says so. Plug-ins are process-wide and other tests install some, so each list is checked only +/// while it holds none of its own rows. +#[test] +fn plugin_lists_show_a_disabled_row_when_nothing_is_installed() { + fn submenu<'a>(nodes: &'a [Node], english: &str) -> Option<&'a [Node]> { + nodes.iter().find_map(|n| match n { + Node::Submenu { label, english: e, children, .. } if e.as_deref().unwrap_or(label) == english => Some(children.as_slice()), + _ => None, + }) + } + fn placeholder_off(nodes: &[Node], text: &str) -> bool { + nodes.iter().any(|n| matches!(n, Node::Item(it) if it.command.id == PLACEHOLDER && it.command.params["label"] == text && !it.enabled)) + } + fn lists(nodes: &[Node], id: &str) -> bool { + nodes.iter().any(|n| match n { + Node::Item(it) => it.command.id == id, + Node::Submenu { children, .. } => lists(children, id), + _ => false, + }) + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = crate::testing::ui_context(); + crate::menus::model::refresh(&mut app, &ctx); + let menu = |english: &str| { + app.menus.laid.menus.iter().find(|m| m.english.as_deref().unwrap_or(&m.title) == english).map(|m| m.children.as_slice()).unwrap_or_default() + }; + + let open_with = submenu(menu("File"), "Open With").expect("File › Open With is in the bar"); + if !lists(open_with, "file.openWith") { + assert!(placeholder_off(open_with, crate::dialogs::plugin::NO_IMPORTERS), "{open_with:?}"); + } + let plugins = submenu(menu("Object"), "Plug-ins").expect("Object › Plug-ins is in the bar"); + if !lists(plugins, "plugin.dialog") { + assert!(placeholder_off(plugins, crate::dialogs::plugin::NO_FILTERS), "{plugins:?}"); + } + + // Whatever is installed: the layout keeps an empty list's row, and the submenu that holds only that row. + let row = |nodes: &[Node], text: &str| nodes.iter().any(|n| matches!(n, Node::Item(it) if it.command.id == PLACEHOLDER && it.label == text)); + let mut empty = vec![ + sub("Open With", vec![placeholder(crate::dialogs::plugin::NO_IMPORTERS)]), + placeholder(crate::dialogs::plugin::NO_FILTERS), + Sep, + c("Reload Plug-ins", "plugin.reload"), + ]; + craft::menu::tidy(&mut empty); + assert!(submenu(&empty, "Open With").is_some_and(|o| row(o, crate::dialogs::plugin::NO_IMPORTERS)), "{empty:?}"); + assert!(row(&empty, crate::dialogs::plugin::NO_FILTERS), "{empty:?}"); +} + /// #543: Object › Image Trace › Make and Make and Expand trace with the Default preset at once, /// with no form asking for a preset's name. #[test] diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 13b33dde44..53b5d973f7 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -45,6 +45,14 @@ impl Listed { } pub fn menu_tree_named(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec)> { + let mut tree = built_in_tree(english_names, listed); + crate::dialogs::plugin::place_commands(&mut tree); + tree +} + +/// The menus with each plug-in command in its plug-in's submenu, before +/// [`crate::dialogs::plugin::place_commands`] moves those whose manifest names another menu. +fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec)> { let panel = |label: &'static str, id: &'static str| cp(label, "window.panel", json!({ "panel": id, "toggle": true })); vec![ ( diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 77b585a69b..3120178fbc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1598,7 +1598,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 31e8ce20f2..15235131dd 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -129,7 +129,7 @@ pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFi /// Lists the file being read for `path` and tells the status bar → `{background: true, status}`. fn track(app: &mut VectorcraftApp, path: &str, done: Receiver>, scope: ScopeHandle, token: CancelToken) -> Value { let label = format!("Opening {}", fileio::file_name(path)); - let started = crate::export_progress::now(); + let started = crate::export_progress::now(app); app.opening.pending.push(Pending { path: path.to_string(), label: label.clone(), done, scope, token, hidden: false, started }); let status = format!("{label}…"); app.status(status.clone()); diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 609f3c18a8..2466381a3d 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -526,6 +526,8 @@ fn bytes(title: &str) -> Vec { #[test] fn a_file_that_takes_a_while_to_open_shows_a_progress_window() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); + // The app's clock stands still: a read is only old enough for its window after `age`. + app.now_override = Some(0.0); let ctx = crate::testing::ui_context(); assert_eq!(progress(&mut app, &ctx), "", "nothing opening"); start(&mut app, "/art/Big.vectorcraft", bytes("Big")); diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs index 5888f2fa26..9089ede4f2 100644 --- a/crates/ui-egui/src/original_editor.rs +++ b/crates/ui-egui/src/original_editor.rs @@ -5,8 +5,9 @@ use std::path::Path; use craft::host::{Host, PickId, PickRequest}; use craft::ui::buttons::Button; -use craft::ui::contract::{Props as _, Show as _}; +use craft::ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Text; +use craft::ui::layout_components::Row; use serde::{Deserialize, Serialize}; use crate::VectorcraftApp; @@ -118,19 +119,21 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, enabled: bool) { { app.status(e); } - ui.horizontal_wrapped(|ui| { + let chosen = app.original_editor.choice.path.clone(); + let (mut choose, mut default) = (false, false); + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Edit Original with:")).show(ui); - let name = app.original_editor.choice.path.as_deref().and_then(|p| Path::new(p).file_name()); + let name = chosen.as_deref().and_then(|p| Path::new(p).file_name()); Text::new(name.map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into())).show(ui); - if Button::new(tl!("Choose…")).enabled(enabled).show(ui).clicked() - && let Err(e) = pick(app) - { - app.status(e); - } - if app.original_editor.choice.path.is_some() && Button::new("PhotoCraft").enabled(enabled).show(ui).clicked() { - reset(app); - } + choose = Button::new(tl!("Choose…")).enabled(enabled).show(ui).clicked(); + default = chosen.is_some() && Button::new("PhotoCraft").enabled(enabled).show(ui).clicked(); }); + if choose && let Err(e) = pick(app) { + app.status(e); + } + if default { + reset(app); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index bf08e37abb..6eba474b74 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1546,6 +1546,7 @@ mod tests { #[test] fn each_filter_plugin_is_a_result_of_its_own() { use vectorcraft_plugins::wat as tpl; + let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner()); let (one, two) = ("test.UI.palette_filter-one", "test.UI.palette_filter-two"); let (key_one, key_two) = (format!("plugin:{one}"), format!("plugin:{two}")); let install = |id: &str, params: &str| { @@ -1826,6 +1827,7 @@ mod tests { #[test] fn filter_plugins_with_one_name_show_their_ids() { use vectorcraft_plugins::wat as tpl; + let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner()); let (one, two) = ("test.UI.palette_same-one", "test.UI.palette_same-two"); for id in [one, two] { let manifest = format!(r#"{{"id":"{id}","name":"Same Name","version":"1","kind":"filter","params":{{"wiggle":{{"type":"bool"}}}}}}"#); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 489eee6f61..0a809cd093 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -989,6 +989,8 @@ mod tests_color_wheel_gamut; #[cfg(test)] mod tests_color_wheel_harmony; #[cfg(test)] +mod tests_color_wheel_opacity; +#[cfg(test)] mod tests_color_wheel_vision; #[cfg(test)] mod tests_constrain; @@ -1003,6 +1005,8 @@ mod tests_links; #[cfg(test)] mod tests_maskview; #[cfg(test)] +mod tests_panel_rows; +#[cfg(test)] mod tests_script_console; #[cfg(test)] mod tests_stroke; diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index 5cff5f4aed..9b8d94a31b 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -9,6 +9,7 @@ use craft::ui::bars::{BarItem, BarItems}; use craft::ui::buttons::{IconButton, PopupMark, ToggleButton}; use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Divider; +use craft::ui::layout_components::Row; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::text::NumberField; @@ -305,7 +306,7 @@ fn bar_items(buttons: impl Iterator) -> BarItems { /// Align panel's Align To says (the key object while there is one), as its own buttons do (#789), /// and the selected artboards with the Artboard tool chosen. pub(crate) fn align_buttons(_app: &mut VectorcraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (icon, b) in align_icons() { command_button(ui, bar_glyph(b).unwrap_or(icon), b); } @@ -333,7 +334,7 @@ pub(crate) fn button_enabled(app: &VectorcraftApp, b: &Button) -> bool { pub(crate) fn control_bar_strip(app: &mut VectorcraftApp, ui: &mut Ui) { let (icon, name) = align_to_icon_name(shown_align_to(app), key_is_anchor(app)); let distributes = if on_artboards(app) { artboards_distribute(app) } else { objects_aligned(app) > 1 }; - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { bar_items(align_icons().map(|(_, b)| b)).show(ui); let button = IconButton::new(IconId::new(icon)) .label(tl!("Align To:")) @@ -498,14 +499,14 @@ pub(crate) fn run_align_to(app: &mut VectorcraftApp, v: AlignTo) -> Result usize { /// The selected artboards (of `n`): while the Artboard tool is in use, those it has selected /// (Shift-click, #1139), else the active one. pub(crate) fn picked(app: &VectorcraftApp, n: usize) -> Vec { + let mut all = tool_selection(app, n); + if all.is_empty() { + all.push(selected(app, n)); + } + all +} + +/// The artboards (of `n`) the Artboard tool has selected while it is in use, sorted and once +/// each; empty with another tool or with none selected. +pub(crate) fn tool_selection(app: &VectorcraftApp, n: usize) -> Vec { let tool = (app.session.tool_id() == "artboard").then(|| app.session.tool_options()["selected"].clone()); let mut all: Vec = tool .iter() @@ -184,9 +194,6 @@ pub(crate) fn picked(app: &VectorcraftApp, n: usize) -> Vec { .filter_map(|i| usize::try_from(i).ok()) .filter(|i| *i < n) .collect(); - if all.is_empty() { - all.push(selected(app, n)); - } all.sort_unstable(); all.dedup(); all @@ -608,6 +615,16 @@ pub(crate) fn open_rearrange(app: &mut VectorcraftApp) { app.run("ui.menuDialog", json!({ "command": "artboard.rearrange" })).ok(); } +/// Open Rearrange for the selected artboards ([`picked`]), whose OK waits for a click on the +/// canvas. +pub(crate) fn open_rearrange_selected(app: &mut VectorcraftApp) { + let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); + if n > 0 { + let indices = picked(app, n); + crate::dialogs::rearrange_artboards::open_selected(app, &indices); + } +} + /// The rows of the panel's menu. pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { let command = |id: &'static str| PanelRow::Command(CommandRef::new(id)); @@ -621,6 +638,7 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { command("artboard.convertToArtboards"), PanelRow::Command(CommandRef::with_params("tool.options", json!({"tool": "artboard"}))), PanelRow::Command(CommandRef::with_params("ui.menuDialog", json!({"command": "artboard.rearrange"}))), + command("ui.artboards.rearrange"), PanelRow::Separator, command("ui.artboards.fitToArt"), ] @@ -638,12 +656,14 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { set(CommandRef::new("artboard.convertToArtboards"), tl!("Convert to Artboards"), crate::menus::enabled(app, "artboard.convertToArtboards")); set(CommandRef::with_params("tool.options", json!({"tool": "artboard"})), tl!("Artboard Options…"), n > 0); set(CommandRef::with_params("ui.menuDialog", json!({"command": "artboard.rearrange"})), tl!("Rearrange All Artboards…"), n > 1); + set(CommandRef::new("ui.artboards.rearrange"), tl!("Rearrange…"), !tool_selection(app, n).is_empty()); set(CommandRef::new("ui.artboards.fitToArt"), tl!("Fit to Artwork Bounds"), n > 0); } /// Run the panel menu's own row `id` (`ui.artboards.`) → its result; None for any other id. Rename /// opens the name field on the active artboard's row when that artboard is selected, else on the first -/// selected row. +/// selected row. Rearrange… opens Rearrange for the artboards the Artboard tool has selected, and does +/// nothing when it has none. pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option> { let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); match id { @@ -658,6 +678,11 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option } "ui.artboards.deleteEmpty" => return Some(delete_empty(app)), "ui.artboards.fitToArt" => return Some(app.run("artboard.fitToArt", json!({ "indices": picked(app, n) }))), + "ui.artboards.rearrange" => { + if !tool_selection(app, n).is_empty() { + open_rearrange_selected(app); + } + } _ => return None, } Some(Ok(Value::Null)) diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 1595711f38..beaf1466e4 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -144,7 +144,7 @@ fn list_events_and_menu_rows_reach_their_commands() { assert!(run(&mut app, "ui.artboards.rename", &json!({})).is_some()); assert_eq!(app.ui.artboards_ui.rename, Some(2)); assert!(run(&mut app, "ui.artboards.nothing", &json!({})).is_none()); - assert_eq!(menu_rows(&app).len(), 11); + assert_eq!(menu_rows(&app).len(), 12); } /// #1006: Select › All on Active Artboard selects the art of the artboard made active here, @@ -913,16 +913,17 @@ fn the_artboard_tools_menu_lists_the_pages_entries_in_order() { } /// An entry whose command can't run is left out: Cut with every artboard selected, or a locked one; -/// Delete Artboards in a document of one; Select All Artboards with all selected; Rearrange with one; -/// Fit to Artwork Bounds without art; Switch Orientation on a square artboard. +/// Delete Artboards in a document of one; Select All Artboards with all selected; Fit to Artwork +/// Bounds without art; Switch Orientation on a square artboard. Rearrange lays out the one selected +/// artboard. #[test] fn the_artboard_tools_menu_leaves_out_what_cannot_run() { let shown = |app: &VectorcraftApp, label: &str| menu_labels(&crate::menus::context_items(app)).contains(&label); let mut app = menu_app(1); - for label in ["Cut", "Delete Artboards", "Delete Empty Artboards", "Select All Artboards", "Rearrange", "Fit to Artwork Bounds"] { + for label in ["Cut", "Delete Artboards", "Delete Empty Artboards", "Select All Artboards", "Fit to Artwork Bounds"] { assert!(!shown(&app, label), "{label} with one empty artboard"); } - assert!(shown(&app, "Copy") && shown(&app, "Switch Orientation")); + assert!(shown(&app, "Copy") && shown(&app, "Switch Orientation") && shown(&app, "Rearrange")); app.session.execute("artboard.setProps", &json!({"index": 0, "width": 50})).unwrap(); assert!(!shown(&app, "Switch Orientation"), "a square artboard"); @@ -1085,6 +1086,33 @@ fn the_artboard_tools_menu_deletes_empty_artboards_and_opens_dialogs() { assert_eq!(selected(&app, 1), 0); } +/// The panel menu's Rearrange… lays out the artboards the Artboard tool has selected, once each and +/// in document order; with another tool nothing is selected by it, so Rearrange… is off and opens +/// nothing, while the other entries still act on the active artboard. The list's Rearrange button +/// stays Rearrange All Artboards. +#[test] +fn the_panels_rearrange_lays_out_only_what_the_artboard_tool_selected() { + let mut app = menu_app(3); + let ctx = app.ui_ctx.clone().expect("a window"); + app.session.set_tool_option("selected", &json!([2, 0, 2])); + assert_eq!(tool_selection(&app, 3), [0, 2]); + assert!(enabled_state(&app, "ui.artboards.rearrange")); + run(&mut app, "ui.artboards.rearrange", &Value::Null).unwrap().unwrap(); + assert!(is_open::(&app)); + assert_eq!(dialog_fields(&app)["indices"], json!([0, 2])); + cancel_open(&mut app, &ctx); + apply(&mut app, vec![PageListEvent::Rearrange]); + assert!(is_open::(&app)); + assert!(dialog_fields(&app).get("indices").is_none(), "the list's button lays out every artboard"); + cancel_open(&mut app, &ctx); + app.select_tool("selection"); + select(&mut app, 1); + assert_eq!((tool_selection(&app, 3), picked(&app, 3)), (vec![], vec![1]), "another tool"); + assert!(!enabled_state(&app, "ui.artboards.rearrange")); + run(&mut app, "ui.artboards.rearrange", &Value::Null).unwrap().unwrap(); + assert!(!is_open::(&app)); +} + /// A lock entry lists only the artboards it changes and is left out when it has none, so it never /// records an undo step that changes nothing. #[test] diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 0db7310e92..80f1be75a8 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -32,6 +32,7 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use super::{Live, active_paint, color_json, live_run, proxy_events}; use crate::VectorcraftApp; use crate::edits::{EditPath, apply_event}; +use crate::paint_preview::well_paint; /// The layout the app's panel and its menu use. const LAYOUT: ColorPanelLayout = ColorPanelLayout::FillStroke; @@ -532,11 +533,11 @@ fn switch_rgb_units(app: &mut VectorcraftApp) -> bool { app.ui.color_panel.rgb_percent } -/// The proxy's paint as one well: the colour of a solid paint or a gradient's first stop. +/// The proxy's paint as one well, drawn as the Tools panel's proxy draws it (a gradient, None or a +/// pattern as itself), and the color the panel is given for it: a solid paint's color, black for any other paint. fn well(label: &'static str, paint: &Paint, mixed: bool) -> (PairWell, Srgba) { let color = srgba(&paint.color().unwrap_or(Color::BLACK)); - // PLAN: PairWell::paint (wg.W48) would also show gradients and None as they are. - (PairWell::new(label, if mixed { Mixed::Mixed } else { Mixed::Same(color) }), color) + (PairWell::paint(label, if mixed { Mixed::Mixed } else { Mixed::Same(well_paint(paint, &|_| None)) }), color) } /// Draw numeric paint controls and run what they report. diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 102bf09995..e63fc09e7a 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -381,3 +381,26 @@ fn picked_mesh_points_are_the_color_the_panel_shows_and_edits() { assert_eq!(picked(&app), vec![0, middle], "the Shift-click adds the top middle point"); assert_eq!(crate::panels::mixed_paints(&app, &ctx), (true, false), "picking recomputes it"); } + +/// The panel's Fill and Stroke wells show a gradient and None as the Tools panel's proxy does, +/// not as black. +#[test] +fn the_wells_show_a_gradient_and_none_as_the_tools_proxy_does() { + use crate::tests::panel_harness::Panel; + let painted = || { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app + }; + let color = Panel::new(painted(), show); + let tools = Panel::new(painted(), crate::panels::proxy); + // The wells are unnamed parts of the pair, so they are found by the value each one reads as. + let wells = tools.values(); + assert_eq!(wells.len(), 2, "the Tools proxy's two wells read as {wells:?}"); + assert_ne!(wells[0], wells[1], "a gradient and None read differently"); + for well in &wells { + assert!(color.shows_value(well), "the Color panel shows a well that reads as {well:?}"); + } +} diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index d4d09ec6c4..067f820a5a 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -16,7 +16,8 @@ use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; use craft::ui::buttons::IconButton; use craft::ui::choice::{SwatchSpacing, SwatchTable}; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _}; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow, ThumbSize}; use craft::ui::menu::PanelRow; use craft::ui::notices::Notice; @@ -518,7 +519,7 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { d.sel = i; } sliders(ui, &mut d, &mut mode, &mut held); - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let hex = d.colors.get(d.sel).map(hex_rgba).unwrap_or(Rgba::rgb(0, 0, 0)); let mut edited = hex; HexField::hex(tl!("Color"), Bind::bound(&mut edited)).show(ui); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 7d10ca7d0b..57b12524ee 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -20,6 +20,13 @@ //! that color. The markers follow the current color, and a click on one applies its color as a //! pick does. //! +//! The panel menu's Show Opacity adds a row under the wheel or the box that sets the opacity of +//! what the panel edits: the fill item (`paint.setFill {opacity}`), the stroke item +//! (`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the +//! first stop or point when none is selected, as for a color pick). The row is gray with nothing +//! selected, for an object selected in a symbol instance, and when the fill or stroke item it +//! would set is on type characters or missing. +//! //! Panel menu › Show Color Vision Preview adds a row under the wheel or the box with the color as //! simulated for protanopia, deuteranopia and tritanopia, through the simulations View › Proof //! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the @@ -40,7 +47,7 @@ //! preferences too. //! //! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule, -//! Show Color Vision Preview and Show Document Colors are kept with the preferences +//! Show Opacity, Show Color Vision Preview and Show Document Colors are kept with the preferences //! (`ui.colorWheel`). use std::hash::{Hash, Hasher}; @@ -48,6 +55,7 @@ use std::sync::Arc; // PLAN: assumed `craft-color-ui`, `craft-theme`, `craft-behavior` and `craft-keymap` are dependencies of // vectorcraft-ui-egui (Cargo.toml is not in this set's table); `craft_ui` does not re-export them at the base. +use craft::behavior::ColumnWidth; use craft::behavior::Mixed; use craft::behavior::Selection; use craft::color_ui::AreaMode; @@ -57,7 +65,8 @@ use craft::theme::{ColorModel, HsbModel, ModelValues, RgbModel, Srgba}; use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Shade, Text}; -use craft::ui::layout_components::Stack; +use craft::ui::layout::CellAlign; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Label; @@ -78,6 +87,10 @@ use crate::edits::{EditPath, apply_edits}; pub const ID: &str = "colorWheel"; +/// The columns of the panel's top row: the proxy as wide as its content, and the wheel or the box beside it in the +/// rest of the width. +const BESIDE: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; + /// What the panel shows right of the proxy: the wheel, or the box (a color field and a channel /// strip). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] @@ -170,6 +183,9 @@ pub struct Settings { /// The rule of Show Harmony, one of [`harmony_rules`]. #[serde(serialize_with = "serialize_rule", deserialize_with = "deserialize_rule")] pub harmony_rule: Harmony, + /// Show Opacity: the opacity row under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub opacity: bool, /// Show Color Vision Preview: the row of simulated colors under the wheel or the box. A saved /// `true` shows the row and any other value hides it. #[serde(deserialize_with = "crate::panels::color::deserialize_lenient_bool")] @@ -222,6 +238,7 @@ impl Default for Settings { gamut: false, harmony: false, harmony_rule: Harmony::Complementary, + opacity: false, vision: false, document_colors: false, } @@ -274,12 +291,12 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { @@ -290,7 +307,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result<(), String> { - const KEYS: [&str; 8] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "vision", "documentColors"]; + const KEYS: [&str; 9] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "opacity", "vision", "documentColors"]; match p { Value::Null => {} Value::Object(o) => { @@ -339,6 +356,9 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S })? } } + if let Some(on) = crate::menus::opt_bool(p, "opacity")? { + set.opacity = on; + } if let Some(on) = crate::menus::opt_bool(p, "vision")? { set.vision = on; } @@ -411,6 +431,7 @@ fn items(set: &Settings, srgb: bool) -> Vec { json!({ "harmonyRule": rule.id() }), )); } + out.push(item("opacity".into(), tl!("Show Opacity"), set.opacity, true, json!({ "opacity": !set.opacity }))); out.push(item("vision".into(), tl!("Show Color Vision Preview"), set.vision, true, json!({ "vision": !set.vision }))); out.push(item( "documentColors".into(), @@ -424,7 +445,7 @@ fn items(set: &Settings, srgb: bool) -> Vec { /// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Out-of-Gamut /// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; Show -/// Color Vision Preview; and Show Document Colors. +/// Opacity; Show Color Vision Preview; and Show Document Colors. pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { let command = |row: String| PanelRow::Command(CommandRef::new(row_id(&row))); let mut rows = vec![command("view.wheel".into()), command("view.box".into())]; @@ -435,7 +456,7 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { rows.push(PanelRow::Separator); rows.extend(["gamut", "sliders.hsl", "sliders.oklch", "harmony"].map(|row| command(row.into()))); rows.push(PanelRow::Submenu(Label::from(tl!("Harmony Rule").to_string()), harmony_rules().map(|rule| command(rule_row_id(rule))).collect())); - rows.extend(["vision", "documentColors"].map(|row| command(row.into()))); + rows.extend(["opacity", "vision", "documentColors"].map(|row| command(row.into()))); rows } @@ -521,6 +542,8 @@ pub struct WheelUi { oklch_tracks: [Option<([u64; 3], Vec)>; 3], /// The slider rows whose drag previews on an open interaction, until it is released. rows_live: Option, + /// Whether a drag of the Show Opacity row previews on an open interaction, until it is released. + opacity_live: bool, } /// The colors the row shows and whether they are the selection's, read with `color.used` once per @@ -1051,6 +1074,100 @@ fn hsl_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pic }); } +/// The opacity (0 to 1) the row shows for `tgt` and whether the row can set it: the selected +/// gradient stop's or freeform point's (the first when none is selected, as [`wheel_target`] +/// picks it), else that of the fill or stroke item +/// ([`vectorcraft_engine::Session::proxy_opacity`]), which nothing selected and type characters +/// do not have. A stop or point of a gradient on type characters belongs to the gradient, so the +/// row sets it. With nothing selected, or while the Live Paint Bucket paints +/// ([`vectorcraft_engine::Session::bucket_paints`]), the stop or point belongs to the defaults for +/// new art, which the row leaves alone, and an object selected in a symbol instance has no opacity +/// the row can set. +fn shown_opacity(app: &VectorcraftApp, tgt: &Target) -> (f32, bool) { + let stroke = !app.session.fill_active; + let selected = !app.session.bucket_paints() && app.session.active().is_some_and(|d| !d.selection.is_empty() && d.selection.symbol_part.is_none()); + let point = |index: usize| match super::active_paint(app) { + Paint::Gradient(g) => super::gradient::shown_points(&g).points.get(index).map(|p| p.opacity), + _ => None, + }; + let found = match tgt { + _ if !selected => None, + Target::Stop { paint: Paint::Gradient(g), index, .. } => g.gradient.stops.get(*index).map(|s| s.opacity), + Target::Point { index, .. } => point(*index), + _ => app.session.proxy_opacity(stroke), + }; + (found.unwrap_or(1.0), found.is_some()) +} + +/// Set the opacity (0 to 1) of what the row edits for `tgt`: a stop through the Gradient panel's +/// edit, a freeform point through `paint.freeform.setPoint`, else the fill or stroke item through +/// `paint.setFill` or `paint.setStroke`. A drag previews and commits as one undo step. +fn apply_opacity(app: &mut VectorcraftApp, tgt: &Target, o: f32, phase: Live) { + let o = o.clamp(0.0, 1.0); + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.opacity = o; + } + super::gradient::set_stops_keeping_models(app, &stops, None, phase); + } + Target::Point { index, .. } => { + let p = json!({"index": index, "opacity": o, "stroke": !app.session.fill_active}); + super::live_run(app, "Opacity", "paint.freeform.setPoint", p, phase); + } + _ => { + let cmd = super::proxy_cmd(app, false); + super::live_run(app, "Opacity", cmd, json!({"opacity": f64::from(o) * 100.0}), phase); + } + } +} + +/// End the drag of the Show Opacity row when the row is hidden (`ui.colorWheel {opacity: false}`) +/// or turned gray before the release: the preview is kept as one undo step and the interaction +/// ends. +fn end_opacity_drag(app: &mut VectorcraftApp, panel: &mut WheelUi) { + if !panel.opacity_live { + return; + } + if app.session.in_interaction() + && let Err(e) = app.session.commit_interaction() + { + app.status(e.to_string()); + } + app.sync_views(); + panel.opacity_live = false; +} + +/// The Show Opacity row: a slider whose track shows `color` through `cms` from clear to solid over +/// the transparency checkerboard, and a percent field. Gray when [`shown_opacity`] finds nothing +/// to set. +fn opacity_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, tgt: &Target, color: &Color, cms: &Cms) { + let (o, live) = shown_opacity(app, tgt); + let [r, g, b] = cms.display_rgb(color).map(|v| v.clamp(0.0, 1.0)); + let track = vec![Srgba::new(r, g, b, 0.0), Srgba::new(r, g, b, 1.0)]; + // The row reads dim and takes no edit with nothing it can set. + Stack::new().enabled(live).show(ui, |ui, _| { + let rule = super::whole_steps(0.0..=100.0); + let row = ChannelRow::new(tl!("Opacity").to_string(), Bind::given(f64::from(o) * 100.0), rule) + .unit(ChannelUnit::Percent) + .track(track.clone()) + .checker(true); + if let Some(edit) = row.show(ui) + && live + { + apply_edits(app, &edit, EditPath::Preview, |app, v, phase| { + apply_opacity(app, tgt, (*v / 100.0) as f32, phase); + panel.opacity_live = phase == Live::Dragging; + }); + } + }); + // A drag whose row turned gray reports no release. + if !live { + end_opacity_drag(app, panel); + } +} + /// The wheel: the hue ring around the saturation and brightness square, with Show Harmony's markers /// on the ring. A click on a marker applies its color; a press held on one keeps the ring from /// picking. @@ -1107,29 +1224,48 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) { let cx = Pick { tgt: &tgt, color, cms: &cms, behind, cmyk_doc, shown: hsb }; let set = app.ui.color_wheel.clone(); let now = ui.input(|i| i.time); - ui.horizontal_top(|ui| { - ui.vertical(|ui| super::proxy(app, ui)); + // The stack's gap separates the rows. + Stack::new().show(ui, |ui, _| show_rows(app, panel, ui, &cx, &set, now)); +} + +/// The panel's rows: the Fill/Stroke proxy beside the box or the wheel, level with its top, then the slider rows, +/// the color vision row and the document colors row that `set` turns on. +fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings, now: f64) { + Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| { + super::proxy(app, ui); match set.view { - View::Box => show_box(app, panel, ui, &cx, &set), - View::Wheel => show_wheel(app, panel, ui, &cx, &set), + View::Box => { + Row::new().fill_width().show(ui, |ui, _| show_box(app, panel, ui, cx, set)); + } + View::Wheel => show_wheel(app, panel, ui, cx, set), } }); + if set.opacity { + ui.add_space(4.0); + let shown = color.unwrap_or(app.session.last_solid); + let owner = color.map(|c| Owner::of(app, &tgt, c)); + opacity_row(app, panel, ui, &tgt, &shown, &cms); + // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the + // HSB picked last stays with the new gradient. + if let (Some(c), Some(was)) = (color, owner) + && let Some((remembered, ..)) = &mut panel.hsb + && *remembered == was + { + *remembered = Owner::of(app, &tgt, c); + } + } else { + end_opacity_drag(app, panel); + } match set.sliders { Sliders::None => {} - Sliders::Oklch => { - ui.add_space(4.0); - oklch_rows(app, panel, ui, &cx); - } - Sliders::Hsl => { - ui.add_space(4.0); - hsl_rows(app, panel, ui, &cx); - } + Sliders::Oklch => oklch_rows(app, panel, ui, cx), + Sliders::Hsl => hsl_rows(app, panel, ui, cx), } // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`), or turned gray // (OKLCH rows after the working RGB space stops being sRGB), reports no release: its preview is // kept as one undo step and the interaction ends. let sliders = app.ui.color_wheel.sliders; - if panel.rows_live.is_some_and(|rows| rows != sliders || (rows == Sliders::Oklch && !cms.rgb_is_srgb())) { + if panel.rows_live.is_some_and(|rows| rows != sliders || (rows == Sliders::Oklch && !cx.cms.rgb_is_srgb())) { if app.session.in_interaction() && let Err(e) = app.session.commit_interaction() { @@ -1139,12 +1275,11 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) { panel.rows_live = None; } if set.vision { - ui.add_space(4.0); - vision_row(ui, &cms, color.as_ref()); + vision_row(ui, cx.cms, cx.color.as_ref()); } if set.document_colors - && let Some(u) = document_colors_row(app, panel, ui, &cms, now) + && let Some(u) = document_colors_row(app, panel, ui, cx.cms, now) { - apply_used(app, &tgt, &u, behind); + apply_used(app, cx.tgt, &u, cx.behind); } } diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 469effeec6..e323f23620 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -3,6 +3,8 @@ //! 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 std::sync::Arc; + use craft::keymap::CommandRef; use craft::ui::contract::{Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Shade, Text}; @@ -39,8 +41,9 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { } /// `document.info` with its categories, fetched again only when the document, the scope or the -/// artboards the Artboard tool has selected change. -pub(crate) fn info(app: &mut VectorcraftApp) -> Option { +/// artboards the Artboard tool has selected change. A frame that fetches nothing returns the stored +/// result without copying it and stores nothing; a failed fetch leaves the stored result as it was. +pub(crate) fn info(app: &mut VectorcraftApp) -> Option> { let selection_only = app.ui.doc_info.selection_only; let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; let st = app.session.active()?; @@ -48,10 +51,10 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Option { if let Some((cached, info)) = &app.canvas.doc_info && *cached == key { - return Some(info.clone()); + return Some(Arc::clone(info)); } - let info = app.session.execute("document.info", &json!({ "selectionOnly": selection_only })).ok()?; - app.canvas.doc_info = Some((key, info.clone())); + let info = Arc::new(app.session.execute("document.info", &json!({ "selectionOnly": selection_only })).ok()?); + app.canvas.doc_info = Some((key, Arc::clone(&info))); Some(info) } @@ -230,14 +233,39 @@ fn font_detail_value(e: &Value) -> Option { } } -/// An `imageObjects` entry as Linked Images and Embedded Images show it: its size in pixels, and -/// for a linked image the file it shows. +/// An `imageObjects` entry as Linked Images and Embedded Images show it: its format, its size in +/// pixels, and for a linked image its resolution and the file it shows, for an embedded one the +/// memory its pixels take. Format names and file names stay as they are. fn image_value(o: &Value) -> Option { + use vectorcraft_engine::cmd::{byte_size, ppi_number}; + let format = match &o["format"] { + Value::Null => tl!("Unknown format"), + f => f.as_str()?, + }; let size = crate::i18n::fmt( tl!("{width} × {height} px"), &[("width", &o["width"].as_u64()?.to_string()), ("height", &o["height"].as_u64()?.to_string())], ); - if o["linked"] == true { Some(crate::i18n::fmt(tl!("{size} — {file}"), &[("size", &size), ("file", o["file"].as_str()?)])) } else { Some(size) } + let detail = if o["linked"] == true { + match &o["effectivePpi"] { + Value::Null => tl!("resolution unavailable").to_string(), + ppi => { + let (x, y) = (ppi_number(ppi.get(0)?.as_f64()?), ppi_number(ppi.get(1)?.as_f64()?)); + if x == y { crate::i18n::fmt(tl!("{n} ppi"), &[("n", &x)]) } else { crate::i18n::fmt(tl!("{x} × {y} ppi"), &[("x", &x), ("y", &y)]) } + } + } + } else { + match &o["memoryBytes"] { + Value::Null => tl!("memory unavailable").to_string(), + bytes => crate::i18n::fmt(tl!("estimated memory {memory}"), &[("memory", &byte_size(bytes.as_u64()?))]), + } + }; + let shown = crate::i18n::fmt(tl!("{format}; {size}; {detail}"), &[("format", format), ("size", &size), ("detail", &detail)]); + if o["linked"] == true { + Some(crate::i18n::fmt(tl!("{size} — {file}"), &[("size", &shown), ("file", o["file"].as_str()?)])) + } else { + Some(shown) + } } /// A `repeatObjects` entry as Repeat Objects shows it: its kind and the number of instances it @@ -583,7 +611,7 @@ mod tests { let gone = fonts.iter().find(|(l, _)| l.starts_with("Qx Absent Family")).unwrap_or_else(|| panic!("{fonts:?}")).1.clone(); assert!(gone == "fehlt" || gone.starts_with("fehlt: angezeigt in "), "{gone}"); assert_eq!(images.len(), 1); - assert!(images[0].1.ends_with(" px") && images[0].1.contains(" × "), "{images:?}"); + assert!(images[0].1.contains(" × ") && images[0].1.contains(" px; geschätzter Speicher ") && images[0].1.ends_with(" B"), "{images:?}"); // A swatch named like a kind keeps its name; the gradient named by its kind is translated. assert_eq!(value(&gradients, "Glow"), "Linear gradient, Radialer Verlauf"); assert_eq!(value(&selected, "Glow"), "Linear gradient, Radialer Verlauf"); @@ -593,6 +621,54 @@ mod tests { assert!(report.contains("Units: Millimeters\n") && report.contains("Radial Repeat, 6 instances"), "{report}"); } + /// Linked Images and Embedded Images show each image's format, size, resolution or memory in + /// the interface language, the format and file names as they are; values that do not fit an + /// image entry are shown as `document.info` gives the row. + #[test] + fn image_details_show_in_the_interface_language() { + let linked = |format: Value, ppi: Value| json!({"name": "a.png", "width": 3, "height": 2, "linked": true, "file": "/art/a.png", "format": format, "effectivePpi": ppi}); + let embedded = + |memory: Value| json!({"name": "Image", "width": 3, "height": 2, "linked": false, "file": null, "format": "PNG", "memoryBytes": memory}); + let shown = || { + [ + linked(json!("PNG"), json!([150.0, 150.0])), + linked(json!(null), json!([144.0, 72.0])), + linked(json!("TIFF"), json!(null)), + embedded(json!(1536)), + embedded(json!(null)), + ] + .map(|o| image_value(&o)) + }; + assert_eq!( + shown(), + [ + "PNG; 3 × 2 px; 150 ppi — /art/a.png", + "Unknown format; 3 × 2 px; 144 × 72 ppi — /art/a.png", + "TIFF; 3 × 2 px; resolution unavailable — /art/a.png", + "PNG; 3 × 2 px; estimated memory 1.5 KiB", + "PNG; 3 × 2 px; memory unavailable", + ] + .map(|v| Some(v.to_string())) + ); + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let german = shown(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!( + german, + [ + "PNG; 3 × 2 px; 150 ppi – /art/a.png", + "Unbekanntes Format; 3 × 2 px; 144 × 72 ppi – /art/a.png", + "TIFF; 3 × 2 px; Auflösung nicht verfügbar – /art/a.png", + "PNG; 3 × 2 px; geschätzter Speicher 1.5 KiB", + "PNG; 3 × 2 px; Speicher nicht verfügbar", + ] + .map(|v| Some(v.to_string())) + ); + assert_eq!(image_value(&linked(json!("PNG"), json!([150.0]))), None); + assert_eq!(image_value(&embedded(json!("big"))), None); + } + /// Document shows the transparency settings with their values in the interface language (two /// custom grid colors as they are), and while the Artboard tool is the current tool the /// artboards it has selected, following its selection without an edit to the document. @@ -642,6 +718,151 @@ mod tests { assert_eq!(custom.as_deref(), Some("#ff0000, #00ff00")); } + /// The by-value cache the panel kept before its result was shared, with the same key. + type CopiedCache = Option<((u64, u64, bool, Value), Value)>; + + /// `document.info` read as the panel read it before its result was shared: the stored result + /// copied out by value on every call, kept in `cache` so it does not touch the panel's. + fn copied_info(app: &mut VectorcraftApp, cache: &mut CopiedCache) -> Option { + let selection_only = app.ui.doc_info.selection_only; + let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; + let st = app.session.active()?; + let key = (st.uid, st.revision, selection_only, artboard_tool); + if let Some((cached, info)) = cache.as_ref() + && *cached == key + { + return Some(info.clone()); + } + let info = app.session.execute("document.info", &json!({ "selectionOnly": selection_only })).ok()?; + *cache = Some((key, info.clone())); + Some(info) + } + + /// A frame that fetches nothing keeps the stored `document.info` result without a copy and + /// shows the same rows; another document (at the same revision), an edit, Selection Only and + /// the Artboard tool's options each store a new one, and a category does not. With no + /// document nothing is fetched and the stored result stays as it was. + #[test] + fn frames_that_fetch_nothing_reuse_the_cached_rows() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let mut old: CopiedCache = None; + let mut frame = |app: &mut VectorcraftApp| { + let text = crate::tests_labels::painted_text(app, show); + let Some((key, stored)) = app.canvas.doc_info.clone() else { panic!("nothing stored") }; + // The rows are the ones the by-value read gives for the same state. + let has_doc = app.session.active().is_some(); + assert_eq!(has_doc.then(|| (*stored).clone()), copied_info(app, &mut old), "the same rows as before"); + (key, stored, text) + }; + let (_, first, text) = frame(&mut app); + assert!(text.contains("Color Mode") && text.contains("Artboard 1"), "{text}"); + let (_, same, again) = frame(&mut app); + assert!(Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new result"); + assert!(Arc::ptr_eq(&info(&mut app).unwrap(), &same), "the stored result is returned without a copy"); + assert_eq!(text, again); + // Another document at the same revision. + let revision = |app: &VectorcraftApp| app.session.active().map(|st| st.revision); + let at = revision(&app); + let before = app.session.active().map(|st| st.uid); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(revision(&app), at, "both documents are at the same revision"); + let (key, other, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&same, &other), "another document stores a new result"); + assert_ne!(Some(key.0), before); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let (_, edited, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&other, &edited), "an edit stores a new result"); + assert!(shown_rows(&edited, "objects").contains(&("Paths".into(), "1".into())), "{:?}", shown_rows(&edited, "objects")); + run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap(); + let (_, selection, text) = frame(&mut app); + assert!(!Arc::ptr_eq(&edited, &selection), "Selection Only stores a new result"); + assert!(text.contains("(selection)"), "{text}"); + run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap(); + run(&mut app, "ui.docInfo.category", &json!({"category": "objects"})).unwrap().unwrap(); + let (_, all, _) = frame(&mut app); + let (_, category, _) = frame(&mut app); + assert!(Arc::ptr_eq(&all, &category), "a category filters the stored result"); + run(&mut app, "ui.docInfo.category", &json!({"category": ""})).unwrap().unwrap(); + app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + let (_, two, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&category, &two), "a new artboard stores a new result"); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0])); + let (_, tool, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&two, &tool), "the Artboard tool stores a new result"); + let artboard_rows = |i: &Value| shown_rows(i, "document").iter().filter(|(l, _)| l == "Artboard").count(); + assert_eq!(artboard_rows(&tool), 1); + app.session.set_tool_option("selected", &json!([0, 1])); + let (_, picked, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&tool, &picked), "the Artboard tool's options store a new result"); + assert_eq!(artboard_rows(&picked), 2); + let (_, kept, _) = frame(&mut app); + assert!(Arc::ptr_eq(&picked, &kept)); + app.select_tool("selection"); + let (key, away, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&kept, &away), "another tool stores a new result"); + assert_eq!(key.3, Value::Null); + // With no document the panel shows its empty state and keeps the stored result. + app.session.execute("file.close", &json!({})).unwrap(); + app.session.execute("file.close", &json!({})).unwrap(); + let (_, closed, text) = frame(&mut app); + assert!(Arc::ptr_eq(&away, &closed), "nothing is fetched or stored without a document"); + assert!(text.contains("No document"), "{text}"); + } + + /// Time a frame's read of Document Info's result for a document with 5,000 objects painted + /// with a gradient (a row each): by the by-value read before the result was shared + /// ([`copied_info`]) and by [`info`]. Per run each side reads 2,000 times; the two sides + /// alternate, and the median time per read of 7 runs is printed, as this thread's CPU time + /// where the system reports it (Linux), else wall-clock time. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib doc_info::tests::cached_rows_read_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn cached_rows_read_timing() { + const OBJECTS: usize = 5_000; + const READS: u32 = 2_000; + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); + let mut ids = vec![]; + for i in 0..OBJECTS { + let r = json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10}); + ids.push(app.session.execute("shape.rectangle", &r).unwrap()["id"].clone()); + } + let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + app.session.execute("paint.setFill", &json!({"ids": ids, "gradient": ramp})).unwrap(); + let mut old: CopiedCache = None; + let rows = + info(&mut app).unwrap()["sections"].as_array().into_iter().flatten().map(|s| s["rows"].as_array().map_or(0, Vec::len)).sum::(); + assert_eq!(copied_info(&mut app, &mut old), info(&mut app).map(|i| (*i).clone())); + let time = |app: &mut VectorcraftApp, f: &mut dyn FnMut(&mut VectorcraftApp) -> usize| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..READS { + assert!(f(app) > 0); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(READS) / 1000.0 + }; + let sections = |i: &Value| i["sections"].as_array().map_or(0, Vec::len); + let (mut copied, mut shared) = (vec![], vec![]); + for _ in 0..7 { + copied.push(time(&mut app, &mut |app| copied_info(app, &mut old).map_or(0, |i| sections(&i)))); + shared.push(time(&mut app, &mut |app| info(app).map_or(0, |i| sections(&i)))); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{OBJECTS} objects, {rows} rows; {clock} per read, median of 7 runs"); + eprintln!("copied ({READS} reads a run): {:>10.3} us {copied:.3?}", median(&mut copied)); + eprintln!("shared ({READS} reads a run): {:>10.3} us {shared:.3?}", median(&mut shared)); + } + /// A Repeat object's counts take each language's plural forms, and a grid that draws fewer /// instances than its rows and columns give is followed by the number it draws. #[test] diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 0ffa35a7b4..0633f3fbcd 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -20,17 +20,20 @@ use craft::behavior::{EditEvent, GesturePhase, IconId, Selection}; use craft::ui::contract::{ Bind, DropAt, DropPayload, DropPlace, Entry, ListDrag, MemoProps, PopupKind, ReorderMove, SelectMode, Show as _, ShowContainer as _, Trigger, }; -use craft::ui::display::Divider; +use craft::ui::display::{Divider, Picture, PictureSize}; +use craft::ui::list::ThumbAspect; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::patterns::presets::{ PickerField, PresetBrowser, PresetDrop, PresetEvent, PresetFns, PresetPicker, PresetReorder, PresetRow, PresetSource, PresetState, PresetView, }; use craft::ui::primitives::{ - ContentPainterCx, IconSpec, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, + ContentPainterCx, IconSpec, PaintShape, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, }; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; +use craft::ui::runtime::env::Env; use craft::ui::sections::{FooterAction, FooterBar, FooterOutput, Panel}; -use egui::{Color32, Rect, Sense, TextureHandle, Ui, pos2, vec2}; +use craft::ui::style::DataColor; +use egui::{Color32, Rect, TextureHandle, Ui, pos2}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::style_libs::STYLE_LIBRARIES; @@ -130,9 +133,6 @@ fn thumbnails(ctx: &egui::Context, salt: &'static str) -> Thumbnails { Thumbnails::in_context(ctx, salt, ThumbnailOptions::new()) } -/// Side of the large preview shown while the pointer rests on a style. -const LARGE: f32 = 132.0; - thread_local! { // PLAN: the sheet drops RENDERER, but `render` and `render_object` need one renderer that outlives a call. static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); @@ -337,7 +337,7 @@ fn paint_thumb(cx: &ContentPainterCx<'_>, rect: Rect, thumbs: &Thumbnails ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), - None => ui.painter().rect_filled(r, 0.0, Color32::WHITE), - }; + ui.set_max_width(side); + let texture = tex.as_ref().map(TextureHandle::id); + // Decorative: the style's name below it says what it shows. + Picture::painter("", ThumbAspect::SQUARE, move |cx, rect| { + cx.with_draw(|draw| match texture { + Some(id) => draw.texture(rect, id, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))), + None => draw.data_fill(&PaintShape::Rect(rect, egui::CornerRadius::ZERO), DataColor::new(Color32::WHITE)), + }) + }) + .extent(PictureSize::Fill) + .show(ui); ui.label(key); } diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index b7d5fdc67d..2dd7f1f39f 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -14,6 +14,7 @@ use craft::ui::buttons::{IconButton, PopupMark, ToggleButton}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::form::Field; +use craft::ui::layout_components::Row; use craft::ui::menu::{Menu, PanelRow}; use craft::ui::pickers::Select; use craft::ui::popover::Popover; @@ -438,8 +439,8 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { if text_style(app).is_none() { return true; } - // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row; `horizontal` stands in until it lands. - ui.horizontal(|ui| { + // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row. + Row::new().show(ui, |ui, _| { let link = crate::panels::option_link(tl!("Paragraph:")).tooltip(tl!("Paragraph options")).show(ui); Popover::new(tl!("Paragraph"), Bind::kept()) .overlay(|overlay| overlay.opened_by(&link.response, Trigger::Click)) @@ -660,7 +661,7 @@ fn list_control(ui: &mut Ui, kind: ListKind, pressed: bool, entries: &[Entry toggle_list(app, ListKind::Bullets), diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c339c73b6e..c4a5b91318 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -10,8 +10,9 @@ use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSec use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; use craft::ui::choice::Segmented; -use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, TooltipSpec}; +use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec}; use craft::ui::form::Field; +use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; use craft::ui::popover::Popover; @@ -390,7 +391,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { arrow_rows(app, ui, st.as_ref()); ui.separator(); Field::new(tl!("Profile")).show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { profile_select(app, ui); flip_buttons(app, ui, st.as_ref()); }); @@ -410,11 +411,14 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { (st.and_then(|s| s.end_arrow.clone()), false, tl!("End arrowhead"), "endArrow"), ]; Field::new(tl!("Arrowheads")).show(ui, |ui, _| { - ui.horizontal(|ui| { + // The two heads share the width the Swap button leaves; a field too narrow for all three puts Swap on a + // new line. + Row::new().fill_width().wrap(true).show(ui, |ui, _| { for (head, start, label, key) in &heads { let (start, key) = (*start, *key); let out = Select::new(*label, Bind::given(head.clone()), &entries) .picture(move |a, cx, rect| arrow_thumb(cx, rect, a.as_ref(), start)) + .sizing(Sizing::FillWidth) .show(ui); // A custom head goes with its art, as document.inspect reports it. if let Some(a) = out.events.landed() { diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 9bc58b6f6f..851717edf8 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -18,10 +18,10 @@ use craft::ui::contract::{Bind, DropAt, DropPlace, ListDrag, MemoProps, SelectMo use craft::ui::contract::{Entry, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::presets::{PresetEvent, PresetView, ThumbInfo}; -use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec, StrokeWidth}; +use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec, PaintShape, StrokeWidth}; use craft::ui::runtime::env::Label; use craft::ui::sections::{FooterAction, FooterBar}; -use craft::ui::style::UiTokens; +use craft::ui::style::{DataColor, UiTokens}; use egui::{Color32, Painter, Rect, Response, Shape, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::{Value, json}; use vectorcraft_color::swatch::REGISTRATION; @@ -543,10 +543,7 @@ pub(super) fn paint_swatch(cx: &ContentPainterCx<'_>, rect: Rect, paint: &Paint, match paint { _ if paint.is_registration() => registration_mark(cx, inner), Paint::Solid { .. } => {} - Paint::None => { - let slash = Stroke::new(cx.stroke_width(StrokeWidth::Medium), Color32::from_rgb(0xe0, 0x20, 0x20)); - cx.data_shapes([Shape::line_segment([inner.left_bottom(), inner.right_top()], slash)]); - } + Paint::None => none_slash(cx, inner), Paint::Pattern { .. } if pattern.is_some_and(|doc| pattern_thumb_in(doc, cx, inner, paint)) => {} _ => crate::paint_preview::paint_rect(cx, inner, paint), } @@ -593,6 +590,15 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: & true } +/// The red of None's slash on a swatch tile and of a disabled opacity mask's cross, drawn on the document's white or +/// black paper. It is the same in every theme. +pub(super) const OFF_MARK: Color32 = Color32::from_rgb(0xe0, 0x20, 0x20); + +/// None's slash across `r`, from its lower left to its upper right, in [`OFF_MARK`] at the medium stroke width. +fn none_slash(cx: &ContentPainterCx<'_>, r: Rect) { + cx.with_draw(|draw| draw.stroke(&PaintShape::Path(vec![r.left_bottom(), r.right_top()]), StrokeWidth::Medium, DataColor::new(OFF_MARK))); +} + /// Registration's mark: a black target on white. fn registration_mark(cx: &ContentPainterCx<'_>, r: Rect) { let c = r.center(); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index f828a67883..2186d75339 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -82,8 +82,10 @@ fn a_drag_in_the_field_is_one_undo_step_and_the_strip_sets_the_channel() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let harmony = - json!({"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "documentColors": false}); + let harmony = json!({ + "sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "vision": false, + "documentColors": false + }); let with = |v: serde_json::Value| { let mut v = v; v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone()); @@ -133,9 +135,15 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors"); + assert_eq!( + e, + "unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors" + ); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors"); + assert_eq!( + e, + "unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors" + ); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index bcca0605a2..87d581ca8e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -83,7 +83,8 @@ fn ui_color_wheel_sets_gamut() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let with = |v: serde_json::Value| { let mut v = v; - let rest = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false, "documentColors": false}); + let rest = + json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "opacity": false, "vision": false, "documentColors": false}); v.as_object_mut().unwrap().extend(rest.as_object().unwrap().clone()); v }; diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs new file mode 100644 index 0000000000..27def08cd7 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -0,0 +1,351 @@ +//! The Color Wheel panel's Show Opacity row drawn headless through the `Fixture`: the setting and +//! `ui.colorWheel`, the slider on a fill, a gradient stop and a freeform point, the keys, screen +//! readers, the percent field and the gray row. + +use craft::ui::runtime::access::Role; +use craft::ui::testing::Target; +use craft::ui::testing::focus::AccessActionKind; +use egui::{Key, Modifiers}; +use serde_json::json; +use vectorcraft_color::Paint; +use vectorcraft_engine::Session; + +use super::color_wheel::Settings; +use super::tests_color_wheel::Panel; +use crate::VectorcraftApp; + +/// An app with a selected red rectangle and Show Opacity checked. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + app +} + +/// The node of `role` named Opacity. +fn named(p: &Panel, role: Role) -> Option { + p.fx.by_role(role).into_iter().find(|t| p.fx.tree().name_of(t.node) == Some("Opacity")) +} + +/// The row's slider. +fn slider(p: &Panel) -> Target { + named(p, Role::SLIDER).expect("the Opacity slider") +} + +/// The row's percent field. +fn field(p: &Panel) -> Target { + named(p, Role::SPIN_BUTTON).or_else(|| named(p, Role::TEXT_INPUT)).expect("the Opacity field") +} + +fn disabled(p: &Panel) -> bool { + p.fx.tree().is_disabled_key(slider(p).node) +} + +/// An AccessKit action on the slider, then two frames. +fn act(p: &mut Panel, kind: AccessActionKind) { + let t = slider(p); + p.fx.access(kind, &t).idle(2); +} + +fn fill_opacity(app: &VectorcraftApp) -> f32 { + app.session.proxy_opacity(false).expect("a fill item") +} + +fn undo_labels(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +/// The point at `f` (0 to 1) across the middle of the slider. +fn along(t: &Target, f: f32) -> egui::Pos2 { + egui::pos2(t.rect.left() + f * t.rect.width(), t.rect.center().y) +} + +/// The panel menu's Show Opacity and `ui.colorWheel {opacity}` check and uncheck the row; a bad +/// value is an error and changes nothing. +#[test] +fn show_opacity_is_a_setting_of_the_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["opacity"], json!(false)); + assert_eq!(app.run("ui.colorWheel", json!({"opacity": true})).unwrap()["opacity"], json!(true)); + let e = app.run("ui.colorWheel", json!({"opacity": "no"})).unwrap_err(); + assert_eq!(e, "`opacity` must be true or false"); + assert!(app.ui.color_wheel.opacity); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["opacity"], json!(true)); + let set = app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + assert_eq!(set["opacity"], json!(true), "another key keeps Show Opacity"); + assert_eq!(super::color_wheel::run(&mut app, "ui.colorWheel.opacity", &json!({})).unwrap().unwrap()["opacity"], json!(false)); + let p = Panel::new({ + let mut app = self::app(); + app.run("ui.colorWheel", json!({"opacity": false})).unwrap(); + app + }); + assert!(named(&p, Role::SLIDER).is_none(), "no row while unchecked"); +} + +/// The row also shows under the box, and a click at its middle sets the fill item's opacity there. +#[test] +fn the_row_shows_under_the_box_view() { + let mut app = app(); + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + let mut p = Panel::new(app); + assert!(p.fx.by_label("Color box").is_some(), "the box shows"); + let at = along(&slider(&p), 0.5); + p.fx.click_at(at).idle(2); + let o = fill_opacity(&p.app()); + assert!((o - 0.5).abs() < 0.05, "{o}"); +} + +/// A value this build does not read keeps the rest of the preferences and reads as the default. +#[test] +fn saved_settings_read_leniently() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + saved["color_panel"] = json!({"rgbPercent": true}); + for bad in [json!("box"), json!({"opacity": "yes"}), json!(7)] { + saved["color_wheel"] = bad.clone(); + let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(ui.color_wheel, Settings::default(), "{bad}"); + assert!(ui.color_panel.rgb_percent, "{bad}"); + } + saved["color_wheel"] = json!({"opacity": true, "later": 1}); + let ui: crate::UiState = serde_json::from_value(saved).unwrap(); + assert!(ui.color_wheel.opacity); +} + +/// A click at the middle of the track sets the fill item's opacity to about 50 % as one undo step +/// named Opacity, the fill keeps its color, and → then adds 1 %. +#[test] +fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { + let mut p = Panel::new(app()); + let undo = undo_labels(&p.app()).len(); + let at = along(&slider(&p), 0.5); + p.fx.click_at(at).idle(2); + let o = fill_opacity(&p.app()); + assert!((o - 0.5).abs() < 0.05, "{o}"); + let labels = undo_labels(&p.app()); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); + assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000"); + let before = (o * 100.0).round(); + let t = slider(&p); + p.fx.access(AccessActionKind::Focus, &t).key(Key::ArrowRight, Modifiers::NONE).idle(2); + assert_eq!((fill_opacity(&p.app()) * 100.0).round(), before + 1.0); +} + +/// Hiding the row during a drag on its slider keeps the opacity the drag previewed as one undo step +/// and leaves no interaction open. +#[test] +fn hiding_the_row_during_a_drag_keeps_its_opacity_as_one_undo_step() { + let mut p = Panel::new(app()); + let undo = undo_labels(&p.app()).len(); + let t = slider(&p); + let (from, to) = (along(&t, 0.5), along(&t, 0.25)); + p.fx.drag_hold_at(from, to - from); + assert!(p.app().session.in_interaction(), "the drag previews"); + let previewed = fill_opacity(&p.app()); + assert!(previewed < 0.45, "{previewed}"); + p.run("ui.colorWheel", json!({"opacity": false})); + assert!(!p.app().session.in_interaction(), "the interaction ended"); + assert!((fill_opacity(&p.app()) - previewed).abs() < 1e-6); + p.fx.release_at(to).idle(2); + assert_eq!(undo_labels(&p.app()).len(), undo + 1); +} + +/// Screen readers get a slider named Opacity with its percentage and its range, and can step it and +/// set it. +#[test] +fn screen_readers_read_and_set_the_opacity() { + let mut p = Panel::new(app()); + let numeric = p.fx.tree().numeric_of(slider(&p).node).expect("a numeric slider"); + assert_eq!(numeric.value, Some(100.0)); + assert_eq!(numeric.range, 0.0..=100.0); + act(&mut p, AccessActionKind::SetValue(25.0)); + assert!((fill_opacity(&p.app()) - 0.25).abs() < 1e-6); + act(&mut p, AccessActionKind::Decrement); + assert!((fill_opacity(&p.app()) - 0.24).abs() < 1e-6); +} + +/// The stroke proxy in front: the row sets the stroke item's opacity and leaves the fill's. +#[test] +fn with_the_stroke_in_front_the_row_sets_the_stroke() { + let mut app = app(); + app.run("paint.toggleActive", json!({})).unwrap(); + let mut p = Panel::new(app); + act(&mut p, AccessActionKind::SetValue(40.0)); + assert!((p.app().session.proxy_opacity(true).unwrap() - 0.4).abs() < 1e-6); + assert_eq!(fill_opacity(&p.app()), 1.0); +} + +/// A selected gradient stop takes the opacity, and the other stop keeps its own. +#[test] +fn a_selected_gradient_stop_takes_the_opacity() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut p = Panel::new(app); + act(&mut p, AccessActionKind::SetValue(30.0)); + let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") }; + let o: Vec = g.gradient.stops.iter().map(|s| s.opacity).collect(); + assert!((o[0] - 1.0).abs() < 1e-6 && (o[1] - 0.3).abs() < 1e-6, "{o:?}"); + assert_eq!(fill_opacity(&p.app()), 1.0, "the fill item keeps its opacity"); +} + +/// With no stop selected, the first stop takes the opacity, as it takes a color pick. +#[test] +fn without_a_selected_stop_the_first_takes_the_opacity() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + assert_eq!(app.session.selected_stop(), None); + let mut p = Panel::new(app); + act(&mut p, AccessActionKind::SetValue(30.0)); + let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") }; + let o: Vec = g.gradient.stops.iter().map(|s| s.opacity).collect(); + assert!((o[0] - 0.3).abs() < 1e-6 && (o[1] - 1.0).abs() < 1e-6, "{o:?}"); +} + +/// The hue picked last for a white gradient stop stays on the box's strip after the row sets the +/// stop's opacity. +#[test] +fn an_opacity_edit_keeps_the_hue_picked_for_a_white_stop() { + let mut app = app(); + app.run("ui.colorWheel", json!({"view": "box", "channel": "hue"})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + let mut p = Panel::new(app); + p.set("Hue", 120.0); + assert_eq!(p.number("Hue"), Some(120.0), "the strip shows the hue picked for white"); + act(&mut p, AccessActionKind::SetValue(30.0)); + let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") }; + assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops); + assert_eq!(p.number("Hue"), Some(120.0), "the strip keeps the hue after the opacity edit"); +} + +/// A drag across the slider previews and ends as one undo step named Opacity. +#[test] +fn a_drag_is_one_undo_step() { + let mut p = Panel::new(app()); + let undo = undo_labels(&p.app()).len(); + let t = slider(&p); + let (from, to) = (along(&t, 0.1), along(&t, 0.9)); + p.fx.drag_at(from, to - from).idle(2); + let o = fill_opacity(&p.app()); + assert!(o > 0.7 && o < 1.0, "{o}"); + let labels = undo_labels(&p.app()); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); + assert!(!p.app().session.in_interaction()); +} + +/// A selected object without a fill item beside one with a fill item: the row shows and sets the +/// second one's opacity. +#[test] +fn an_object_without_a_fill_item_leaves_the_row_to_the_next() { + let mut app = app(); + let first = app.session.doc().unwrap().selection.objects[0]; + app.run("appearance.removeItem", json!({"index": 0})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 50})).unwrap(); + let second = app.session.doc().unwrap().selection.objects[0]; + app.run("select.set", json!({"ids": [first.0, second.0]})).unwrap(); + let mut p = Panel::new(app); + assert!(!disabled(&p)); + act(&mut p, AccessActionKind::SetValue(45.0)); + let n = p.app().session.doc().unwrap().doc.node(second).unwrap().clone(); + assert!((n.appearance.fill().unwrap().opacity - 0.45).abs() < 1e-6); +} + +/// Type painted with a gradient: the row sets the gradient's stop, which belongs to the gradient. +#[test] +fn a_gradient_stop_on_type_takes_the_opacity() { + let mut app = app(); + app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + let mut p = Panel::new(app); + assert!(!disabled(&p)); + act(&mut p, AccessActionKind::SetValue(30.0)); + let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") }; + assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops); +} + +/// The selected freeform point takes the opacity. +#[test] +fn the_selected_freeform_point_takes_the_opacity() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {"kind": "freeform"}})).unwrap(); + let mut p = Panel::new(app); + act(&mut p, AccessActionKind::SetValue(60.0)); + let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") }; + let f = super::gradient::shown_points(&g); + assert!((f.points[0].opacity - 0.6).abs() < 1e-6, "{:?}", f.points.iter().map(|p| p.opacity).collect::>()); +} + +/// The percent field takes a typed value. +#[test] +fn the_percent_field_takes_a_typed_value() { + let mut p = Panel::new(app()); + let t = field(&p); + p.fx.click(&t).key(Key::A, Modifiers::COMMAND).type_text("35").key(Key::Enter, Modifiers::NONE).settle(); + assert!((fill_opacity(&p.app()) - 0.35).abs() < 1e-6, "{}", fill_opacity(&p.app())); +} + +/// With nothing selected, and with only type selected (its characters take the paint), the row is +/// gray and screen readers cannot set it. +#[test] +fn the_row_is_gray_with_nothing_selected_and_on_type() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut p = Panel::new(app); + assert!(disabled(&p)); + let doc = p.app().session.doc().unwrap().doc.clone(); + act(&mut p, AccessActionKind::SetValue(25.0)); + assert_eq!(*p.app().session.doc().unwrap().doc, *doc); + + let mut app = self::app(); + app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + let p = Panel::new(app); + assert!(disabled(&p)); + + // A gradient left as the default for new art: its stop is not the row's to change. + let mut app = self::app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let mut p = Panel::new(app); + assert!(disabled(&p)); + let defaults = p.app().session.paint.fill.clone(); + act(&mut p, AccessActionKind::SetValue(25.0)); + assert_eq!(p.app().session.paint.fill, defaults); + + // The Live Paint Bucket painting a gradient with an object selected: the stop is the bucket's. + let mut app = self::app(); + app.session.select_tool("livePaintBucket", Default::default()).unwrap(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let mut p = Panel::new(app); + assert!(disabled(&p)); + let defaults = p.app().session.paint.fill.clone(); + act(&mut p, AccessActionKind::SetValue(25.0)); + assert_eq!(p.app().session.paint.fill, defaults); + + // An object with a gradient fill selected in a dynamic symbol instance. + let mut app = self::app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0].0; + let inst = app.run("symbol.new", json!({"name": "One", "ids": [id], "type": "dynamic"})).unwrap()["id"].clone(); + app.run("symbol.instance.selectPart", json!({"id": inst, "path": []})).unwrap(); + let p = Panel::new(app); + assert!(disabled(&p)); +} + +/// `ui.colorWheel` answers every junk parameter, with and without a document, without a panic. +#[test] +fn ui_color_wheel_answers_junk_params_without_a_panic() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; + for mut app in [app(), VectorcraftApp::new(Session::new(), Default::default())] { + for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { + let _ = app.run("ui.colorWheel", p); + } + } +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index f2fc39ca83..863ffd36d0 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -88,7 +88,7 @@ fn with_a_none_fill_the_chips_have_no_color() { #[test] fn ui_color_wheel_sets_and_reads_the_settings() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none", "documentColors": false}); + let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "vision": vision, "sliders": "none", "documentColors": false}); assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false)); assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true)); assert_eq!(crate::control::inspect(&app, &crate::testing::ui_context())["ui"]["color_wheel"]["vision"], true); @@ -99,7 +99,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() { assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5"); assert_eq!( app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(), - "unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors" + "unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors" ); assert!(app.ui.color_wheel.vision); assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true); diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs new file mode 100644 index 0000000000..51a22a4d2b --- /dev/null +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -0,0 +1,38 @@ +//! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width. + +use super::tests_appearance::app_with_rect; +use super::*; +use crate::panel_docking::PANEL_MIN_WIDTH; +use crate::tests::panel_harness::{Panel, ROOM}; + +#[test] +fn the_arrowhead_row_stays_inside_the_stroke_panel() { + let panel = Panel::new(app_with_rect(), stroke::show); + // The Arrowheads field spans the panel's width. + let row = panel.rect("Arrowheads"); + for name in ["Start arrowhead", "End arrowhead", "Swap start and end arrowheads"] { + assert!(row.contains_rect(panel.rect(name)), "{name} at {:?} is outside the row {row:?}", panel.rect(name)); + } +} + +#[test] +fn the_color_themes_hex_row_stays_inside_a_narrow_panel() { + let mut panel = Panel::new(app_with_rect(), color_themes::show); + panel.room(egui::vec2(PANEL_MIN_WIDTH, ROOM.y)).frame(); + // The tab strip spans the panel's width. + let width = panel.rect("Color Themes"); + for name in ["Color", "Set the current fill or stroke to the selected color", "Set the selected color to the current color"] { + let at = panel.rect(name); + assert!(at.left() >= width.left() && at.right() <= width.right(), "{name} at {at:?} is outside the panel {width:?}"); + } +} + +#[test] +fn the_color_wheel_box_and_its_strip_stay_inside_the_panel() { + let mut app = app_with_rect(); + app.ui.color_wheel.view = color_wheel::View::Box; + let panel = Panel::new(app, color_wheel::show); + let (field, strip) = (panel.rect("Color box"), panel.rect("Hue")); + assert!(strip.height() <= field.height(), "the strip {strip:?} is taller than the box {field:?}"); + assert!(field.right() <= ROOM.x && strip.right() <= ROOM.x, "the box {field:?} or its strip {strip:?} runs past the panel"); +} diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index ee674781ae..1fafa33563 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -19,13 +19,15 @@ use craft::ui::list::{List, ListRow, RowEvent, ThumbSize, ThumbTarget}; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; use craft::ui::primitives::{ - ContentPainterCx, IconSpec, LoadFailure, LoadedPicture, Priority, ThumbJob, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, + ContentPainterCx, IconSpec, LoadFailure, LoadedPicture, PaintShape, Priority, StrokeWidth, ThumbJob, ThumbRender, ThumbRequest, ThumbSource, + ThumbnailOptions, Thumbnails, }; use craft::ui::primitives::{Revision, ThumbPaint}; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::runtime::env::UnitKind; +use craft::ui::style::DataColor; use craft::ui::text::NumberField; -use egui::{Color32, Stroke, Ui}; +use egui::{Color32, Ui}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Knockout, Node, NodeId, OpacityMask}; use vectorcraft_engine::cmd::TransparencyInfo; @@ -183,8 +185,7 @@ fn mask_row( if !object_state.as_ref().is_some_and(|s| store.paint(cx, rect, s, plain)) && let Some(c) = fill { - // PLAN: a colour from data should go through the content painter's data path, not the raw painter. - cx.painter.rect_filled(rect.shrink(rect.width() * 0.2), 0.0, c); + cx.data_shapes([egui::Shape::rect_filled(rect.shrink(rect.width() * 0.2), 0.0, c)]); } }; let paint_mask = move |cx: &ContentPainterCx, rect: egui::Rect| { @@ -193,9 +194,12 @@ fn mask_row( store.paint(cx, rect, s, paper); } if disabled { - let red = Stroke::new(2.0, Color32::from_rgb(220, 40, 40)); - cx.painter.line_segment([rect.left_top(), rect.right_bottom()], red); - cx.painter.line_segment([rect.right_top(), rect.left_bottom()], red); + let red = DataColor::new(super::swatches::OFF_MARK); + cx.with_draw(|draw| { + for line in [[rect.left_top(), rect.right_bottom()], [rect.right_top(), rect.left_bottom()]] { + draw.stroke(&PaintShape::Path(line.to_vec()), StrokeWidth::Thick, red); + } + }); } } else { cx.icon(rect, &IconSpec::svg(IconId::new("dc-mask-none"))); diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index d70caa18ae..6be029beba 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -363,6 +363,7 @@ fn spawn_labeled( }); let jobs = app.jobs(); app.placing.lane.push(&*jobs, "vectorcraft-place", job); + let started = crate::export_progress::now(app); app.placing.pending.push(Pending { name, label: label.clone(), @@ -375,7 +376,7 @@ fn spawn_labeled( scope: completion, token, hidden: false, - started: crate::export_progress::now(), + started, }); let status = format!("{label}…"); app.status(status.clone()); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 385600ab5a..990e449e88 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -2017,6 +2017,8 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { let mut app = VectorcraftApp::new(Session::new(), services); crate::tests_background::threaded(&mut app); app.placing.off_the_ui_thread = true; + // The app's clock stands still: a read is only old enough for its window after `age`. + app.now_override = Some(0.0); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index 1f9eae3978..f7c579337c 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -43,7 +43,7 @@ pub struct Running { pub progress: Arc, /// Continue in Background: the progress window no longer shows it. pub hidden: bool, - /// When it started, in seconds of the monotonic clock: the progress window's age. + /// [`export_progress::now`] when it started: the progress window's age. started: f64, done: Receiver, } @@ -89,7 +89,7 @@ pub fn start(app: &mut VectorcraftApp, p: Value) -> Result { }; app.host.jobs().spawn("vectorcraft-plugin", Box::new(job)); let label = format!("Running {who}…"); - let started = craft::platform::clock::monotonic_ms() / 1000.0; + let started = export_progress::now(app); let runs = &mut app.plugin_runs; runs.running.push(Running { label: label.clone(), who, params, progress: shown, hidden: false, started, done }); app.status(label.clone()); diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index aa53b3659f..ad3b05db4a 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -41,6 +41,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("scrubNumericFields", "Dragging sideways on a numeric field's label changes the field's value."), ("trackpadRotateView", "A two-finger rotate gesture on a trackpad rotates the canvas view."), ("interpolateControlPoints", "When you move anchor points, each curve with one moved end keeps its shape relative to its ends."), + ("deleteKeepsPathsJoined", "Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there."), ("holdToolKeys", "Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again."), ("holdShortcuts", "Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut."), ("keyHoldDelay", "How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut."), diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 72c5ec628c..b4693d5830 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -8,8 +8,9 @@ use std::sync::{Mutex, PoisonError}; use craft::host::{PickKind, PickRequest}; use craft::theme::Rgba; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::form::{SliderField, SliderFieldLayout}; +use craft::ui::layout_components::Row; use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PathSetting, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Map, Value, json}; @@ -350,10 +351,11 @@ impl PreferencesModel for Live<'_> { } "prefsFile" => { let (mut export, mut import, mut reset) = (false, false, false); - ui.horizontal_wrapped(|ui| { + let web = crate::io::is_web(self.app); + Row::new().wrap(true).show(ui, |ui, _| { export = Button::new(tl!("Export Preferences…")).show(ui).clicked(); // Not on the web, whose open dialog answers with the file's contents, not a path to import. - if !crate::io::is_web(self.app) { + if !web { import = Button::new(tl!("Import Preferences…")).show(ui).clicked(); } reset = Button::new(tl!("Reset Preferences")).show(ui).clicked(); diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index 7d45e37953..a715f982af 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -241,7 +241,7 @@ pub(crate) fn items_at(now: f64) -> Vec { }; let mut nodes = level(&listing.entries); let notes = [listing.truncated.then_some(TRUNCATED), listing.unreadable.then_some(UNREADABLE), note]; - nodes.extend(notes.into_iter().flatten().map(Node::heading)); + nodes.extend(notes.into_iter().flatten().map(crate::menus::placeholder)); if !nodes.is_empty() { nodes.push(Node::Separator); } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 0f302c1551..4f8bfedcba 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1642,6 +1642,7 @@ fn a_live_effect_plugin_installed_later_takes_a_shortcut_of_its_own() { #[test] fn each_filter_plugin_takes_a_shortcut_of_its_own() { use vectorcraft_plugins::wat as tpl; + let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner()); let (one, two) = ("test.UI.key_filter-one", "test.UI.key_filter-two"); let (key_one, key_two) = (format!("plugin:{one}"), format!("plugin:{two}")); let install = |id: &str, name: &str, params: &str| { @@ -1717,6 +1718,10 @@ fn a_filter_plugin_keeps_its_shortcut_when_replaced_or_reloaded() { fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { use vectorcraft_plugins::wat as tpl; let mut app = new_app(); + // The background work waits until the test runs it, which it never does: the run started from + // the key is still running when Cancel stops it, however long the frames take. + let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); + app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build()); app.session.allow_plugin_grants_from_requests(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d40fe48c3d..3a65476203 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -40,6 +40,21 @@ pub enum ViewMove { Jump, } +/// Rearrange for selected artboards, confirmed and waiting for the click on the canvas that places +/// the grid's top-left: the document (`DocState::uid`) and the tool it was confirmed in, and the +/// `artboard.rearrange` parameters, `indices` included, with the `Artboard::id` of each listed +/// artboard (`ids`), so a placement whose artboards moved in the list or were removed is dropped. +/// `armed` is false until the canvas has seen one frame of it, so the Enter that confirmed the +/// dialog does not also place the artboards. +#[derive(Clone, Debug)] +pub struct RearrangePlacement { + pub doc: u64, + pub tool: String, + pub params: Value, + pub ids: Vec, + pub armed: bool, +} + /// Per-document view (camera). #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct View { @@ -612,6 +627,10 @@ pub struct UiState { pub view: ViewFlags, #[serde(skip)] pub brush_key_color_pick: Option, + /// Rearrange for selected artboards waiting for its click on the canvas + /// (`dialogs::rearrange_artboards`). + #[serde(skip)] + pub rearrange_placement: Option, /// A control request is being answered: its caller gets what fails as its reply, so no /// dialog says it too (`io::report_write_error`). #[serde(skip)] @@ -826,7 +845,7 @@ pub struct UiState { #[serde(skip)] pub(crate) new_swatch: Option, /// Color Wheel panel: the wheel or the box, the box's channel, the slider rows, the - /// out-of-gamut shading and the color vision row + /// out-of-gamut shading, Show Opacity and the color vision row /// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]). #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] pub color_wheel: crate::panels::color_wheel::Settings, @@ -1400,6 +1419,7 @@ impl Default for UiState { help_bar: true, view: ViewFlags::default(), brush_key_color_pick: None, + rearrange_placement: None, answering_control: false, group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), touch_drawing_tool: None, diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index ad10a9bac5..dbb5a87b32 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -56,3 +56,8 @@ mod tab_reorder; pub(crate) mod taskbar; mod toolescape; mod trace_runs; + +/// Installed plug-ins are process-wide. Tests that install filter plug-ins under a name another +/// test also installs, or that check how plug-ins sharing a name are told apart, hold this lock +/// while their plug-ins are installed, so each sees only its own plug-ins under that name. +pub(super) static SHARED_PLUGIN_NAMES: std::sync::Mutex<()> = std::sync::Mutex::new(()); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0949ef8c80..574da463f5 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -306,6 +306,12 @@ impl Panel { self.fixture.tree().description_of(self.look(name).node).map(str::to_owned) } + /// The value texts of the latest frame's controls, in tree order. + pub(crate) fn values(&self) -> Vec { + let tree = self.fixture.tree(); + tree.keys().into_iter().filter_map(|key| tree.value_of(key)).map(str::to_owned).collect() + } + /// Whether a control in the latest frame holds the value text `value`. pub(crate) fn shows_value(&self, value: &str) -> bool { self.shows_value_with(|shown| shown == value) diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 50354ce723..f23f63b763 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -937,6 +937,22 @@ fn crop_image_shows_a_box_that_apply_crops_to() { assert!(!crate::menus::enabled(&app, "ui.cropImage") && app.run("ui.cropImage", json!({})).is_err()); } +/// With Crop Image in use and room to spare, the Control bar shows the cropping options: the +/// resolution, the box's position and size, and Apply and Cancel. +#[test] +fn the_control_bar_shows_crop_image_s_options_with_apply_and_cancel() { + use crate::tests_removeanchors::{control_frame, has}; + let mut app = app(); + let dir = Folder::new("ui-place-crop-bar"); + app.run("file.place", json!({"path": dir.file("crop.png", &png(100, 50, 72.0)), "link": false})).unwrap(); + app.run("ui.cropImage", json!({})).unwrap(); + let ctx = window(&app); + let bar = control_frame(&mut app, &ctx, vec![]); + for s in ["PPI", "X", "Y", "W", "H", "Apply", "Cancel"] { + assert!(has(&bar, s), "Crop Image: {s} missing from {:?}", bar.iter().map(|(t, _)| t).collect::>()); + } +} + /// Crop Image's Apply and Object › Rasterize say in the status bar when the image couldn't be /// decoded, as raster exports do. #[test] diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index 0ebc06643d..ed161e797f 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -16,7 +16,7 @@ use vectorcraft_plugins::{registry, wat as tpl}; use super::plugins::{approve, window}; use crate::dialogs::plugin::InstallPrompt; -use crate::{VectorcraftApp, dialogs, plugin_runs}; +use crate::{VectorcraftApp, dialogs, export_progress, plugin_runs}; /// An app with a new 200 × 200 pt document. fn app() -> VectorcraftApp { @@ -28,9 +28,11 @@ fn app() -> VectorcraftApp { /// The window of an [`app`] whose background work waits until the test runs it: a run that OK /// started is still running when the frame that started it ends. On threads a fast run could end -/// before a later pass of that frame, which applies it. +/// before a later pass of that frame, which applies it. The app's clock stands still, so the +/// progress window, which would hold the results back, opens only when a test moves the clock. fn held_window() -> (Harness<'static, VectorcraftApp>, Arc) { let mut app = app(); + app.now_override = Some(0.0); let jobs = Arc::new(ManualJobs::new()); app.host = Arc::new(Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs.clone()).build()); (window(app), jobs) @@ -158,6 +160,30 @@ fn a_heavy_filter_runs_off_the_ui_thread_and_applies_as_one_undo_step() { assert!(app.ui.status.is_empty(), "{}", app.ui.status); } +/// The progress window opens once the run is [`export_progress::DELAY`] old on the app's clock, +/// however long the frames take; after Continue in Background closes it the result applies. +#[test] +fn the_progress_window_opens_by_the_app_clock() { + use egui_kittest::kittest::Queryable; + let (mut h, jobs) = held_window(); + let id = "test.ui.heavy.clock"; + install(h.state_mut(), id, 1, "{}"); + let undo = h.state().session.doc().unwrap().history.undo.len(); + assert_eq!(h.state_mut().run("plugin.dialog", json!({"id": id})).unwrap()["background"], true); + // Only the progress window shows its step. + let step = "The plug-in is computing…"; + frame(&mut h); + assert!(h.query_by_label(step).is_none(), "not before the delay"); + h.state_mut().now_override = Some(export_progress::DELAY); + frame(&mut h); + assert!(h.query_by_label(step).is_some(), "the progress window, after the delay"); + assert_eq!(h.state_mut().run("plugin.hideRuns", json!({})).unwrap(), json!({"hidden": 1})); + frame(&mut h); + assert!(h.query_by_label(step).is_none(), "Continue in Background closed it"); + finish_held(h.state_mut(), &jobs); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); +} + /// A document edited while the filter runs doesn't take its result: nothing changes, and the status /// bar says to run it again. #[test] diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 7bb145686a..24ec586447 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -467,6 +467,241 @@ fn plugin_commands_are_menu_items_and_shortcut_entries() { assert!(row(grow).is_none()); } +/// A filter at API level 2 named `name` whose commands are `commands` (a JSON list). +fn placing_plugin(id: &str, name: &str, commands: &str) -> String { + placing_kind(id, name, "filter", commands) +} + +/// A plug-in of `kind` at API level 2 named `name` whose commands are `commands` (a JSON list). +fn placing_kind(id: &str, name: &str, kind: &str, commands: &str) -> String { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"{kind}","commands":{commands}}}"#); + vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()) +} + +/// A command whose manifest's `menu` names another menu is listed there, after the built-in item +/// `after` names or at the end of the menu, with its plug-in's name after its label, and not in its +/// plug-in's submenu; one with no `menu` stays there. Commands of two plug-ins at the same spot are +/// listed in plug-in id order whichever was installed first. Keyboard Shortcuts and the command +/// palette list it under its menu, and removing its plug-in takes it out of every menu. +#[test] +fn a_plugin_command_is_placed_in_the_menu_its_manifest_names() { + let mut app = app(); + let (ant, bee) = ("test.ui.place.ant", "test.ui.place.bee"); + let low = |id: &str| vectorcraft_engine::cmd::plugin::command_id(id, "low"); + // Bee is installed first; Ant's id sorts first. + let bee_commands = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse"}}, + {"id":"tail","label":"Tail","menu":{"path":["Select"],"after":"No Such Item"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(bee, "Bee", bee_commands)})).unwrap(); + let ant_commands = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse…"},"params":{"area":{"type":"number","min":0,"max":100,"default":4}}}, + {"id":"same","label":"Same Area","menu":{"path":["Select","Same"]}}, + {"id":"lost","label":"Lost Anchor","menu":{"path":["Select"],"after":"No Such Item"}}, + {"id":"end","label":"End","menu":{"path":["Select"]}}, + {"id":"edges","label":"Edges","menu":{"path":["View"],"after":"Show Edges"}}, + {"id":"stay","label":"Stay"}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(ant, "Ant", ant_commands)})).unwrap(); + + let entries = menus::menu_entries(&app); + let select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"]).collect(); + let at = |command: &str| select.iter().position(|e| e.command.as_deref() == Some(command)); + let inverse = at("select.inverse").expect("Inverse is listed"); + assert_eq!((at(&low(ant)), at(&low(bee))), (Some(inverse + 1), Some(inverse + 2)), "after Inverse, Ant's before Bee's"); + assert_eq!(select[inverse + 1].label, "Low Area (Ant)…", "the item names its plug-in"); + assert_eq!(select[inverse + 2].label, "Low Area (Bee)"); + // An `after` that names no item means the end of the menu, as no `after` does, and the end keeps + // plug-in id order and then manifest order too. + let command = vectorcraft_engine::cmd::plugin::command_id; + let lost = command(ant, "lost"); + let tail = [at(&lost), at(&command(ant, "end")), at(&command(bee, "tail"))]; + let n = select.len(); + assert_eq!(tail, [Some(n - 3), Some(n - 2), Some(n - 1)], "Ant's two, then Bee's, at the end"); + let same = vectorcraft_engine::cmd::plugin::command_id(ant, "same"); + assert!(entry(&entries, &["Select", "Same"], "Same Area (Ant)").is_some_and(|e| e.command.as_deref() == Some(same.as_str()))); + assert!(menus::menu_strings().contains("Same"), "Select › Same is still a built-in submenu"); + // An item that switches between two labels is matched by either of them. + let view: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["View"]).collect(); + let edges = view.iter().position(|e| e.command.as_deref() == Some("view.edges")).expect("Hide Edges is listed"); + assert_eq!(view.get(edges + 1).and_then(|e| e.command.clone()), Some(command(ant, "edges")), "after the edges toggle"); + + // Each placed command is in one menu only; Stay is still in Ant's submenu. + for command in [low(ant), low(bee), same.clone(), lost.clone()] { + assert_eq!(entries.iter().filter(|e| e.command.as_deref() == Some(command.as_str())).count(), 1, "{command}"); + } + assert!(entry(&entries, &["Object", "Plug-ins", "Ant"], "Stay").is_some()); + let bee_item = entry(&entries, &["Object", "Plug-ins"], "Bee").expect("Bee is a plain item again: all its commands are placed"); + assert_eq!(bee_item.command.as_deref(), Some("plugin.dialog")); + + let listed = crate::shortcut_editor::entry(&low(ant)).expect("in Keyboard Shortcuts"); + assert_eq!((listed.label.as_str(), listed.group.as_str()), ("Low Area (Ant)", "Select")); + assert!(crate::palette::items().iter().any(|(name, id)| *id == low(bee) && name.ends_with("Low Area (Bee)")), "in the command palette"); + + app.run("plugin.remove", json!({"id": ant})).unwrap(); + let entries = menus::menu_entries(&app); + assert!(entries.iter().all(|e| e.command.as_deref().is_none_or(|c| !c.starts_with("plugin.test.ui.place.ant."))), "Ant's commands are gone"); + assert!(entries.iter().any(|e| e.path == ["Select"] && e.command.as_deref() == Some(low(bee).as_str()))); + app.run("plugin.remove", json!({"id": bee})).unwrap(); + assert!(menus::menu_entries(&app).iter().all(|e| e.command.as_deref() != Some(low(bee).as_str()))); + assert!(crate::shortcut_editor::entries().iter().all(|e| e.key != low(bee))); +} + +/// Commands placed after an item that switches between two labels are one spot whichever label +/// their `after` names: they keep manifest order within a plug-in and plug-in id order across +/// plug-ins. +#[test] +fn both_labels_of_a_switching_item_are_one_spot() { + let mut app = app(); + let (ape, bat) = ("test.ui.place.ape", "test.ui.place.bat"); + let command = vectorcraft_engine::cmd::plugin::command_id; + let ape_commands = r#"[{"id":"first","label":"First","menu":{"path":["View"],"after":"Hide Bounding Box"}}, + {"id":"second","label":"Second","menu":{"path":["View"],"after":"Show Bounding Box"}}]"#; + let bat_commands = r#"[{"id":"third","label":"Third","menu":{"path":["View"],"after":"Hide Bounding Box"}}]"#; + // Bat is installed first; Ape's id sorts first. + app.run("plugin.install", json!({"dataBase64": placing_plugin(bat, "Bat", bat_commands)})).unwrap(); + app.run("plugin.install", json!({"dataBase64": placing_plugin(ape, "Ape", ape_commands)})).unwrap(); + + let entries = menus::menu_entries(&app); + let view: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["View"]).collect(); + let toggle = view.iter().position(|e| e.command.as_deref() == Some("view.boundingBox")).expect("Hide Bounding Box is listed"); + let after: Vec> = (1..=3).map(|i| view.get(toggle + i).and_then(|e| e.command.clone())).collect(); + assert_eq!(after, [Some(command(ape, "first")), Some(command(ape, "second")), Some(command(bat, "third"))]); + for id in [ape, bat] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// A live effect whose commands are all placed elsewhere is a single item in Effect › Plug-ins. A +/// filter with the same name placing a command with the same label at the same spot keeps it in its +/// own submenu, so the menu shows that label once. Replaced by a module whose command has no +/// `menu`, the effect's command leaves the menu it was placed in and is listed once, in its +/// submenu. +#[test] +fn placed_commands_of_a_live_effect_and_a_clashing_label() { + let mut app = app(); + let (eff, twin) = ("test.ui.place.eff", "test.ui.place.twin"); + let command = vectorcraft_engine::cmd::plugin::command_id; + let placed = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_kind(eff, "Glow", "effect", placed)})).unwrap(); + app.run("plugin.install", json!({"dataBase64": placing_plugin(twin, "Glow", placed)})).unwrap(); + + let entries = menus::menu_entries(&app); + let (low, twin_low) = (command(eff, "low"), command(twin, "low")); + let in_select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"] && e.label == "Low Area (Glow)").collect(); + assert_eq!(in_select.len(), 1, "the label is listed once"); + assert_eq!(in_select[0].command.as_deref(), Some(low.as_str()), "the plug-in with the lower id takes the spot"); + let own = entry(&entries, &["Effect", "Plug-ins"], "Glow").expect("the effect is a single item"); + assert!(own.command.as_deref().is_some_and(|c| !vectorcraft_engine::cmd::plugin::is_command_id(c)), "{:?}", own.command); + assert!(entries.iter().all(|e| e.path != ["Effect", "Plug-ins", "Glow"]), "no submenu is left"); + assert!(entry(&entries, &["Object", "Plug-ins", "Glow"], "Low Area").is_some_and(|e| e.command.as_deref() == Some(twin_low.as_str()))); + let listed = crate::shortcut_editor::entry(&twin_low).expect("in Keyboard Shortcuts"); + assert_eq!((listed.label.as_str(), listed.group.as_str()), ("Low Area", "Object › Plug-ins › Glow")); + + // An item whose two labels share no first word is matched by either label too. + let global = "test.ui.place.global"; + let after_stop = r#"[{"id":"next","label":"Next","menu":{"path":["Select"],"after":"Stop Global Edit"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(global, "Global", after_stop)})).unwrap(); + let entries = menus::menu_entries(&app); + let select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"]).collect(); + let toggle = select.iter().position(|e| e.command.as_deref() == Some("select.globalEdit")).expect("Start Global Edit is listed"); + assert_eq!(select.get(toggle + 1).and_then(|e| e.command.clone()), Some(command(global, "next"))); + app.run("plugin.remove", json!({"id": global})).unwrap(); + + let unplaced = placing_kind(eff, "Glow", "effect", r#"[{"id":"low","label":"Low Area"}]"#); + app.run("plugin.install", json!({"dataBase64": unplaced, "replace": true})).unwrap(); + let entries = menus::menu_entries(&app); + assert_eq!(entries.iter().filter(|e| e.command.as_deref() == Some(low.as_str())).count(), 1, "listed once"); + assert!(entry(&entries, &["Effect", "Plug-ins", "Glow"], "Low Area").is_some(), "back in its submenu"); + assert!( + entry(&entries, &["Select"], "Low Area (Glow)").is_some_and(|e| e.command.as_deref() == Some(twin_low.as_str())), + "the filter's takes the spot" + ); + for id in [eff, twin] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// Every menu a manifest's `menu` may name is a built-in menu of the menu bar, so a command placed +/// there is never left in its plug-in's submenu while Keyboard Shortcuts lists it under that menu. +#[test] +fn every_menu_a_plugin_may_name_is_in_the_menu_bar() { + fn find<'a>(items: &'a [menus::Node], label: &str) -> Option<&'a [menus::Node]> { + items.iter().find_map(|it| match it { + menus::Node::Submenu { label: l, children, .. } if l == label => Some(children.as_slice()), + _ => None, + }) + } + let tree = menus::menu_tree(); + for place in vectorcraft_plugins::manifest::MENU_PLACES { + let (first, rest) = place.split_first().unwrap(); + let mut menu = tree.iter().find(|(title, _)| title == first).map(|(_, items)| items.as_slice()); + for segment in rest { + menu = menu.and_then(|m| find(m, segment)); + } + assert!(menu.is_some(), "{place:?} is in the menu bar"); + } +} + +/// Every engine command whose menu item switches between two labels is in the engine's +/// `SWITCHING_LABELS`, so a placed plug-in command that reads like its other label stays in its +/// plug-in's submenu without the desktop app too. +#[test] +fn engine_commands_with_two_labels_are_known_to_the_engine() { + use vectorcraft_engine::cmd::plugin::{SWITCHING_LABELS, other_state}; + for spec in vectorcraft_engine::cmd::command_specs() { + let switches = menus::DYNAMIC_LABELS.contains(&spec.label) + && other_state(spec.label).is_some_and(|other| menus::DYNAMIC_LABELS.contains(&other.as_str())); + assert_eq!(SWITCHING_LABELS.contains(&spec.label), switches, "{} ({})", spec.id, spec.label); + } +} + +/// Every item of a menu a plug-in command may be placed in, other than an engine command of that +/// menu, is in the engine's `DESKTOP_MENU_ITEMS` with both of its labels, so a placed plug-in +/// command that reads like it stays in its plug-in's submenu without the desktop app too. +#[test] +fn desktop_items_of_placeable_menus_are_known_to_the_engine() { + use vectorcraft_engine::cmd::plugin::{DESKTOP_MENU_ITEMS, SWITCHING_LABELS, other_state}; + let key = |l: &str| l.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect::(); + let tree = menus::menu_tree(); + let mut missing = Vec::new(); + for place in vectorcraft_plugins::manifest::MENU_PLACES { + let (first, rest) = place.split_first().unwrap(); + let mut items = tree.iter().find(|(title, _)| title == first).map(|(_, items)| items.as_slice()).unwrap(); + for segment in rest { + items = items + .iter() + .find_map(|it| match it { + menus::Node::Submenu { label, children, .. } if label.as_str() == *segment => Some(children.as_slice()), + _ => None, + }) + .unwrap(); + } + let engine_reads = |label: &str| { + vectorcraft_engine::cmd::command_specs().iter().any(|s| { + s.menu == *place + && (key(s.label) == key(label) + || SWITCHING_LABELS.contains(&s.label) && other_state(s.label).is_some_and(|o| key(&o) == key(label))) + }) + }; + for it in items { + let label = match it { + menus::Node::Item(i) if !menus::lists_plugin(&i.command.id, &i.command.params) => i.label.as_str(), + menus::Node::Submenu { label, children, .. } if !menus::holds_plugin_commands(children) => label.as_str(), + _ => continue, + }; + let mut labels = vec![label.to_string()]; + if menus::DYNAMIC_LABELS.contains(&label) { + labels.extend(other_state(label)); + } + for l in labels { + let known = DESKTOP_MENU_ITEMS.iter().any(|(path, d)| path == place && key(d) == key(&l)); + if !engine_reads(&l) && !known && !missing.contains(&(place, l.clone())) { + missing.push((place, l)); + } + } + } + } + let rows: Vec = missing.iter().map(|(place, l)| format!(" (&{place:?}, {l:?}),")).collect(); + assert!(missing.is_empty(), "missing from DESKTOP_MENU_ITEMS:\n{}", rows.join("\n")); +} + /// The `grant` and `allowHeavy` that `ui.installPlugin` is given approve nothing: it asks all the /// same, and what OK would approve comes from the manifest. A module with nothing to approve /// installs without either. diff --git a/crates/ui-egui/src/tests/removeanchors.rs b/crates/ui-egui/src/tests/removeanchors.rs index 9e4a216b31..90c977f58f 100644 --- a/crates/ui-egui/src/tests/removeanchors.rs +++ b/crates/ui-egui/src/tests/removeanchors.rs @@ -301,3 +301,61 @@ fn open_anchor_delete_and_backspace_cut_the_clicked_anchor_then_clear() { assert!(pieces.iter().all(|piece| app.session.doc().unwrap().doc.node(*piece).is_none()), "the next {key:?} clears every piece"); } } + +/// With General › Delete Removes Anchor Points and Keeps Paths Joined on, both deletion keys +/// remove the clicked anchor of a closed path and leave it closed, in one undo step. +#[test] +fn with_the_preference_on_delete_and_backspace_keep_the_path_joined() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + app.run("prefs.set", json!({"key": "deleteKeepsPathsJoined", "value": true})).unwrap(); + let id = rect(&mut app); + app.select_tool("directSelection"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + anchor_delete_frame(&mut app, &ctx, vec![]); + } + let at = app.canvas_view().unwrap().to_screen(Point::new(150.0, 50.0)); + let click = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + anchor_delete_frame(&mut app, &ctx, vec![Event::PointerMoved(at), click(true)]); + anchor_delete_frame(&mut app, &ctx, vec![click(false)]); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.anchors.get(&id).map(|a| a.len()), Some(1), "the real canvas click selected one anchor"); + let (before, undo) = (st.doc.clone(), st.history.undo.len()); + let press = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + anchor_delete_frame(&mut app, &ctx, vec![press(true)]); + anchor_delete_frame(&mut app, &ctx, vec![press(false)]); + let st = app.session.doc().unwrap(); + let path = st.doc.node(id).and_then(|n| n.path_data()).unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed, "{key:?} keeps the path closed"); + assert_eq!(anchor_count(&app, id), 3); + assert_eq!(st.history.undo.len(), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + } +} + +/// The Smart Pen does not take Delete, so with it chosen Delete follows the preference too. +#[test] +fn with_the_smart_pen_chosen_delete_follows_the_preference() { + for on in [false, true] { + let mut app = app(); + app.run("prefs.set", json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap(); + let id = rect(&mut app); + app.select_tool("smartPen"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + anchor_delete_frame(&mut app, &ctx, vec![]); + } + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let press = |pressed| Event::Key { key: egui::Key::Delete, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + anchor_delete_frame(&mut app, &ctx, vec![press(true)]); + anchor_delete_frame(&mut app, &ctx, vec![press(false)]); + assert_eq!(app.session.tool_id(), "smartPen"); + let st = app.session.doc().unwrap(); + let closed = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.len() == 1 && p.subpaths[0].closed); + assert_eq!(closed, on, "with the preference {on}, Delete keeps the path closed: {on}"); + assert_eq!(anchor_count(&app, id), 3, "Delete removed one anchor"); + } +} diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 2b03214f3a..33674ec957 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -88,6 +88,7 @@ fn label(node: &Node) -> Option { /// for a separator. fn shape(nodes: &[Node]) -> String { let one = |node: &Node| match node { + Node::Item(item) if item.command.id == menus::PLACEHOLDER => format!("({})", item.label), Node::Item(item) => item.label.clone(), Node::Submenu { label, children, .. } => format!("{label}/[{}]", shape(children)), Node::Heading(text) => format!("({text})"), @@ -297,6 +298,10 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { std::fs::write(dir.join("Scripts"), "").unwrap(); read(&app); assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + // The menu layout keeps the note. + let mut laid = scripts(); + craft::menu::tidy(&mut laid); + assert_eq!(shape(&laid), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 35d569cb1c..1e0ce31c9a 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -849,7 +849,7 @@ fn tools_offer_their_bar_or_none() { let labels = |app: &mut VectorcraftApp| offer(app).map(|o| o.actions.iter().map(|a| a.0).collect::>()).unwrap_or_default(); app.select_tool("artboard"); crate::panels::artboards::select(&mut app, 1); - assert_eq!(labels(&mut app), ["Resize", "Duplicate", "Rearrange All", "Export"]); + assert_eq!(labels(&mut app), ["Resize", "Duplicate", "Rearrange", "Export"]); let b = app.session.active().unwrap().doc.artboards[1].rect; let o = offer(&mut app).unwrap(); assert!( @@ -860,9 +860,266 @@ fn tools_offer_their_bar_or_none() { app.select_tool("selection"); app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); assert_eq!(labels(&mut app), ["Edit Path", "Offset Path", "Simplify", "Duplicate"]); + // One artboard, selected: Rearrange places it. app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); app.select_tool("artboard"); - assert_eq!(labels(&mut app), ["Resize", "Duplicate", "Export"]); + assert_eq!(labels(&mut app), ["Resize", "Duplicate", "Rearrange", "Export"]); +} + +/// Three 200 by 100 pt artboards with the Artboard tool, `selected` selected. +fn rearrange_app(selected: serde_json::Value) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &selected); + app +} + +fn artboard_rects(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect() +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// Opens Rearrange for the selected artboards and presses OK with one row 10 pt apart, inside `rig`. +fn confirm_rearrange(rig: &mut Rig) { + use crate::dialogs::rearrange_artboards::{PLACE_HINT, RearrangeArtboardsDialog}; + rig.run_fired(); + let mut app = rig.app(); + crate::panels::artboards::open_rearrange_selected(&mut app); + let id = app.dialogs().and_then(|d| d.with(|h| h.open_dialogs().last().map(|o| o.id))).expect("Rearrange opens"); + assert!(app.dialogs().unwrap().with(|h| h.is_open::())); + crate::tests::picks::answer_dialog(&mut app, id, &[("layout", json!("row")), ("spacing", json!(10))], true); + assert!(app.ui.rearrange_placement.is_some() && app.ui.status == PLACE_HINT, "{}", app.ui.status); +} + +/// Rearrange for the selected artboards, confirmed, waits for a click: the grid's outline follows +/// the pointer, and a press on the canvas puts the selected artboards' grid there with its top-left +/// at the press, as one undo step, leaving the other artboards and giving the tool no press. Esc +/// cancels a waiting one, and so does another tool, with nothing moved. +#[test] +fn rearrange_places_the_selected_artboards_where_the_canvas_is_clicked() { + use crate::dialogs::rearrange_artboards::{PLACE_HINT, placement_overlays}; + let mut app = rearrange_app(json!([0, 2])); + let (before, steps) = (artboard_rects(&app), undo_steps(&app)); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let view = rig.app().canvas_view().expect("the canvas is laid out"); + let at = view.rect.center() + vec2(-150.0, -120.0); + let doc = view.to_doc(at); + + // Esc: nothing moves. + confirm_rearrange(rig); + rig.fx.frame(vec![egui::Event::PointerMoved(at)]); + rig.fx.key(Key::Escape, Modifiers::NONE); + rig.run_fired(); + assert!(rig.app().ui.rearrange_placement.is_none(), "Esc cancels"); + assert_ne!(rig.app().ui.status, PLACE_HINT); + // Another tool: nothing moves. + confirm_rearrange(rig); + rig.app().select_tool("selection"); + rig.fx.frame(vec![egui::Event::PointerMoved(at)]); + assert!(rig.app().ui.rearrange_placement.is_none(), "another tool cancels"); + { + let app = rig.app(); + assert_eq!((artboard_rects(&app), undo_steps(&app)), (before.clone(), steps)); + } + + rig.app().select_tool("artboard"); + rig.app().session.set_tool_option("selected", &json!([0, 2])); + confirm_rearrange(rig); + rig.fx.frame(vec![egui::Event::PointerMoved(at)]); + let outline = placement_overlays(&rig.app()); + assert_eq!(outline.len(), 2, "an outline for each selected artboard"); + rig.fx.click_at(at); + rig.run_fired(); + let app = rig.app(); + let after = artboard_rects(&app); + assert_eq!(after.len(), 3, "the Artboard tool made no artboard"); + assert_eq!(after[1], before[1], "artboard 2 is not selected"); + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + assert!(near(after[0].x0, doc.x) && near(after[0].y0, doc.y), "{:?} at {doc:?}", after[0]); + assert!(near(after[2].x0, doc.x + 210.0) && near(after[2].y0, doc.y), "{:?}", after[2]); + assert_eq!(undo_steps(&app), steps + 1); + assert!(app.ui.rearrange_placement.is_none() && app.ui.status != PLACE_HINT); + }); +} + +/// A waiting Rearrange takes Enter from the keyboard: with the pointer off the canvas, the grid +/// starts at the first selected artboard's top-left, in one undo step. A press with Space held +/// pans and places nothing. +#[test] +fn rearrange_places_the_selected_artboards_with_enter_and_lets_space_pan() { + let mut app = rearrange_app(json!([2, 0])); + let (before, steps) = (artboard_rects(&app), undo_steps(&app)); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + confirm_rearrange(rig); + // Space held: the press pans. + let at = rig.app().canvas_view().expect("the canvas is laid out").rect.center(); + let origin = |rig: &Rig| rig.app().canvas_view().unwrap().to_screen(Point::ZERO); + let start = origin(rig); + let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let end = at + vec2(30.0, 20.0); + for ev in [ + key(Key::Space, true), + egui::Event::PointerMoved(at), + button(at, true), + egui::Event::PointerMoved(at.lerp(end, 0.5)), + egui::Event::PointerMoved(end), + button(end, false), + ] { + rig.fx.frame(vec![ev]); + } + rig.fx.frame(vec![key(Key::Space, false)]); + rig.run_fired(); + assert!(origin(rig) != start, "the Space-drag pans the view"); + { + let app = rig.app(); + assert!(app.ui.rearrange_placement.is_some(), "a Space-drag places nothing"); + assert_eq!((artboard_rects(&app), undo_steps(&app)), (before.clone(), steps)); + } + rig.fx.frame(vec![egui::Event::PointerGone]); + rig.fx.key(Key::Enter, Modifiers::NONE); + rig.run_fired(); + }); + let after = artboard_rects(&app); + assert!(app.ui.rearrange_placement.is_none()); + assert_eq!((after[0], after[1]), (before[0], before[1])); + assert_eq!((after[2].x0, after[2].y0), (before[0].x0 + 210.0, before[0].y0)); + assert_eq!(undo_steps(&app), steps + 1); +} + +/// Once a pen has been seen, a finger press on the canvas navigates and does not place a waiting +/// Rearrange: the finger's drag pans the view while the artboards and the history stay as they +/// were. A mouse click then places it. +#[test] +fn rearrange_is_not_placed_by_a_finger_once_a_pen_was_seen() { + use crate::touch::{Source, set_pen_seen, set_source}; + let mut app = rearrange_app(json!([1])); + let (before, steps) = (artboard_rects(&app), undo_steps(&app)); + let (touched, panned) = on_canvas(&mut app, |rig| { + rig.fx.settle(); + confirm_rearrange(rig); + let at = rig.app().canvas_view().expect("the canvas is laid out").rect.center() + vec2(40.0, 30.0); + let origin = |rig: &Rig| rig.app().canvas_view().unwrap().to_screen(Point::ZERO); + let start = origin(rig); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let end = at + vec2(60.0, 40.0); + // The platform says a finger drives the pointer once a pen has been seen. + set_source(Source::Pen); + set_source(Source::Finger); + for ev in [ + egui::Event::PointerMoved(at), + button(at, true), + egui::Event::PointerMoved(at.lerp(end, 0.5)), + egui::Event::PointerMoved(end), + button(end, false), + ] { + rig.fx.frame(vec![ev]); + } + rig.run_fired(); + let touched = { + let app = rig.app(); + (app.ui.rearrange_placement.is_some(), artboard_rects(&app), undo_steps(&app)) + }; + let panned = origin(rig) != start; + // The mouse, with the pen still seen. + set_source(Source::Mouse); + rig.fx.click_at(at); + rig.run_fired(); + set_pen_seen(false); + (touched, panned) + }); + assert_eq!(touched, (true, before.clone(), steps), "the finger navigates"); + assert!(panned, "the finger pans the view"); + assert!(app.ui.rearrange_placement.is_none(), "the mouse places it"); + assert_ne!(artboard_rects(&app), before); + assert_eq!(undo_steps(&app), steps + 1); +} + +/// A waiting Rearrange is dropped when its artboards change places in the list before the click, +/// so the click moves no artboard the tool did not select. +#[test] +fn rearrange_waiting_for_a_click_is_dropped_when_its_artboards_are_reordered() { + use crate::dialogs::rearrange_artboards::PLACE_HINT; + let mut app = rearrange_app(json!([0])); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + confirm_rearrange(rig); + rig.app().run("artboard.reorder", json!({"index": 2, "to": 0})).unwrap(); + let before = artboard_rects(&rig.app()); + let at = rig.app().canvas_view().unwrap().rect.center(); + rig.fx.click_at(at); + rig.run_fired(); + let app = rig.app(); + assert!(app.ui.rearrange_placement.is_none() && app.ui.status != PLACE_HINT); + assert_eq!(artboard_rects(&app), before); + }); +} + +/// A Rearrange placement that moves nothing says the artboard is locked only when every selected +/// artboard is locked; a locked artboard beside one already in its cell leaves no such message. +#[test] +fn rearrange_says_locked_only_when_every_selected_artboard_is_locked() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let layout = json!({"layout": "row", "spacing": 10}); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3, "artboardLayout": layout})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap(); + app.select_tool("artboard"); + for (selected, status) in [(json!([0, 1]), ""), (json!([0]), "the artboard is locked")] { + app.session.set_tool_option("selected", &selected); + // The status the placement leaves as the canvas takes Enter. + let placed = on_canvas(&mut app, |rig| { + rig.fx.settle(); + confirm_rearrange(rig); + rig.fx.frame(vec![egui::Event::PointerGone]); + rig.fx.key(Key::Enter, Modifiers::NONE); + let placed = rig.app().ui.status.clone(); + rig.run_fired(); + placed + }); + assert!(app.ui.rearrange_placement.is_none(), "{selected}"); + assert_eq!(placed, status, "{selected}"); + } +} + +/// Where [`rearrange_is_not_placed_by_a_press_on_a_panel_over_the_canvas`] floats its panel. +const PANEL_OVER_CANVAS: Rect = Rect::from_min_max(Pos2::new(300.0, 250.0), Pos2::new(420.0, 370.0)); + +/// A press on a panel floating over the canvas does not place a waiting Rearrange; a press on the +/// open canvas does. +#[test] +fn rearrange_is_not_placed_by_a_press_on_a_panel_over_the_canvas() { + let mut app = rearrange_app(json!([0])); + let (before, steps) = (artboard_rects(&app), undo_steps(&app)); + let show = |app: &mut VectorcraftApp, ui: &mut Ui| { + canvas::show(app, ui); + egui::Area::new(egui::Id::unique("panel over the canvas")).fixed_pos(PANEL_OVER_CANVAS.min).show(ui.ctx(), |ui| { + ui.allocate_exact_size(PANEL_OVER_CANVAS.size(), egui::Sense::click_and_drag()); + }); + }; + let on_panel = driven(&mut app, CANVAS_ROOM, show, |rig| { + rig.fx.settle(); + confirm_rearrange(rig); + assert!(rig.app().canvas_view().expect("the canvas is laid out").rect.contains_rect(PANEL_OVER_CANVAS)); + rig.fx.click_at(PANEL_OVER_CANVAS.center()); + rig.run_fired(); + let on_panel = { + let app = rig.app(); + (app.ui.rearrange_placement.is_some(), artboard_rects(&app), undo_steps(&app)) + }; + rig.fx.click_at(PANEL_OVER_CANVAS.left_top() - vec2(40.0, 40.0)); + rig.run_fired(); + on_panel + }); + assert_eq!(on_panel, (true, before.clone(), steps), "the press is the panel's"); + assert!(app.ui.rearrange_placement.is_none(), "placed on the open canvas"); + assert_ne!(artboard_rects(&app), before); + assert_eq!(undo_steps(&app), steps + 1); } #[test] diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 5de44dbc68..17a92f9785 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -282,10 +282,12 @@ fn a_trace_started_before_a_revert_does_not_apply() { #[test] fn the_progress_window_shows_a_trace() { let mut app = app(); + // The app's clock stands still: the trace is only old enough for its window when made so. + app.now_override = Some(0.0); let ctx = crate::testing::ui_context(); crate::menus::invoke(&mut app, "imageTrace.make", json!({"preset": "Default"})); assert!(!progress(&mut app, &ctx, 0.0).contains("Tracing the image"), "not before the delay"); - // The delay counts on the monotonic clock: the trace started that long ago. + // The delay counts on the app's clock: the trace started that long ago. app.trace_runs.running[0].started -= DELAY; progress(&mut app, &ctx, DELAY + 0.05); // a new window measures itself unseen first let shown = progress(&mut app, &ctx, DELAY + 0.1); diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index 4f7b4f0dae..341c0c4113 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -125,7 +125,7 @@ pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool let _ = tx.send((run, traced)); }) .map_err(|e| e.to_string())?; - let started = crate::export_progress::now(); + let started = crate::export_progress::now(app); app.trace_runs.running.push(Running { started, doc, target, token, superseded: false, steps, from_panel, hidden: false, done }); // This frame may have asked for its next one before the trace started (`tick`): ask now. if let Some(ctx) = &app.ui_ctx { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..48273a94a6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection), and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object (or a group holding a selected member) with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | @@ -273,10 +273,11 @@ Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a sa pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, sliders?, gamut?, harmony?, -harmonyRule?, vision?}` shows the wheel or the box (a color field with a channel strip at its right), picks the box's +harmonyRule?, opacity?, vision?}` shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, shows OKLCH Sliders, HSL Sliders or neither, grays out the colors the CMYK space cannot print, shows the -other colors of a harmony rule as markers on the wheel's ring, and shows or hides the color vision row; it returns the -settings, and `ui.inspect` reports them as `ui.color_wheel`. +other colors of a harmony rule as markers on the wheel's ring, checks or unchecks Show Opacity (an opacity row under +the wheel or the box), and shows or hides the color vision row; it returns the settings, and `ui.inspect` reports them +as `ui.color_wheel`. The key `sliders` takes (`"oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the active document's RGB space, its assigned profile or else the working RGB space, is not sRGB), and the settings carry it too. diff --git a/docs/development.md b/docs/development.md index af91a0a8a3..404dc10f33 100644 --- a/docs/development.md +++ b/docs/development.md @@ -312,7 +312,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE ``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. A literal brace in a row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for - `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish and Indonesian + `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish, Indonesian and Bulgarian translate status and error messages (`COMPLETE_MESSAGES` in `i18n::tests`); the untranslated report lists the message literals the scan finds, and the phrases a parameter schema's error builds at run time (`SCHEMA_PHRASES`), that one of them has no row for. The scan covers the crates in `MESSAGE_CRATES`, the diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 95ed33bf76..555cc17f7f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -17,7 +17,7 @@ translation never fails a test or a build: the interface shows the English text `cargo xtask ci` prints the untranslated report (`cargo xtask i18n-report` alone), which lists per language the strings missing from each catalog with the `complete_menus` flag and the messages missing from each language in the `COMPLETE_MESSAGES` list. Every non-English language marked "full" has the flag, and all of them except -Bosnian and Bulgarian are in the list. No language has help content: there is no translated (or +Bosnian are in the list. No language has help content: there is no translated (or English) in-app help, and the docs are English. **Native review:** every catalog was written clean-room from the English meaning, most of it by agents @@ -66,7 +66,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Czech | `cs` | 9,761 rows, 3,742 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 222 missing Czech messages, and 15 messages that no checked language has a row for | catalog complete; render-site gaps reduced; native review pending | | Bosnian | `bs` | 7,227 rows, 1,205 of them `@msg` and 47 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 113 missing menu strings, 66 `tl!` literals and 30 undo labels for it; not in `COMPLETE_MESSAGES`, so the report does not check its messages; one/few/other plurals | full; AI-assisted, native review pending | | Swedish | `sv` | 9,498 rows, 3,311 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 647 missing messages for it, and 31 menu strings, 14 `tl!` literals and 6 undo labels; one/other plurals | full; native review welcome | -| Bulgarian | `bg` | 7,133 rows, 1,111 of them `@msg` and 47 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 76 menu strings, 48 `tl!` literals, 16 undo labels and 45 swatch names for it; its messages are partial | full; AI-drafted, native review pending | +| Bulgarian | `bg` | 8,940 rows, 2,143 of them `@msg` and 56 `@msgplural` (counted 2026-11-25 on `main` at `9d050d2b01`): in `COMPLETE_MESSAGES`, and the untranslated report lists 71 menu strings, 41 `tl!` literals, 13 undo labels, 45 swatch names and 1,933 messages for it; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 8,003 rows, 1,972 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 1,974 missing messages for it | full; native review welcome | | Georgian | `ka` | 9,758 rows, 3,740 of them `@msg` and 49 `@msgplural` (counted 2026-11-15): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1 missing Georgian message; reviewed by a native speaker | full | | Turkish | `tr` | 9,784 rows, 3,746 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`); 235 messages, 79 menu strings, 39 `tl!` literals, 16 undo labels and the default swatch names still fall back to English | full | diff --git a/docs/mcp.md b/docs/mcp.md index 51028efbb9..e963a4bd42 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -692,9 +692,14 @@ whole cell or none of it, so a grayed cell can hold printable colors and a clear print. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or -`highContrast2`). `{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel +`highContrast2`). `"opacity": true` checks Show Opacity, as the panel menu does: a row under the wheel or the box +with a slider and a percent field sets the opacity of the fill row (`paint.setFill {opacity}`), the stroke row +(`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point +when none is selected), and `false` hides the row. The row is gray with nothing selected, for an object selected in +a symbol instance, and when the fill or stroke row it would set is on type characters or missing. +`{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel or the box. Keys left out keep their values. Params that are not an object, another key or a value off -the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}`, +the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors}`, and the settings are kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or @@ -904,7 +909,17 @@ Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, a `item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. -`inspect_document` reports it as `paint.appearanceItem`. Live effects take the same `item` to apply to one fill or +`inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` +(0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with +or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint +undone. A `swatch` that is not a name does not make the request an opacity alone: it is an error without a paint of +its own. A color for a grayscale or 1-bit image's drawing color creates no fill row, so an opacity given with it goes +to a fill row the image has. With New Art Has Basic Appearance off, the next shape copies the first selected object's +appearance after any command, its opacity included. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has +that row (a selected path of a compound path answers with its compound path's row, which the commands edit, and a +selected Live Paint group answers with its faces' fills and its edges' strokes). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket paints (it is the active tool, or a Cmd+click or an Eyedropper pick works for it), +while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that +row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; `apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`. @@ -3232,7 +3247,9 @@ is given as its file name alone. `script.grants.revoke {script?, path?, all?}` r a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but -cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script +cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is +not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well +formed. A script cannot run either command. ```json @@ -3470,6 +3487,14 @@ Without `ids`, direct-selected anchors or selected ruler guides retain their usu With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected. +Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as +`path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected +(the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected +whole, as `path.removeAnchors` leaves it, so the next Delete removes the whole path. Paths with a selected segment are +cut there, and their selected anchors stay in the path, as with `keepJoined: false`; and objects selected whole are deleted, in the +same undo step. `keepJoined` defaults to the `deleteKeepsPathsJoined` preference, and the value used joins the journal +entry; a saved step without it opens the paths, as it did when it was recorded. With `ids`, `keepJoined` has no +effect. A `keepJoined` value that is not a boolean is an error, with or without `ids`. `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's @@ -5267,10 +5292,18 @@ printed plates an image whose pixels do not take its color (a preview of its fil pixels. Older files that listed Overprint Black objects in the document get the flags on load. PDF export writes them with `advanced.overprint: "preserve"` (the default): each overprinting fill and stroke sets a graphics state with `/OP true /op true /OPM 1` (`/OPM 0` in PDF/A). With `discardWhiteOverprint` (`document.setup`, on by -default) white ones knock out instead, but not a tint above 0% of a spot swatch, which prints as that ink; -`"discard"` writes none. EPS export (`overprints: "preserve"`, the default) turns -overprinting on for a colorized image's color as it does for fills and strokes, except a white color with -`discardWhiteOverprint` on, which knocks out unless it is such a spot tint. PDF export writes an overprinting +default) paper white ones knock out instead; `"discard"` writes none. Paper white is solid white that is not a spot +white. Spot white objects keep overprinting +([white overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html), +[reference, White Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=650)). +These are VectorCraft's own rules: a spot white is a white linked to a solid spot swatch at a tint above 0% (an opaque +white ink, for example), so a 0% tint of a spot swatch is paper white, and so is a spot white that printed separations +convert to process inks. A spot white's fills, strokes, characters and colorized image colors keep overprinting in PDF +export, Overprint Preview, Separations Preview and printed separations, its fills, strokes and colorized image colors +keep overprinting in composite print with Overprints set to Simulate, and Print Ink Fixes' `removeWhiteOverprint` +leaves it overprinting. EPS export (`overprints: "preserve"`, the default) turns overprinting on for a colorized image's +color as it does for fills and strokes, except a paper white color with `discardWhiteOverprint` on, which knocks out; +EPS export applies `discardWhiteOverprint` to nothing else. PDF export writes an overprinting colorized image in a gray or CMYK color in only the process inks the color puts down, and EPS export does too (one DeviceN image at Level 3, one Separation image per ink at Level 2). The previews and printed separations show a colorized image knocking out when it has a visible effect of its own other than a warp or a geometry effect (a drop @@ -6027,23 +6060,40 @@ same extension and bytes as one there, loads as that User Defined library (categ is refused before it is read. From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and -art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot +art, into the document as a pattern swatch under the library swatch's name. The swatch goes into its color group when +`names` is left out or when the first entry of `names` that covers the swatch is its group; when that first entry is +the swatch's own name, the swatch comes in ungrouped. A library swatch named after its +pattern instead takes the name the pattern comes in under, when the pattern comes in under another name that no +library swatch has and the swatch does not keep a free numbered name as described below. For such a swatch, when the +document already has a swatch under any name that paints that pattern placed the same way, that swatch is used and +nothing is added. Otherwise, when a +swatch or color group of the document already uses that name, the swatch comes in under a numbered copy of it +("Tiles 2 2"). A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes -in under a numbered name ("Ink 2") and the pattern links to that. That numbered name skips the names the library -gives its other swatches. A library color whose name the document gives -another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color -again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name -is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the -document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added -earlier or came with a pattern's art. A library global color is not the document's process color of the same name and -paint: it comes in numbered. A global or spot color that a library tint or gradient links to and the document lacks -comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. The -document's tint or gradient of the library one's name is that swatch when it links to the copy of the color that the -art of a pattern picked with it takes; a numbered copy that the library also names stands for that library swatch -otherwise. When the document's tint or gradient links to a color the document no longer has (deleted without -unlinking), that color comes back under its own name. A pattern is found again when it was pasted with Add or Merge for all of its colors; one pasted -with Merge for some colors and Add for others is added again as a copy. `added` lists the colors the pattern's art, a -tint or a gradient brings too. A document with +in under a numbered name ("Ink 2") and the pattern links to that. That numbered name, and the numbered names of a +pattern swatch and of a pattern the art is painted with, skip the names the library gives its other swatches. A swatch +of a numbered library name, such as a color or tint "Ink 2", that the pattern's art brings keeps that name when the +document does not use it. Of two library swatches with one numbered name, the first one in the library keeps the name +when the other is a swatch the pattern's art brings or a pattern swatch. A pattern the art is painted with keeps a +numbered name; when the library's swatch of that name places the pattern otherwise, the swatch that comes with the +pattern gets another name. When the document gives that name to another pattern, the pattern comes in under a new +number, and its swatch keeps the library swatch's name when no swatch or color group uses it. A library color whose +name the document gives another color is the document's numbered copy of the same color when it has one, so adding the +pattern and its color again adds nothing; a numbered copy whose name the library gives another swatch, and which is +that swatch, is not a copy of another color, whether or not the pattern's art uses that swatch. A pattern the document +already holds with its art linked to the document's own color of that name, or to a numbered copy of the color as +pasting leaves it, is used as it is, unless using it would give another swatch a name the library uses. A library +tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered +copy, links to that copy, whether the color is picked before or after it, was added earlier or came with a pattern's +art. A library global or spot color is not the document's color of the same name and paint when that color is of +another kind (process, global or spot): it comes in numbered. A global or spot color that a library tint or gradient +links to and the document lacks comes in with the tint or gradient, under a numbered name when the document gives its +name another swatch. The document's tint or gradient of the library one's name is that swatch when it links to the +copy of the color that the art of a pattern picked with it takes; a numbered copy that the library also names stands +for that library swatch otherwise. When the document's tint or gradient links to a color the document no longer has +(deleted without unlinking), that color comes back under its own name. A pattern is found again when it was pasted +with Add or Merge for all of its colors; one pasted with Merge for some colors and Add for others is added again as a +copy. `added` lists the colors the pattern's art, a tint or a gradient brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. @@ -7127,6 +7177,8 @@ The anchor after each removed one is then selected (the one before at an open pa `path.deleteAnchors {keepEmpty?}` (the Delete key) deletes the selected anchors with their segments, opening closed paths there. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given; `edit.clear` passes its `keepEmpty` on when it deletes direct-selected anchors. +With the `deleteKeepsPathsJoined` preference on, the Delete key (`edit.clear`) removes them as `path.removeAnchors` +does instead. ```json {"name":"run_command","arguments":{"command":"select.anchors","params":{"id":12,"anchors":[[0,1],[0,3]]}}} @@ -7333,7 +7385,15 @@ there too and a `brush.freehand` call does not change the path's brush or the se A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing -the path it had begun while that stays selected. Its reply's `tool` is the tool given back. +the path it had begun while that stays selected. With Direct Selection or Group Selection, `mods.cmd` drags with the +Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection). With the Selection tool, it drags +with Direct Selection or Group Selection, whichever was chosen last (Direct Selection until one is), except where the +press lands on a selected object, or on a group holding a selected member, with another object under the pointer, away +from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, while +`ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the object behind. A double-click +or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went to, and one that follows a +Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool +given back. `tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the @@ -7650,9 +7710,36 @@ the path. The command returns an error and changes nothing when both or neither an unknown `action`, a `turn` outside 1 to 359, a `flip` or `closed` that is not true or false, a `keep` outside 1 to the subpath's points, and for a closed subpath, a locked or hidden path or an `id` that is not a path. +Dragging the handle at the start or end of the path makes the line or arc there longer or shorter, as +[Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) +describes. The tool shows a handle 20 screen points beyond each end of the path being drawn, along the direction the +path leaves that end, where the end is a straight line or a circular arc; with no path being drawn, it shows them on +each open subpath of the one editable path selected. A line keeps its other point and its direction. An arc keeps its +other point, its circle and the way it turns, and its sweep follows the pointer around the circle, up to 359°. The +dragged end stays on its line or circle and does not snap to Smart Guides, and a drag stops where the path would +reach past the canvas. Each drag is one undo step, Escape during +the drag takes it back, and the path being drawn goes on from the new end. The pieces of the path being drawn that the +drag does not change stay pieces: C and `[` `]` still change the last one. The last piece, dragged by its end, stays +that piece, and as an arc it keeps an arc size of at least 1°. C and `[` `]` do nothing until the drag ends, and the +end goes where the pointer is let go. A click on a handle that does not drag is an ordinary +click: it adds a point, closes the path or starts a new one. The handle's place, the 359° limit, the 1° minimum, +Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules. + +`path.quickPenLength {id, subpath?, end?, length}` does the same for scripts and agents: it makes the line or arc at +`end` (`"end"`, the default, or `"start"`) of the open subpath `subpath` (0 when left out) `length` points long, +selects the path, as one undo step, and answers `{id, kind, length}`, where `kind` is `"line"` or `"arc"`. The arc at an +end is the run of segments before it that lie on one circle and turn the same way, as the Quick Pen draws them. A +`length` the line or arc already has changes nothing and records no undo step. The command returns an error and +changes nothing when `id` or `length` is missing, when `length` is not a number, is under 0.001, or is over 1000000 +for a line or over 359° of its circle for an arc, for an `end` other than `"start"` or `"end"`, an end that is neither +a straight line nor a circular arc (`the end is not a straight line or a circular arc`), a result that would reach past +the canvas, a closed subpath, a locked or hidden path, and an `id` that is not a path. For an arc, the error gives the +359° limit in points, rounded down to the thousandth. + ```json {"name":"run_command","arguments":{"command":"path.quickPen","params":{"start":[100,100],"pieces":[{"x":200,"y":100},{"x":300,"y":200,"action":"continuousArc"},{"x":300,"y":300,"action":"sharpArc","turn":90,"flip":true}]}}} {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"quickPen","key":"action","value":"sharpArc"}}} +{"name":"run_command","arguments":{"command":"path.quickPenLength","params":{"id":12,"end":"start","length":40}}} ``` ## Registration and trim marks @@ -8547,6 +8634,12 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture as it did when it was recorded. Align and Distribute, and the anchors of type paths and area type frames (`text.reshapePath`, `text.reshapeArea`), move as before. Off, the handles of a moved anchor move with it and the other handles stay where they are. +- `deleteKeepsPathsJoined` (General › Delete Removes Anchor Points and Keeps Paths Joined, off by default): the + default of the `keepJoined` param of `edit.clear` (Delete, Backspace, Edit › Clear, and the Layers panel's Delete + button while no row is highlighted). On, Delete removes the direct-selected anchors of a path as `path.removeAnchors` does, refitting the curve + around each one, so a closed path stays closed and an open path stays in one piece; a path left with fewer than two + anchors is deleted. The next anchor along (the one before at an open path's end) is then selected, so the next + Delete goes on along the path. Off, Delete deletes the anchors with their segments and opens the path there. - `hideCornerWidgetAbove` (177° by default): corners wider than this show no Live Corners widget (a rectangle's right angles hide below 90°). - `transformPatternTiles` (off by default): the default of the transforms' `patterns` param (`object.transform`, @@ -9303,7 +9396,7 @@ unless `link: false`; a Photoshop document as its merged image), an SVG as one g and swatches it uses. A VectorCraft document read from `path` is a placed document: one locked object showing its artboard `page` (or, with `crop: "bounding"`, its art's bounds), linked to the file and read again when it changes (see Linked images), and vectors in every output; with `link: false` (or from `dataBase64`) it is an editable copy -of its art, as one clipped group. A PDF, `.ai` or `.ait` page read from `path` (with neither `password` nor +of its art, as one clipped group. A PDF, `.ai` or `.ait` page read from `path` (with neither a non-empty `password` nor `textAs: "outlines"`) is a placed document the same way, showing page `page` clipped to its `crop` box (or its art's bounds); with `link: false` it is placed as one clipped group. An EPS file, a PostScript file or a PostScript `.ai` read from `path` is a placed document too, showing the art `link: false` places (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); @@ -9376,7 +9469,7 @@ slices (Place PSD). `showImportOptions: false` places such a file without asking its dialog: the text options, the DXF fit, lineweight, centering and layer choices with the drawing at 1:1 in its own unit, and the PSD conversion, hidden-layer and Import Slices choices. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no -`password` still asks for the password. An encrypted PDF given a `page` and no `password` asks for the password with +`password` (or an empty one) still asks for the password. An encrypted PDF given a `page` and no `password` asks for the password with Show Import Options on too, and places that page. A `showImportOptions` that is not true or false is refused, and nothing is placed. The Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). @@ -9637,22 +9730,49 @@ page in the page's order, and no entries for objects or the view: Cut (`artboard (`edit.paste`), Undo, Redo, New Artboard (`artboard.new`), Duplicate Artboards (`artboard.duplicate`), Rename (`artboard.rename`), Delete Artboards (`artboard.delete` with `indices`), Delete Empty Artboards (`artboard.deleteEmpty`), Select All Artboards (`artboard.selectAll`), Lock Artboards and Unlock Artboards -(`artboard.setProps` with `locked`), Rearrange (`artboard.rearrange`), Fit to Artwork Bounds (`artboard.fitToArt`), -Switch Orientation (`artboard.switchOrientation`), Artboard Options (`tool.options {tool: "artboard"}`) and Export -(`file.exportForScreens`). Exit Isolation Mode and the Unlock submenu for locked objects under the pointer follow them. -Cut, Copy, Duplicate Artboards, Rename, Delete Artboards, Lock Selected, Unlock Selected, Fit to Artwork Bounds, Switch -Orientation and Export act on the artboards the tool has selected, else the active one. Artboard Options opens on the -active artboard. New Artboard, Paste, Undo, Redo, Delete Empty Artboards, Select All Artboards and Rearrange do not act on -the selected artboards. Lock All and Unlock All act on every artboard, and Lock All Except Selected acts on the artboards -that are not selected. A right-click on an artboard that is not selected first selects it alone. An entry that cannot -run is left out: Cut with a locked artboard or every artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Rearrange with -one artboard, Fit to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected -artboard to change, and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and +(`artboard.setProps` with `locked`), Rearrange (`artboard.rearrange` with `indices`), Fit to Artwork Bounds +(`artboard.fitToArt`), Switch Orientation (`artboard.switchOrientation`), Artboard Options +(`tool.options {tool: "artboard"}`) and Export (`file.exportForScreens`). Exit Isolation Mode and the Unlock submenu +for locked objects under the pointer follow them. Cut, Copy, Duplicate Artboards, Rename, Delete Artboards, Lock +Selected, Unlock Selected, Rearrange, Fit to Artwork Bounds, Switch Orientation and Export act on the artboards the tool +has selected, else the active one. Artboard Options opens on the active artboard. New Artboard, Paste, Undo, Redo, +Delete Empty Artboards and Select All Artboards do not act on the selected artboards. Lock All and Unlock All act on +every artboard, and Lock All Except Selected acts on the artboards that are not selected. A right-click on an artboard +that is not selected first selects it alone. An entry that cannot run is left out: Cut with a locked artboard or every +artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Fit +to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected artboard to change, +and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and Fit to Artwork Bounds once, at the right-click. Paste centers copied artboards on the right-click's point (`edit.paste {artboardsAt: [x, y]}`) and centers copied objects there too (`center`). Chosen from a menu or the command palette with the tool in use, `artboard.new` makes the new artboard active, `artboard.duplicate` selects the copies, and `artboard.delete` and `artboard.deleteEmpty` make a remaining artboard active. +Rearrange for selected artboards: the +[Rearrange artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html) +help page describes rearranging only the artboards picked with the Artboard tool, with the same layout, order, count, +spacing and move-artwork choices as for all artboards, and a click on the canvas that puts the arrangement in place. +`artboard.rearrange {indices: [n…]}` lays out only those artboards (zero-based, sorted, an index given twice counts once), +in document order, and leaves every other artboard, its art and its guides where they are; `at: [x, y]` puts the +grid's top-left there, else at the first listed artboard's top-left. A listed locked artboard stays where it is and +keeps its cell. With `moveArtwork`, an object moves with the listed artboard its center is on; an object whose center +is on another artboard stays. `indices` that is not a list, an empty list, an entry that is not a whole number and an +`at` that is not [x, y] are refused before anything moves, and an index past the last artboard is `no such artboard`. +The reply adds `indices` and `moved`, the number of artboards that moved; with none moved (every listed artboard +locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard, and its +reply is `{artboards, rows, columns}`; `at` there puts the grid's top-left at `at` too. In the desktop app, the +Artboard tool's canvas menu and Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards +panel's menu (Rearrange…), open the Rearrange dialog (kind `rearrangeArtboards` with field `indices`) for the +artboards the tool has selected, showing their count. With another tool Rearrange… is off. The panel's Rearrange +button stays Rearrange All Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the +next press on the canvas runs `artboard.rearrange` with `indices` and `at` at the press, as one undo step. Enter, when +no other control has the keyboard focus, runs it with `at` at the pointer over the canvas, else without `at` (the grid at the first selected artboard's top-left). +A press with Space held pans or zooms as usual and places nothing. Esc, another tool or another document cancels it +without an edit. The status bar reads "Click on the canvas to place the +artboards (Esc cancels)" meanwhile. The top-left reference point, the outline, the fallback to the first artboard's +corner and the rules for locked artboards and art on other artboards are VectorCraft's own. Object › Artboards › +Rearrange All Artboards…, the Artboards panel's Rearrange All Artboards… and the Properties panel's Rearrange All still +lay out every artboard at once. + Locked artboards: `artboard.setProps {index, locked: true}` locks an artboard and `{index, locked: false}` unlocks it, each in one undo step. The Artboards panel's lock column, left of a row's options icon, shows a lock on a locked artboard, and a click there runs this command. A locked artboard keeps its place and size. `artboard.setProps` with a @@ -10276,9 +10396,15 @@ type in a mask or in a symbol's or pattern's art once however many objects show (`[{font, match, family, style, file, embedding}]`: each font of `fonts`, in order, as the fontDetails category's rows give it: `match` is `exact`, `style` (a style the family lacks, shown in `family` `style`), `missingWithFallback` (not installed, shown in `family` `style`) or `missing`; `file` is the face's file name, null for a built-in face; `embedding` is `allowed`, `editing`, `previewPrint` or `forbidden`, null when no -face is found), `imageObjects` (`[{name, width, height, linked, file}]`: the image objects in the order the -linkedImages and embeddedImages categories list them, with the file a linked image's row shows and null for an -embedded one), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside +face is found), `imageObjects` (`[{name, width, height, linked, file, format, effectivePpi, memoryBytes, +storedBytes}]`: the image objects in the order the linkedImages and embeddedImages categories list them, with the file +a linked image's row shows and null for an embedded one; `format` is a linked image's file format by its extension, +else the format of the pixels the document holds, null when neither is known; `effectivePpi` is `[x, y]`, the pixels +per inch at the size the image is placed at (a distorted image measured at its middle), null when it has no area; +`memoryBytes` is, for an embedded image, width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, and +`storedBytes` is the bytes of the encoded image the document holds; both are null for a linked image; a linkedImages row reads +`PNG; 1200 × 800 px; 150 ppi — /art/photo.png` and an embeddedImages row `PNG; 1200 × 800 px; estimated memory 3.7 MiB`, +with `Unknown format`, `resolution unavailable` or `memory unavailable` for a value that is null), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside the English `document.units`), `document.transparency` (`{gridSize, gridColors, gridColorsName, simulatePaper, flattenerPreset}`: File › Document Setup's transparency settings, the grid's size (`small`, `medium` or `large`), its two colors as `#rrggbb`, their preset's name or `Custom`, Simulate Colored Paper and the flattener preset, which the @@ -13617,7 +13743,9 @@ changes nothing when a new `pluginsFolder` is missing, is not a folder or can't value or the folder the preference already holds, and the web build does not check folders. A filter or live effect may declare commands of its own ([plugins.md](plugins.md#commands)): each is the command `plugin..` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry -(`commands: [{id, command, label, params, paramsSchema}]`). Run it with `{ids?, params?}` (its parameters may also +(`commands: [{id, command, label, params, paramsSchema, menu?}]`; `menu`, `{path, after?, placed?}`, is the menu its +manifest places it in, with `placed: false` when the command stays in its plug-in's submenu, see +[plugins.md](plugins.md#placing-a-command-in-another-menu)). Run it with `{ids?, params?}` (its parameters may also be top-level keys): the parameters are checked before the plug-in runs, a run is one undo step named after the command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's name and the command's label and leaves the document and the undo history as they were. For `plugin.run` and plug-in @@ -15178,6 +15306,30 @@ Commands: ```json {"name":"run_command","arguments":{"command":"addon.pathtools.boundingCircle","params":{"offset":2}}} ``` +- `addon.pathtools.inscribedCircle {}` draws the largest live circle inside each selected closed path or compound + path (Object › Plug-ins › Path Precision Tools › Add Inscribed Circle, #6966). Its center is the shape's + [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). A path of a compound path + selected on its own counts as a path. The circle lies in the area the shape fills under its fill rule: holes and the + overlaps of crossing subpaths count as the fill shows them, and strokes and effects are left out. The command + flattens the outline to within 0.005 pt and searches square cells best first to within 0.01 pt, then measures the + radius from the center to the curves, so before the circle is drawn its radius is within 0.02 pt of the largest. + When the box of the filled area is less than 10 pt across on its narrower side, the search and the flattening use + a thousandth and a two-thousandth of that side, and the radius is within a five-hundredth of it. A curve whose + control polygon is longer than 4096² times the flattening tolerance (83,886 pt at 0.005 pt) is flattened more + coarsely, and the circle can be smaller by as much. A curved hole narrower than the flattening tolerance can also + make it smaller. A shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 + of the tolerance. The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command + draws it 0.03% smaller, and it stays inside where it touches the shape. Holes and gaps narrower than 1e-6 pt close + up, and edges can move by as much, as in the other path operations. The circles get the current paint and go on + top of the current layer, or of the isolated group, as other new art does; inside an isolated compound path they + join it and take its appearance. The new circles are selected, and one undo removes them all. It is an error, + with the document unchanged, when a selected object is not a closed path or compound path ("object N is not a + closed path or compound path"; an open path has no inside), when it fills no area ("object N fills no area"), and + when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces + once flattened, or the searches of all the selected objects together measure more than 134,217,728 distances from + a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length + that it flattens to no area even at the finest tolerance ("object N is too complex to measure"). + → `{id: the first circle, ids}` A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; @@ -15653,7 +15805,7 @@ document's inks for print, as one undo step: | `scope` | `selection`, `document` (the selection, or the document while nothing is selected) | What it fixes; `ids` stand for the selection | | `inkLimit` | total ink % 1…400, 0 off (off) | CMYK colours (solid, gradient stops, gradient meshes) with more ink than this are scaled down to it; colours of spot swatches and Registration stay | | `excludePureBlack` | bool (true) | Black-only CMYK and grey colours keep their ink | -| `removeWhiteOverprint` | bool (false) | White fills and strokes, characters' and the white color of a colorized image stop overprinting | +| `removeWhiteOverprint` | bool (false) | White fills and strokes, characters' and the white color of a colorized image stop overprinting; a white linked to a spot swatch at a tint above 0% is an ink and keeps overprinting | | `overprintBlack` | black % 1…100, 0 off (off) | Black-only and grey fills and strokes this dark or darker overprint, as `edit.colors.overprintBlack` sets it (not spot-linked or rich blacks) | | `textOnly` | bool (false) | Overprint Black on type only | | `fill`, `stroke` | bool (true) | Which paints the fixes reach | diff --git a/docs/plugins.md b/docs/plugins.md index 242afb543c..b0f72bfb63 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -89,14 +89,15 @@ replaced by a module without it. - **Menus.** A plug-in with commands is a submenu of **Object › Plug-ins** (a live effect: **Effect › Plug-ins**) named after the plug-in. The submenu holds the plug-in's own item, then its commands. A command with parameters has - an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A manifest cannot put a - command in another menu: a `menu` key in a command is ignored. -- **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its submenu, and the user can give it a + an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A command whose manifest + gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)). +- **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its menu, and the user can give it a shortcut. A manifest cannot give a command a shortcut. - **Actions and agents.** A command run is recorded in an action like any other command and plays back with its parameters. `run`, MCP and `command.batch` call it as `plugin..` with `{"ids"?: [...], "params"?: {…}}` (its parameters may also be top-level keys). MCP's `command_list` and `list_commands` list it, and `plugin.list` - lists a plug-in's commands as `commands: [{id, command, label, params, paramsSchema}]`. + lists a plug-in's commands as `commands: [{id, command, label, params, paramsSchema, menu?}]`, with `menu` for a + command whose manifest places it in another menu. - **Runs.** The parameters are checked against the command's declarations before the plug-in runs. The plug-in runs through `vc_run` on the selection (or `ids`) as a filter run does, with `_context.mode` `"command"` and `_context.command` set to the command's id ([Parameters](#parameters)), under the plug-in's @@ -106,6 +107,40 @@ replaced by a module without it. document and the undo history as they were, and the error starts with the plug-in's name and the command's label (`“Cmd Test” › Grow: …`). +#### Placing a command in another menu + +At `api` 2 a command may name the menu it is listed in with `menu`: `{"path": [menu, …], "after"?: item}`. For +example, `"menu": {"path": ["Select"], "after": "Inverse"}` lists the command in the Select menu right after +Inverse. + +- `path` is one of these menus, by their English labels: `["Edit"]`, `["Edit", "Edit Colors"]`, `["Object"]`, + `["Object", "Transform"]`, `["Object", "Arrange"]`, `["Object", "Path"]`, `["Object", "Compound Path"]`, + `["Object", "Clipping Mask"]`, `["Type"]`, `["Select"]`, `["Select", "Same"]`, `["Select", "Object"]`, `["Effect"]` + and `["View"]`. The File, Window and Help menus, the application menu, Edit › Preferences and the submenus that list + files, fonts, panels or plug-ins cannot be named. Any other `path`, a `menu` that is not an object or is given twice, + a key other than `path` and `after`, and an `after` that is not 1–64 printable characters are refused when the + module is installed, and the error names the command. +- `after` is the English label of a built-in item or submenu of that menu, with or without its closing ellipsis + (`"Inverse"`). The command is listed right after it. An item that switches between two labels is matched by either + of them (`"Show Edges"` and `"Hide Edges"`, `"Start Global Edit"` and `"Stop Global Edit"`). Without `after`, or when no + built-in item of the menu has that label, the command is listed at the end of the menu, and the module still + installs. Items of plug-ins are never matched. +- The item's label is the command's label followed by the plug-in's name in parentheses (`Low Area Closed Paths + (Tidy)`). Keyboard Shortcuts, the command palette and `command_list` list the command under that menu with that + label. +- A command stays in its plug-in's submenu, under its own label, when its label with the plug-in's name has the same + letters and digits, ignoring case, as a built-in item or submenu of that menu (`Paste (in Place)` and Edit › Paste + in Place, `Hide (Edges)` and View › Hide Edges; either label of one that switches between two), or as a command that + a plug-in with a lower id, or an earlier command of the same plug-in, places in that menu. The desktop app and + `vectorcraft-cli` give the same result. `plugin.list` then gives the command's `menu` with + `"placed": false`. +- Commands of several plug-ins placed at the same spot are listed in plug-in id order, then in manifest order. A + plug-in whose commands all name another menu is listed in Object › Plug-ins (or Effect › Plug-ins) as a single item, + without a submenu. Commands without `menu` stay in the plug-in's submenu. +- A placed command leaves the menus when its plug-in is removed or replaced by a module without the command. Turning + the plug-in off (`plugin.setEnabled`) removes it at the next launch. +- At `api` 1 a `menu` key, repeated or not, is ignored and the command stays in the plug-in's submenu. + **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a @@ -587,10 +622,12 @@ the module's start function, in a run that isn't a filter's run on a document, o list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and `document.open` reads a file with the importer only when `importer` names it. - `commands` (filters and live effects; not heavy filters): up to 32 commands of the plug-in's own - ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}}`. An `id` is 1–32 characters from - `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with - control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` are. A malformed - entry is refused when the module is installed, and the error names the command by its id (or its place, `[0]`). + ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}, "menu"?: {…}}`. An `id` is 1–32 + characters from `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; + menus show it with control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` + are. `menu` (`api` 2 and later; ignored at `api` 1) places the command in [another menu](#placing-a-command-in-another-menu). + A malformed entry is refused when the module is installed, and the error names the command by its id (or its place, + `[0]`). - `commandAllowlist` (filters at `api` 2 with the usual budget, and only with the `commands` permission, which needs it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 293af3ab4b..b5346c5af7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -291,7 +291,7 @@ 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; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; 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; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores 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); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; 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; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; 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; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, 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; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, 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, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | @@ -647,6 +647,8 @@ since 2026-10-01. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. +- **Quick Pen length handles (#2660, in part):** the Quick Pen tool shows a handle beyond the start and the end of the path being drawn, or of the selected path, where the end is a straight line or a circular arc; dragging it makes the line longer or shorter along its direction, or the arc longer or shorter around its circle, as one undo step (`path.quickPenLength`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. A click on a handle that does not drag is an ordinary click. The handle's place, the 359° limit, the 1° minimum for a dragged last arc, Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules. Tests: tools `quickpen::tests` (`a_line_end_takes_a_new_length_along_its_direction`, `an_arc_end_keeps_its_circle`, `a_small_arc_end_follows_its_handle_around_the_circle`, `other_ends_have_no_piece`), engine `tests::quickpen` (`dragging_the_end_handle_lengthens_the_last_line`, `a_dragged_last_arc_still_flips`, `a_dragged_last_arc_keeps_at_least_one_degree`, `the_end_handle_changes_the_last_arc_on_a_shared_circle`, `another_selected_path_shows_its_handles`, `the_start_handle_of_a_selected_path_shortens_its_arc`, `a_click_on_a_handle_adds_a_point`, `a_length_drag_shows_no_next_piece`, `a_length_drag_stays_on_the_canvas`, `the_start_handle_keeps_the_last_arc_a_piece`, `path_quick_pen_length_sets_an_end`). Score and hours unchanged. + - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. @@ -1048,7 +1050,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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. 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. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` starts with a line holding the run's name in square brackets, such as `[main.jsx]`, then writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.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`, `localizedName`, `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: `localizedName` gives the same decoded name as `displayName`, without looking up a name the system shows in another language; 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; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants (it fails when the grants file is there but cannot be read) and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `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`). @@ -1107,7 +1109,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, the Type tools, the basic shape tools, the Smooth tool 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). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). + - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange (the selected artboards, placed with a click on the canvas) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - On a blank canvas the contextual task bar offers Draw (Pencil), which switches to the Pencil tool, and Place Image, which picks files for the Place dialog, as the help page lists for a new document (). VectorCraft's own rules: the bar shows them while a selection tool is in use in a document with no artwork (layers and guides only), sits under the active artboard (under the canvas's center when the artboard is out of view), and leaves out the Fill, Stroke, Recolor Artwork and Lock controls. Not done: Generate Vectors. Evidence: `a_blank_canvas_offers_draw_and_place_image`, `the_blank_canvas_bar_draws_with_the_pencil_and_places_an_image` and `the_blank_canvas_bar_wraps_on_a_narrow_canvas` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. @@ -1494,6 +1496,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). + VectorCraft's own preference General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default, part of #8326): on, Delete, Backspace and Edit › Clear remove the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece; the next anchor along (the one before at an open path's end) is selected, so the next Delete goes on along the path. Paths with a selected segment are still cut there, objects selected whole are still deleted, and a path left with fewer than two anchors goes, in one undo step. `edit.clear` takes a `keepJoined` param that defaults to the preference, and the value used joins the journal (`with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor`, `several_paths_and_an_object_selected_whole_change_in_one_undo_step`, `with_the_preference_on_delete_and_backspace_keep_the_path_joined`). 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). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. @@ -1541,7 +1544,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. + - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on, as "Select behind an object" (Ctrl+click twice) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. @@ -1669,6 +1672,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. + Rearrange lays out only the artboards the Artboard tool has selected, as the [Rearrange artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html) help page describes for a selection: the canvas context menu's Rearrange, the Contextual Task Bar's Rearrange, and the Artboards panel menu's Rearrange… with the Artboard tool open the Rearrange dialog for them, and after OK the grid's outline follows the pointer until a click on the canvas places its top-left there, in one undo step (`artboard.rearrange {indices, at}`); Enter places it from the keyboard, a Space-drag still pans, and Esc or another tool cancels it. The other artboards, their art and their guides stay where they are, and a selected locked artboard keeps its place and its cell. The top-left reference point and the handling of locked artboards and of art on unselected artboards are VectorCraft's own. Evidence: `tests::newdoc::{rearrange_lays_out_only_the_listed_artboards, rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones, rearrange_refuses_bad_indices_and_at}` in `crates/engine`, `tests::taskbar::rearrange_places_the_selected_artboards_where_the_canvas_is_clicked` and `dialogs::rearrange_artboards::tests::rearrange_from_the_canvas_menu_waits_for_a_click_with_the_selected_artboards` in `crates/ui-egui`. 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. With the Artboard tool, Paste and Paste in Place make the first pasted artboard the active one (the navigator's and the Artboards panel's), and Cut makes the artboard before the first cut one active (the new first artboard when artboard 1 was cut). A command that chooses another document (`document.activate`) starts the tool on that document's active artboard, as choosing its tab does, and File › Revert keeps the active artboard and starts the tool on it. Paste used to leave the active artboard where it was while the tool had the pasted artboard active, and Cut left the active artboard on the artboard after the cut one while the tool had the one before it. With the Artboard tool, an action that reverts the document or switches to another document and back (`command.batch`), and the Actions panel menu's Batch… over a folder whose files it closes or over data sets with a Revert step (`action.batch`), keep the active artboard and start the tool on it, as File › Revert does. They used to make artboard 1 the active one. @@ -1860,7 +1864,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. With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. 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, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch, Danish and Indonesian 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). +- **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, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch, Danish, Indonesian and Bulgarian 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). The Russian catalog (`crates/ui-egui/src/i18n/ru.tsv`) has 1,811 more `@msg` rows, for status and error messages of commands, scripts and file import and export, 3,444 `@msg` rows in all counted on 2026-11-13 (`russian_translates_command_script_and_file_messages` in `crates/ui-egui/src/i18n/tests.rs`). Scores and estimates are unchanged. 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. Burasagari ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) leaves a right-to-left paragraph's comma or full stop inside its line, which then ends at a break where it fits with the mark, and in a left-to-right line with right-to-left text and a tab it hangs a mark only when the mark is drawn at the line's right end and the rest of the line fits as drawn; otherwise the line ends at the latest break that fits as drawn. Both are VectorCraft's own rules (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/hang.rs`). Scores and estimates are unchanged. @@ -2015,6 +2019,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged. - **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged. - **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}`). **Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged. @@ -2099,6 +2104,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for panel deletion outside the Layers panel (archived copy). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the names and types of the brushes applied to the artwork, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, or with Selection Only the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`, `brushes`). Listing each brush once, leaving out the Brushes panel's brushes no art uses (`panelBrushNames` lists the panel's brushes), hidden strokes, strokes at an opacity of 0, strokes with no paint or width, guides, paths with no segment, type that draws no characters, a group's or layer's own strokes, a compound path member's own strokes and an image's strokes without a shape, and listing a brush the panel does not hold as missing, are VectorCraft's own rules. Tests: `cmd::docinfo::tests::info_lists_the_brushes` and `info_brushes_skip_undrawn_strokes_and_name_missing_brushes` (vectorcraft-engine). Document Info's Fonts category gives each font's type and number of uses beside its name, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) describes, for the whole document or with Selection Only for the selected type. The Document Info report and Package's report give them too (`document.info {category: "fonts"}`, `fontUses`), and the panel shows the type and count in the interface language. Counting a use as a text object set in the font (once however many of its runs use it, and the type in a mask or in a symbol's or pattern's art once however many objects show it), naming the type by the face's outlines (TrueType for `glyf`, OpenType for `CFF` or `CFF2`) and showing an unknown type for a font that is not installed in the family and style the type names are VectorCraft's own rules. Tests: `cmd::docinfo::tests::info_fonts_give_each_font_s_type_and_uses` (vectorcraft-engine), `panels::doc_info::tests::font_types_and_uses_show_in_the_interface_language` (vectorcraft-ui-egui), `fontdb::face::tests::outline_format_follows_the_outline_tables` (vectorcraft-text). + Document Info's Linked Images category gives each linked image's format, size in pixels, resolution and file, and its Embedded Images category gives each embedded image's format, size in pixels and memory size, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) describes, for the whole document or with Selection Only for the selected images. The Document Info report and Package's report give them too (`document.info {category: "linkedImages"}`, `imageObjects`' `format`, `effectivePpi`, `memoryBytes` and `storedBytes`), and the panel shows them in the interface language. Taking the format from a linked file's extension or else from the pixels the document holds, measuring the resolution at the size the image is placed at, counting the memory as the 8-bit RGBA pixels the image is drawn from (width × height × 4), and showing `Unknown format` or `resolution unavailable` when those are not known are VectorCraft's own rules. Tests: `cmd::docinfo::tests::image_rows_give_format_resolution_and_memory` and `byte_sizes_and_resolutions_read_to_a_tenth` (vectorcraft-engine), `panels::doc_info::tests::image_details_show_in_the_interface_language` (vectorcraft-ui-egui). 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, fills and strokes at an opacity of 0, 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). @@ -2267,7 +2273,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it, or when the document deleted it without unlinking the tint. Use Library Item also keeps a library pattern's colors when it adds a copy of one, but its numbered names do not skip the names of the library's other swatches. With Add to Swatches, a swatch of a numbered library name that a pattern's art brings, a tint or gradient included, keeps that name when no swatch or color group in the document uses it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too. A numbered copy whose name the library gives another swatch, and which is that swatch, is not reused for another color (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_library_tint_whose_color_the_document_deleted_brings_the_color_back`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name`, `a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name`, `a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it`, `a_numbered_library_pattern_keeps_its_name`, `a_library_pattern_swatchs_copy_skips_the_librarys_other_names`, `a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names`, `a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names`, `a_nested_pattern_does_not_take_a_name_the_library_gives_a_color`, `a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise`, `a_nested_patterns_swatch_takes_the_library_swatchs_free_name`, `a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found`, `a_new_patterns_swatch_takes_the_library_swatchs_free_name`, `a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern`, `a_numbered_name_is_kept_for_the_library_swatch_it_names`, `a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names`, `a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake`, `a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy`, `alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed`, `a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color`, `a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors`, `a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name`, `a_pasted_pattern_is_not_reused_by_taking_a_librarys_name`, `a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name`, `a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings`, `a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). @@ -2404,6 +2410,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells whose 8-bit samples carry none of the plate's ink out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate`, `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` and `print::tests::an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`. - The Print dialog's Graphics section's Fonts setting now reaches PostScript output, with the three choices [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=418) describes: Subset (the default) sends each page Type 3 fonts holding only the glyphs that page shows, Complete sends every glyph of each font once before the first page (an error past 64 MB), and None sends no font and asks for the printer's own by its PostScript name, with a note naming each one. Type in a gradient or pattern, color glyphs, glyphs bent along a curved path, ruby, a glyph without a name under None, and fonts whose license forbids embedding (or allows only whole embedding, under Subset) print as outlines as before, the license cases with a warning. PDF print still embeds subsets of the fonts whose licenses allow it and draws the others as outlines, and None or Complete adds a note saying so. The outlines-as-fallback and the size limit are VectorCraft's own rules. Evidence: `print::tests::subset_downloads_used_glyphs_once_per_page`, `print::tests::complete_downloads_whole_font_once_before_pages`, `print::tests::none_references_font_without_downloading_it`, `print::tests::forbidden_font_stays_art_with_a_note`, `print::tests::complete_large_font_fails_before_partial_output` (`vectorcraft-eps`), `tests::printps::the_fonts_setting_chooses_how_type_is_sent`, `tests::print::non_subset_font_choices_report_pdf_subset_output` (`vectorcraft-pdf`). Print scores and hours are unchanged. - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. + - With Discard White Overprint on, spot white objects keep overprinting and only paper white knocks out ([white overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html), [reference, White Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=650)). These are VectorCraft's own rules: a spot white is a white linked to a solid spot swatch at a tint above 0% (an opaque white ink, for example), so a 0% tint of a spot swatch is paper white, and so is a spot white that printed separations convert to process inks. A spot white's fills, strokes and characters keep overprinting in PDF export, Overprint Preview, Separations Preview and printed separations, its fills and strokes keep overprinting in composite print with Overprints set to Simulate, and Print Ink Fixes' Remove White Overprint leaves it overprinting. Overprint Preview and Separations Preview now also show overprinting paper white characters knocking out while the option is on, as PDF export writes them. EPS export keeps every overprint, as before. Evidence: `overprint::tests::a_white_spot_ink_overprints_under_discard_white`, `tests::layers::a_white_spot_ink_keeps_overprinting_under_discard_white_overprint` and `tests::print::a_white_spot_ink_keeps_overprinting_on_plates_and_in_simulated_composites` (`vectorcraft-pdf`), `cmd::addons::color::print_fixes::tests::a_white_spot_ink_keeps_its_overprint`, `tests::docsetup::discard_white_overprint_keeps_white_overprints_in_overprint_preview`, `tests::memory::proof_previews_draw_changes_as_a_new_renderer_does`, `tests::memory::overprinting_white_characters_follow_discard_white_overprint`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. 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 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 ``. 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`). @@ -2517,7 +2524,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The undo histories of all the open documents together keep their steps within a quarter of the installed memory on the same systems (at least 64 MiB, and at most a quarter of the address space in a 32-bit build), within 1 GiB where the installed memory can't be read, and within 256 MiB in the web build; past that budget the oldest steps of any open document are dropped first, but each document keeps its last eight undo steps and its next eight redo steps. Closing a document frees its share for the others. With `--deep`, each memory row of `vectorcraft-cli perf` also gives the peak so far: the peak working set on Windows and the peak resident memory (`VmHWM`) on Linux. A new last row gives the memory after the SVG export and the save → open → save at the end of the run. The renderer composes the two ink planes of a CMYK document that shows transparency into screen colors on up to as many threads as it rasterizes with, instead of on one. At 2880 × 1800 on 8 threads, a page of 300 shapes at 20% to 90% opacity takes 30 ms a frame instead of 55 ms, and 50,000 paths with one at 99% opacity take 258 ms instead of 361 ms (`vectorcraft-cli bench`), with the same pixels. - With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. + With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes, when a swatch becomes or stops being a spot color while it is on, or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. Pathfinder › Merge and the `pathfinder.merge` group effect find the faces of every fill in a few contour passes over the arrangement, as Trim and Crop do, instead of one pass for each distinct fill. The output paths and their order are the same. With 8,000 squares that do not touch, each with its own fill, Merge takes 72 to 107 ms instead of 17 to 32 s (release build). The Pathfinder panel, Offset Path, Clean Up, Divide Objects Below, Make and Release Blend, Envelope Distort's Make and Release, Repeat (Radial, Grid, Mirror and Release), Vector Halftone, New and Redefine Symbol, Delete Symbol, erasing with the Symbol Sprayer, Rasterize, Convert to Artboards, Flatten Transparency, Clear Guides, Shape Builder, Live Paint, Release Image Trace, Make and Release Opacity Mask, Delete with direct-selected anchor points, Remove Anchor Points, Cut Path, and the Shaper, Knife, Eraser, Path Eraser, Line Cut, Rectangle Cut, Mirror & Cut and Blob Brush tools add and remove objects in one pass over each layer or group they change, and Outline Stroke and Expand write each new object in the place of the object it replaces (#1429). Cut Path at Selected Anchor Points (`path.cutAtAnchors`) selects the cut ends with one selection call, which skips paths already selected through a hash set, instead of adding each cut path in turn and searching the paths already added. The selection is the same, every field (`selecting_cut_ends_matches_adding_them_one_by_one`). With the 8 middle anchors of each of 5,000 open paths of 10 anchors selected, building the selection of 40,000 cut ends takes 9.7 ms instead of 232 ms of CPU time, and with 2,000 paths 3.2 ms instead of 39 ms; at 500 paths both take 3 ms or less (medians of 7 runs, `cargo run --release -p vectorcraft-engine --example cut_path_select_bench`). Scores and hours unchanged. @@ -2551,6 +2558,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). + The Document Info panel keeps its `document.info` result in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, Selection Only is turned on or off, or, while the Artboard tool is the current tool, its options change; choosing a category filters the stored result. In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. In the web build, an edit while that view moves (a tool drag held near an edge of the canvas, which scrolls the view, or a wheel scroll during a drag) draws only the part of the last frame that the edit changed, at the view that frame was rendered for, and the frame stays drawn moved with the view until the view has been still for 0.2 s (#8688). The part of the canvas a pan uncovers shows the pasteboard and the artboards' paper until then, as for a pan without an edit. Edits that go on after the view stops don't start that 0.2 s again: the whole canvas renders 0.2 s after the view stopped. An edit that changes more than half of the frame, or one while more than the view and the document change, renders the whole canvas at once as before. Tests: `canvas::tests::without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still`, `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render`. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). @@ -2689,7 +2697,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. +- **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) unless its manifest places it in another menu, 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. +- **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands at one spot keep plug-in id order and then manifest order; a filter whose commands are all placed elsewhere is a single item in Object › Plug-ins, and such a live effect is a single item in Effect › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `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 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. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. 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. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. 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. @@ -3018,6 +3027,10 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Pre A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle (`addon.pathtools.boundingRectangle`) draws a live rectangle on the selection's geometric bounding box, and Add Bounding Circle (`addon.pathtools.boundingCircle`) draws the [smallest enclosing circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) of the selected outlines, with curves flattened to within 0.01 pt and the radius 0.01 pt larger, so the circle holds the curves. A curve is split into 1,024 pieces at most. One command makes at most 1,048,576 splits at any depth, and with `each` every shape gets an equal share. A shape that has used up its share splits each further curve into at most 8 pieces, with at most 7,340,032 more splits shared the same way (8,388,608 in all), and then counts each further curve whole. A piece that still bends more counts by the hull of its control points cut down to its bounding box, which can make the circle larger than the smallest one. Before the 0.01 pt is added, the circle around a circle of four curves is less than 0.3% larger when each curve is split into 8 pieces, and about 14% larger when each counts whole. Both use the current paint, go on top of the current layer or the isolated group, and are one undo step; shapes with no size are skipped (#6966). The commands take `each` (one shape per object) and `offset`, and the menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset, One per Object and Preview. Tests: `shapes::tests` in `vectorcraft-geom` (`enclosing`, `convex_hull`), `cmd::addons::pathtools::bounding::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object`). Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Add Inscribed Circle (2026-11-22) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (when the filled area's box is less than 10 pt across, within a five-hundredth of its narrower side), and the circle is then drawn 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The searches of one command share one work limit. The circles use the current paint, go on top of the current layer or the isolated group (inside an isolated compound path they join it and take its appearance), and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 anchors or flattened pieces or the search's limits are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, a small area left by the fill rule, the edge and work limits, a shared work limit, a long thin shape, a long rectangle, a fill far smaller than the precision, a lens and a bowed strip thinner than the flattening tolerance, the cell limit, no area), `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_inscribed_circle_draws_its_circles_without_a_dialog`). Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns the dashed stroke of each selected path and compound path into separate open paths, one per dash, for cutters and plotters that need the centre lines rather than Outline Stroke's filled outlines. The dashes are laid out by the renderer's own dash code, so they match what the canvas draws: the dash pattern, its offset and Align Dashes to Corners and Path Ends, a dash running on through the start of a closed path, a dash all the way round staying closed, and under a round or projecting cap each dot (a dash of no length) as a path on its point. Each dash keeps the path's appearance with the top stroke's dashes and arrowheads off; the path's fills stay on it, below its dashes; a compound path's dashes are plain paths. One undo step; the dashes are selected; at most 100000 (more, or a pattern too fine to draw, is refused). Tests: `expand_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (the stroke kept with dashes off, the offset, one undo step, the fill kept below, dashes centred on corners when aligned, dots under round and butt caps, compound paths, refusals and the piece cap), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 74d9503bbf..e1c6a08b3b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -208,7 +208,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: Ctrl+scroll for the arc size, and editing and deleting with the tool | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | @@ -366,7 +366,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) | | A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| 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 | +| 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); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, still selects the object behind it while Command Click to Select Objects Behind is on, so repeated Cmd-clicks select behind as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; 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 | | Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | @@ -560,6 +560,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored |