Merge main into fix/ui-port-text-divider-notice
@@ -156,6 +156,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 | |
|
||||
@@ -196,6 +197,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 | |
|
||||
@@ -205,6 +215,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 | |
|
||||
@@ -232,6 +245,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 | |
|
||||
@@ -250,6 +264,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 | |
|
||||
@@ -264,7 +280,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 | |
|
||||
@@ -275,7 +295,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 | |
|
||||
|
||||
@@ -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 `<name>_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.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20v-8a8 8 0 0 1 8-8h8"/><path d="M12 12L6.34 6.34" stroke-dasharray="1.5 2"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 332 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 15l4-4 4 3 4-6 4 3v9H4Z" fill="currentColor" fill-opacity="0.4"/><path d="M4 4v16h16"/></svg>
|
||||
|
After Width: | Height: | Size: 289 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="4" y="5" width="9" height="3"/><rect x="4" y="9.5" width="15" height="3"/><rect x="4" y="14" width="6" height="3"/></svg>
|
||||
|
After Width: | Height: | Size: 336 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="7" y="11" width="3" height="9"/><rect x="11.5" y="6" width="3" height="14"/><rect x="16" y="9" width="3" height="11"/></svg>
|
||||
|
After Width: | Height: | Size: 339 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><path d="M7 15l4-5 3 3 6-7"/></svg>
|
||||
|
After Width: | Height: | Size: 241 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8"/><path d="M12 12V4a8 8 0 0 1 6.93 12Z" fill="currentColor" fill-opacity="0.4"/></svg>
|
||||
|
After Width: | Height: | Size: 299 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4.5l7.61 5.53-2.91 8.94H7.3l-2.91-8.94Z"/><path d="M12 12.5V4.5M12 12.5l7.61-2.47M12 12.5l4.7 6.47M12 12.5l-4.7 6.47M12 12.5l-7.61-2.47" stroke-width="0.75"/><path d="M12 7.5l5.23 3.3-2.58 5.34-5.59.41-1.34-5.44Z" fill="currentColor" fill-opacity="0.4"/></svg>
|
||||
|
After Width: | Height: | Size: 457 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><circle cx="8" cy="15" r="1.3" fill="currentColor"/><circle cx="10.5" cy="10" r="1.3" fill="currentColor"/><circle cx="13.5" cy="13.5" r="1.3" fill="currentColor"/><circle cx="16" cy="7.5" r="1.3" fill="currentColor"/><circle cx="18" cy="11.5" r="1.3" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 485 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="4" y="5" width="9" height="3"/><rect x="4" y="9.5" width="15" height="3"/><rect x="4" y="14" width="6" height="3"/><rect x="4" y="5" width="5" height="3" fill="currentColor"/><rect x="4" y="9.5" width="8" height="3" fill="currentColor"/><rect x="4" y="14" width="3" height="3" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 519 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="7" y="11" width="3" height="9"/><rect x="11.5" y="6" width="3" height="14"/><rect x="16" y="9" width="3" height="11"/><rect x="7" y="16" width="3" height="4" fill="currentColor"/><rect x="11.5" y="13" width="3" height="7" fill="currentColor"/><rect x="16" y="15" width="3" height="5" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 526 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 15.7A8.5 6.5 0 1 1 11 16.4"/><circle cx="7" cy="17.6" r="1.5"/><path d="M6.2 19c-.4 1-1 1.8-1.9 2.4"/><rect x="10" y="8" width="4" height="4" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 365 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 15.7L3.5 9 9 3.5l9 1 3 6.5-6 5.4h-4"/><circle cx="7" cy="17.6" r="1.5"/><path d="M6.2 19c-.4 1-1 1.8-1.9 2.4"/></svg>
|
||||
|
After Width: | Height: | Size: 313 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 15.7A8.5 6.5 0 1 1 11 16.4"/><circle cx="7" cy="17.6" r="1.5"/><path d="M6.2 19c-.4 1-1 1.8-1.9 2.4"/></svg>
|
||||
|
After Width: | Height: | Size: 304 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 21l4.5-9h7l4.5 9Z"/><path d="M10 12v9M4.25 16.5h11.5"/><path d="M15 2v9.5l2.4-2.3 1.7 3.6 1.5-.7-1.7-3.5h3.3Z" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 334 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 12H21" stroke-dasharray="3 3"/></svg>
|
||||
|
After Width: | Height: | Size: 232 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 12H20.5"/><path d="M15 6.5L20.5 12L15 17.5"/></svg>
|
||||
|
After Width: | Height: | Size: 246 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7h9v2h9v9H3Z"/><path d="M12 9v9" stroke-dasharray="2 2"/></svg>
|
||||
|
After Width: | Height: | Size: 259 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="10" height="10" stroke-dasharray="2 2.5"/><rect x="3" y="3" width="4" height="3.5" fill="currentColor"/><path d="M14.5 12.5v9l2.3-2.2 1.6 3.4 1.4-.7-1.6-3.3h3.1Z" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 399 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="10" height="10" stroke-dasharray="2 2.5"/><rect x="3" y="3" width="4" height="3.5" fill="currentColor"/><path d="M11.5 21.5l2.5-6 3.5 3.5Z" fill="currentColor"/><path d="M15.75 17.25l4.5-4.5a1.6 1.6 0 0 1 2.25 2.25l-4.5 4.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 442 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 18C7 8 17 8 21 18"/><rect x="10.5" y="9" width="3" height="3" fill="currentColor"/><path d="M8 5H3.5M5.5 3L3.5 5l2 2M16 5h4.5M18.5 3l2 2-2 2"/></svg>
|
||||
|
After Width: | Height: | Size: 345 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="5.5" cy="12" r="3" fill="currentColor"/><circle cx="12" cy="12" r="3" fill="currentColor" fill-opacity="0.4"/><circle cx="18.5" cy="12" r="3"/></svg>
|
||||
|
After Width: | Height: | Size: 345 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10.5" r="2"/><circle cx="14" cy="10.5" r="2"/><circle cx="12" cy="14" r="2"/><path d="M2 12h4M4.5 10.5L6 12l-1.5 1.5M22 12h-4M19.5 10.5L18 12l1.5 1.5"/></svg>
|
||||
|
After Width: | Height: | Size: 362 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6.5" r="2"/><circle cx="5" cy="12" r="2"/><circle cx="7" cy="17.5" r="2"/><path d="M11 12h10M18 9l3 3-3 3"/></svg>
|
||||
|
After Width: | Height: | Size: 317 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="18" r="2"/><circle cx="15.5" cy="8.5" r="5.5"/><path d="M8 16l3-3M8.5 13H11v2.5"/></svg>
|
||||
|
After Width: | Height: | Size: 291 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 9l3 3-3 3-3-3Z"/><path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M17.3 3.2v3.5h-3.5"/></svg>
|
||||
|
After Width: | Height: | Size: 292 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6.5" cy="7" r="2.5"/><circle cx="6.5" cy="16.5" r="2.5" fill="currentColor"/><path d="M16 5c2.6 3.5 4 5.6 4 7.6a4 4 0 0 1-8 0c0-2 1.4-4.1 4-7.6Z" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 369 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="15" r="3.5"/><circle cx="15.5" cy="11" r="4.5" fill="currentColor" fill-opacity="0.4"/><circle cx="15.5" cy="11" r="2"/><path d="M19.5 2.5v3M18 4h3"/></svg>
|
||||
|
After Width: | Height: | Size: 359 B |
@@ -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())
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String>) -> 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<String> {
|
||||
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<String> {
|
||||
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:?}");
|
||||
|
||||
@@ -12,6 +12,9 @@ pub type AnchorRef = (usize, usize);
|
||||
/// (subpath index, segment index) inside a path.
|
||||
pub type SegmentRef = (usize, usize);
|
||||
|
||||
/// The most objects [`Selection::add_all`] adds by looking for each one in the selected objects.
|
||||
const FEW_TO_ADD: usize = 8;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Selection {
|
||||
/// Selected objects in selection order.
|
||||
@@ -197,14 +200,24 @@ impl Selection {
|
||||
/// carry its current activation, so a removal drops every slot of the id at once.
|
||||
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
|
||||
use std::collections::hash_map::{Entry, HashMap};
|
||||
let mut ids = ids.into_iter().peekable();
|
||||
if ids.peek().is_none() {
|
||||
let ids: Vec<NodeId> = ids.into_iter().collect();
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
// Up to [`FEW_TO_ADD`] objects to add are each looked for in the selected objects; more go
|
||||
// through a table of the selected objects.
|
||||
if !toggle && ids.len() <= FEW_TO_ADD {
|
||||
for id in ids {
|
||||
if !self.objects.contains(&id) {
|
||||
self.objects.push(id);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
|
||||
let mut added: Vec<(NodeId, usize)> = Vec::new();
|
||||
let mut removed = false;
|
||||
|
||||
@@ -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;
|
||||
@@ -859,6 +860,10 @@ pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// What the fill and stroke proxies read from the selected objects, kept with the selection
|
||||
/// ([`crate::doc_state::SelectionRecord`]).
|
||||
pub(crate) use paint::SelectionPaints;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
/// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`.
|
||||
pub(crate) fn date_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<i64>>> {
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -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<String>) -> 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<String>) -> (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<Value> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)]);
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v.extend(bounding::specs());
|
||||
v.extend(inscribed::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
// 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::<Vec<_>>() }))
|
||||
}
|
||||
@@ -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<NodeId> {
|
||||
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::<Vec<_>>()})).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::<Vec<_>>();
|
||||
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<Point> = 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");
|
||||
}
|
||||
}
|
||||
@@ -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<NodeId> = 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::<Vec<_>>()
|
||||
})
|
||||
.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<bool> {
|
||||
let fill = ap.items.get(at)?.is_fill();
|
||||
|
||||
@@ -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<String, SwatchChoice>,
|
||||
/// 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<BTreeMap<String, Swatch>>,
|
||||
}
|
||||
|
||||
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::<Result<_>>()? })
|
||||
}
|
||||
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::<Result<_>>()?,
|
||||
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<BTreeMap<String, Swatch>>) -> 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<String>,
|
||||
/// The global and spot colors that took the document's color (merged).
|
||||
merged_swatches: BTreeSet<String>,
|
||||
/// 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<String, Swatch>, 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<Placed>| 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)
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -166,7 +166,7 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// 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,
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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",
|
||||
|
||||
@@ -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<Value> {
|
||||
})?;
|
||||
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<Value> {
|
||||
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 }))
|
||||
}
|
||||
|
||||
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} 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); 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)} 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); without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -1221,6 +1221,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
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() {
|
||||
@@ -1228,7 +1229,8 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// 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() {
|
||||
@@ -1275,6 +1277,17 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<bool> {
|
||||
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<Value> {
|
||||
const CMD: &str = "edit.dropSelection";
|
||||
|
||||
@@ -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<f32> = 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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -187,7 +187,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
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<Vec<usize>> = 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<Rect> = d.artboards.iter().map(|a| a.rect).collect();
|
||||
let laid: Vec<usize> = picked.clone().unwrap_or_else(|| (0..count).collect());
|
||||
let rects: Vec<Rect> = 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<Vec2> =
|
||||
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<Value> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "artboards": count, "rows": rows, "columns": cols }))
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//! resets new art when it opens such a document.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
@@ -32,7 +33,9 @@ pub(crate) struct NewArtSource {
|
||||
}
|
||||
|
||||
use super::gradient::unplaced;
|
||||
use super::paint::SelectionPaints;
|
||||
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
|
||||
use crate::doc_state::{SelectionRecord, objects_only};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -267,9 +270,10 @@ impl Session {
|
||||
if !has_paint {
|
||||
return;
|
||||
}
|
||||
let (fill_mixed, stroke_mixed) = self.proxy_mixed();
|
||||
let read = self.read_selection_paints();
|
||||
let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed));
|
||||
let (fill, stroke) = self.proxy_paints();
|
||||
let weight_mixed = self.active().is_some_and(|st| st.stroke_mixed().weight);
|
||||
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed);
|
||||
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
|
||||
if !fill_mixed {
|
||||
self.paint.fill = unplaced(&fill);
|
||||
@@ -281,6 +285,30 @@ impl Session {
|
||||
self.paint.stroke_width = width;
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`SelectionPaints`] of the active document's selection, read now and kept in its
|
||||
/// [`SelectionRecord`] when the record holds none. `None` when anything besides whole objects
|
||||
/// is selected ([`objects_only`]), with an active Appearance item, when a selected object is in
|
||||
/// a Live Paint group, and with gradient mesh points picked: the proxies then read the
|
||||
/// selection with [`Session::proxy_mixed`] and [`crate::DocState::stroke_mixed`]. While the
|
||||
/// Live Paint Bucket paints, [`Session::load_selection_paints`] returns before reading them.
|
||||
fn read_selection_paints(&mut self) -> Option<SelectionPaints> {
|
||||
if self.appearance_item().is_some() {
|
||||
return None;
|
||||
}
|
||||
let st = self.active_mut()?;
|
||||
if !objects_only(&st.selection) {
|
||||
return None;
|
||||
}
|
||||
if st.selection_paints().is_none() {
|
||||
let paints = SelectionPaints::of(&st.doc, &st.selection.objects);
|
||||
let settled = st.selection_record().and_then(|r| r.settled);
|
||||
st.selection_record =
|
||||
Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) });
|
||||
}
|
||||
let paints = st.selection_paints()?.clone();
|
||||
(!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints)
|
||||
}
|
||||
}
|
||||
|
||||
fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -601,6 +601,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<Point>, 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)]);
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Points",
|
||||
[],
|
||||
None,
|
||||
"{} 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)",
|
||||
"{} 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<Value> {
|
||||
/// 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<Value> {
|
||||
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<Value> {
|
||||
// `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 st = s.doc()?;
|
||||
@@ -1681,6 +1692,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.remove_many(&whole_ids)?;
|
||||
}
|
||||
let mut survivors = vec![];
|
||||
let mut following = vec![];
|
||||
let remaining: Vec<NodeId> = sel.keys().copied().filter(|id| d.node(*id).is_some()).collect();
|
||||
let mut emptied = Beside::replacing(d, &remaining);
|
||||
for (id, set) in &sel {
|
||||
@@ -1688,6 +1700,23 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<SubPath> = {
|
||||
let path = path_mut(d, *id)?;
|
||||
@@ -1731,6 +1760,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
selection.set(survivors);
|
||||
for (id, next) in following {
|
||||
if !next.is_empty() {
|
||||
selection.anchors.insert(id, next);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -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<BTreeMap<String, Swatch>>;
|
||||
|
||||
/// 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<String> = 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<String> {
|
||||
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<String> {
|
||||
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
|
||||
|
||||
@@ -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<String> {
|
||||
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<String, Option<&'static [&'static str]>>;
|
||||
static PLACED: Mutex<Option<(u64, Placed)>> = 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<CommandSpec> {
|
||||
"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.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, 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.<id>.<command id>, 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.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, 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.<id>.<command id>, 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
|
||||
),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
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) {
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::appearance::{ItemTarget, edit_items, item_target};
|
||||
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
|
||||
use super::paint::{live_paint_parts_skipped, painted};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
|
||||
use crate::DocState;
|
||||
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
|
||||
@@ -465,7 +465,7 @@ impl Session {
|
||||
// A Live Paint group without edges shows the next selected object's stroke; any other object
|
||||
// without a painted object shows none. A face or edge selected with its Live Paint group counts
|
||||
// with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
let covered = st.selection_live_paint_covered(&st.selection.objects);
|
||||
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
@@ -540,7 +540,7 @@ impl DocState {
|
||||
} else {
|
||||
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
let covered = self.selection_live_paint_covered(&self.selection.objects);
|
||||
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
|
||||
painted(n, true, true, &mut nodes);
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<String>, 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<Swatch>, Vec<Swatch>) = (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<String>, taken: &mut HashSet<String>, 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<String> = 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<Value> {
|
||||
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<String> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
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<Value> {
|
||||
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 {
|
||||
|
||||
@@ -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<Option<(NodeId, usize, usize)>> {
|
||||
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
|
||||
|
||||
@@ -150,6 +150,39 @@ pub struct DocState {
|
||||
/// measured: the next refresh checks only the layer trees that differ from it
|
||||
/// ([`cmd::inline::refresh`]). Not saved.
|
||||
pub(crate) inline_resolved: Option<cmd::inline::Resolved>,
|
||||
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
|
||||
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
|
||||
pub(crate) selection_record: Option<SelectionRecord>,
|
||||
}
|
||||
|
||||
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
|
||||
/// while the document and the selected objects stay the same, a command that adds objects checks
|
||||
/// and reads only the added ones.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct SelectionRecord {
|
||||
/// The document, held as [`EmptyArtboards::doc`] holds it.
|
||||
pub(crate) doc: std::sync::Weak<Document>,
|
||||
pub(crate) objects: Vec<NodeId>,
|
||||
/// Lock Guides as it was when [`crate::Session::select`] left these objects selected; `None`
|
||||
/// when it did not.
|
||||
pub(crate) settled: Option<bool>,
|
||||
/// What the proxies read from these objects; `None` when they were not read.
|
||||
pub(crate) paints: Option<cmd::SelectionPaints>,
|
||||
}
|
||||
|
||||
/// Whether `sel` holds selected objects and nothing else: no anchors, segments, key, target,
|
||||
/// slices, ruler guides, object of a symbol instance's art or object on a path.
|
||||
pub(crate) fn objects_only(sel: &Selection) -> bool {
|
||||
sel.anchors.is_empty()
|
||||
&& sel.segments.is_empty()
|
||||
&& sel.key.is_none()
|
||||
&& sel.target.is_none()
|
||||
&& sel.slices.is_empty()
|
||||
&& sel.guides.is_empty()
|
||||
&& sel.key_guide.is_none()
|
||||
&& sel.key_anchor.is_none()
|
||||
&& sel.symbol_part.is_none()
|
||||
&& sel.on_path_member.is_none()
|
||||
}
|
||||
|
||||
/// What the commands scripts ran did to an open document since the person last opened or saved it
|
||||
@@ -407,8 +440,46 @@ impl DocState {
|
||||
art_to_fit: Default::default(),
|
||||
measured_in_own: None,
|
||||
inline_resolved: None,
|
||||
selection_record: None,
|
||||
}
|
||||
}
|
||||
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
|
||||
/// objects changed since it was made, or when anything besides whole objects is selected
|
||||
/// ([`objects_only`]). Only a new [`Document`] makes the record stale: the document's new art
|
||||
/// is the one state that changes in place and matters to it, and [`crate::Session::select`]
|
||||
/// checks the whole selection while there is new art.
|
||||
pub(crate) fn selection_record(&self) -> Option<&SelectionRecord> {
|
||||
self.selection_record
|
||||
.as_ref()
|
||||
.filter(|r| std::ptr::eq(r.doc.as_ptr(), Arc::as_ptr(&self.doc)) && objects_only(&self.selection) && r.objects == self.selection.objects)
|
||||
}
|
||||
/// What the proxies read from the selected objects, when the [`SelectionRecord`] of the
|
||||
/// selection now holds it.
|
||||
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
|
||||
self.selection_record().and_then(|r| r.paints.as_ref())
|
||||
}
|
||||
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
|
||||
/// Lock Guides `guides_locked`. `record` is the record of the selection before: when the
|
||||
/// selected objects start with its objects, the added objects are read into its paints.
|
||||
pub(crate) fn record_selection(&mut self, record: Option<SelectionRecord>, guides_locked: bool) {
|
||||
if !objects_only(&self.selection) {
|
||||
self.selection_record = None;
|
||||
return;
|
||||
}
|
||||
let objects = &self.selection.objects;
|
||||
self.selection_record = Some(match record {
|
||||
Some(mut r) if objects.starts_with(&r.objects) => {
|
||||
let added = &objects[r.objects.len()..];
|
||||
if let Some(p) = &mut r.paints {
|
||||
p.add(&self.doc, added);
|
||||
}
|
||||
r.objects.extend_from_slice(added);
|
||||
r.settled = Some(guides_locked);
|
||||
r
|
||||
}
|
||||
_ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None },
|
||||
});
|
||||
}
|
||||
|
||||
/// The document, its file and the file it was read from as the person last left them, for the
|
||||
/// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command
|
||||
|
||||
@@ -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<u64>, &'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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -923,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
|
||||
/// 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<serde_json::Value> {
|
||||
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<Vec<serde_json::Value>> {
|
||||
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<Vec<serde_json::Value>> {
|
||||
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
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<Vec<serde_json::Val
|
||||
&& g["write"].is_boolean()
|
||||
&& g["folder"].is_boolean()
|
||||
};
|
||||
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
|
||||
if strict {
|
||||
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
|
||||
if grants.len() > 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<std::fs::File> {
|
||||
}
|
||||
|
||||
/// 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<serde_json::Value> {
|
||||
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<Vec<serde_json::Value>> {
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::{
|
||||
Arc, Document, EngineError, Interaction, LastTransform, NamedStep, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane,
|
||||
objects_in_range,
|
||||
Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden,
|
||||
doc_sane, objects_in_range,
|
||||
};
|
||||
use crate::doc_state::objects_only;
|
||||
|
||||
impl Session {
|
||||
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
|
||||
@@ -210,14 +211,32 @@ impl Session {
|
||||
let st = self.doc_mut()?;
|
||||
let before = st.selection.objects.clone();
|
||||
let new_art = st.selection.new_art.clone();
|
||||
let record = if st.selection_record().is_some() { st.selection_record.take() } else { None };
|
||||
f(&st.doc, &mut st.selection);
|
||||
st.selection.prune(&st.doc);
|
||||
// Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide
|
||||
// Slices keep the slices out, whatever selects them.
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// The art on a locked artboard can't be selected, whatever selects it, except new art
|
||||
// that was selected and still is.
|
||||
st.protect_locked_artboards(&before, &new_art, None);
|
||||
let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before);
|
||||
// Objects added to objects this checked in the same document, with Lock Guides as it was
|
||||
// then and no art on a locked artboard to protect, are checked alone, by the rules `prune`
|
||||
// and `deselect_hidden` apply to an object.
|
||||
let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked))
|
||||
&& st.selection.new_art.is_empty()
|
||||
&& st.doc.new_art.get().is_empty()
|
||||
&& !st.doc.artboards.iter().any(|a| a.locked);
|
||||
if added && settled {
|
||||
let doc = &st.doc;
|
||||
let tail = st.selection.objects.split_off(before.len());
|
||||
st.selection.objects.extend(tail.into_iter().filter(|id| {
|
||||
doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
}));
|
||||
} else {
|
||||
st.selection.prune(&st.doc);
|
||||
// Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide
|
||||
// Slices keep the slices out, whatever selects them.
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// The art on a locked artboard can't be selected, whatever selects it, except new art
|
||||
// that was selected and still is.
|
||||
st.protect_locked_artboards(&before, &new_art, None);
|
||||
}
|
||||
st.record_selection(record, menu.guides_locked);
|
||||
// Selecting art makes its layer (or sublayer) the current one, as in the Layers panel of
|
||||
// the reference app: new art then goes beside it.
|
||||
if st.selection.objects != before
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<PathData> {
|
||||
s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned())
|
||||
}
|
||||
|
||||
fn points(s: &Session, id: NodeId) -> Vec<Point> {
|
||||
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);
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Commands that remove, insert or copy many objects, and an Alt-drag that copies them, each walk
|
||||
//! the document's tree a few times on one layer of 25,000 to 100,000 objects, and objects in two
|
||||
//! layers and inside a group keep their order and ids.
|
||||
//! layers and inside a group keep their order and ids. Selecting objects one at a time looks up
|
||||
//! only the added ones.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -696,3 +697,27 @@ fn copies_of_ids_listed_twice_or_inside_another_listed_id_keep_their_order_and_i
|
||||
assert_eq!(layers(&s), [json!([a, n + 1, n, b, c, [group, d, e, f]]), json!([g, h])]);
|
||||
undo_gives_back(&mut s, &before);
|
||||
}
|
||||
|
||||
/// `select.add` run once for each of `n` objects, from nothing selected → the walks of the tree and
|
||||
/// the lookups by id it took.
|
||||
fn add_one_at_a_time(n: usize) -> (u64, u64) {
|
||||
let mut s = session(n, square);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let ids = layer(&s, 0);
|
||||
let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups());
|
||||
for id in &ids {
|
||||
s.execute("select.add", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
assert!(selected(&s, &ids));
|
||||
(vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups)
|
||||
}
|
||||
|
||||
/// Selecting objects one at a time checks and reads only the object each `select.add` adds: twice
|
||||
/// as many objects take about twice as many lookups, and the tree is not walked for each one.
|
||||
#[test]
|
||||
fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() {
|
||||
let (walks, lookups) = add_one_at_a_time(1_000);
|
||||
let (more_walks, more_lookups) = add_one_at_a_time(2_000);
|
||||
assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times");
|
||||
assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000");
|
||||
}
|
||||
|
||||
@@ -4621,6 +4621,38 @@ fn locked_guides_lock_guide_paths() {
|
||||
assert_eq!(selected(&s), vec![b]);
|
||||
}
|
||||
|
||||
/// A guide path added to the selection after another object stays unselected while Lock Guides is
|
||||
/// on, and is selected once it is off.
|
||||
#[test]
|
||||
fn a_guide_path_added_after_another_object_stays_unselected_while_guides_are_locked() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
let g = guide_path(&mut s, 0.0);
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
for id in [b, g] {
|
||||
s.execute("select.add", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
assert_eq!(selected(&s), vec![b]);
|
||||
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b, g]);
|
||||
}
|
||||
|
||||
/// An id that names no object and a ruler guide's id, added to a selection after another object,
|
||||
/// leave the selection as a whole new selection of the same ids would.
|
||||
#[test]
|
||||
fn a_missing_object_and_a_ruler_guide_added_after_another_object_stay_unselected() {
|
||||
let mut s = session();
|
||||
let (b, c) = (rect(&mut s, 20.0, 20.0, 10.0, 10.0), rect(&mut s, 40.0, 20.0, 10.0, 10.0));
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
|
||||
let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
|
||||
let missing = NodeId(u64::MAX);
|
||||
s.select(|_, sel| sel.objects.extend([missing, guide, c])).unwrap();
|
||||
assert_eq!(selected(&s), vec![b, c]);
|
||||
}
|
||||
|
||||
/// A rectangle at (`x`, 0), 10 pt wide, made into a guide; nothing is selected after.
|
||||
fn guide_path(s: &mut Session, x: f64) -> NodeId {
|
||||
let g = rect(s, x, 0.0, 10.0, 10.0);
|
||||
|
||||
@@ -192,6 +192,47 @@ fn a_paint_the_selected_objects_do_not_share_stays_as_it_was() {
|
||||
assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (node(&s, a).appearance.stroke_paint(), 5.0), "the strokes are shared");
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, id: NodeId) {
|
||||
run(s, "select.add", json!({"ids": [id.0]}));
|
||||
}
|
||||
|
||||
/// Objects added one at a time are compared with the objects already selected: a fill and weight
|
||||
/// they all share loads, one they don't stays as it was.
|
||||
#[test]
|
||||
fn objects_added_one_at_a_time_load_only_the_paints_all_selected_objects_share() {
|
||||
let mut s = session();
|
||||
let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0);
|
||||
let b = painted(&mut s, 120.0, "#ff0000", "#00ff00", 5.0);
|
||||
let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0);
|
||||
let red = node(&s, a).appearance.fill_paint();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
add(&mut s, a);
|
||||
(s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5);
|
||||
add(&mut s, b);
|
||||
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and b share them");
|
||||
(s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5);
|
||||
add(&mut s, c);
|
||||
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.5), "c's differ");
|
||||
}
|
||||
|
||||
/// An edit of the selected objects between two additions is read: the objects selected before it
|
||||
/// are compared as the edit left them.
|
||||
#[test]
|
||||
fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() {
|
||||
let mut s = session();
|
||||
let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0);
|
||||
let b = painted(&mut s, 120.0, "#ff0000", "#00ff00", 5.0);
|
||||
let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0);
|
||||
let blue = node(&s, c).appearance.fill_paint();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
add(&mut s, a);
|
||||
add(&mut s, b);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "ids": [a.0, b.0]}));
|
||||
s.paint.fill = Paint::None;
|
||||
add(&mut s, c);
|
||||
assert_eq!(s.paint.fill, blue, "a, b and c are all blue now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_without_paint_leaves_the_proxies_as_they_were() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -532,6 +532,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<NodeId> = 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<f64> = 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()));
|
||||
|
||||
@@ -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<Value> = 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);
|
||||
|
||||
@@ -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::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn fill_opacity(s: &Session, id: NodeId) -> f32 {
|
||||
node(s, id).appearance.fill().unwrap().opacity
|
||||
}
|
||||
|
||||
fn undo_labels(s: &Session) -> Vec<String> {
|
||||
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<f32> = 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<Paint> = 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);
|
||||
}
|
||||
@@ -967,6 +967,21 @@ fn a_locked_artboard_protects_the_art_on_it() {
|
||||
assert!(!tile.is_empty() && !tile.contains(&a), "{tile:?}");
|
||||
}
|
||||
|
||||
/// Art on a locked artboard stays unselected when `select.add` adds it after another object.
|
||||
#[test]
|
||||
fn art_on_a_locked_artboard_added_after_another_object_stays_unselected() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s);
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 200, "height": 200})).unwrap();
|
||||
let b = NodeId(s.execute("shape.rectangle", &json!({"x": 1010, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
for id in [a, b] {
|
||||
s.execute("select.add", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
}
|
||||
|
||||
/// New art on a locked artboard stays selected and editable until the selection leaves it: a
|
||||
/// second Pen click goes on the path the first one started, and pasted art moves. Once another
|
||||
/// object is clicked, a click, a marquee, `select.set` and Select All pass over that art. Undo, in
|
||||
|
||||
@@ -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::<Vec<_>>());
|
||||
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]
|
||||
|
||||
@@ -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<Point> = 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<Point> = 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<Point> = 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<Point> = 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<Point> = 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<Point> = 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() {
|
||||
|
||||
@@ -125,6 +125,22 @@ fn file_names_are_uri_encoded_and_current_relative() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `localizedName` of a file and a folder is the name they show, decoded, as `displayName` is,
|
||||
/// not the encoded `name`.
|
||||
#[test]
|
||||
fn file_and_folder_give_their_localized_name() {
|
||||
let base = folder("localized");
|
||||
let log = logged(
|
||||
&base,
|
||||
"var f = new File('caf%C3%A9 x.txt'), d = new Folder('n%C3%A9w');\n\
|
||||
f.localizedName = 'other';\n\
|
||||
vc.log([f.localizedName === f.displayName, f.localizedName === f.name, d.localizedName === d.displayName,\n\
|
||||
d.localizedName === d.name, f.localizedName, 'localizedName' in Folder.prototype]);",
|
||||
);
|
||||
assert_eq!(log, json!([[true, false, true, false, "caf\u{e9} x.txt", true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_file_without_scope_cannot_probe_home() {
|
||||
let base = folder("home");
|
||||
@@ -637,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() {
|
||||
@@ -652,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::<Value>::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);
|
||||
@@ -1303,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() {
|
||||
|
||||
@@ -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<Option<String>> = 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<Option<String>> = 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<Option<String>> = 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<Option<String>> {
|
||||
doc(s).pattern(p).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect()
|
||||
};
|
||||
let kept: Vec<String> = 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<String> {
|
||||
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<String> = 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]
|
||||
|
||||
@@ -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; <https://community.adobe.com/t5/illustrator-discussions/handles-disappar-on-shape-with-direct-selection-tool/m-p/14848662>).
|
||||
/// 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<String>)> {
|
||||
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<Point>, 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<String>)> {
|
||||
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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"File.prototype.",
|
||||
"absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \
|
||||
exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= modified name openDlg parent path read \
|
||||
exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= localizedName modified name openDlg parent path read \
|
||||
readch readln readonly relativeURI resolve saveDlg seek tell toString type",
|
||||
),
|
||||
(
|
||||
@@ -70,7 +70,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Folder.prototype.",
|
||||
"absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \
|
||||
getRelativeURI modified name parent path relativeURI resolve selectDlg toString",
|
||||
getRelativeURI localizedName modified name parent path relativeURI resolve selectDlg toString",
|
||||
),
|
||||
];
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -314,6 +314,12 @@ fn display_name(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<V
|
||||
parsed(i, &this, "displayName", "display")
|
||||
}
|
||||
|
||||
/// `localizedName`: the same decoded name as `displayName`; VectorCraft does not look up a name the
|
||||
/// system shows in another language.
|
||||
fn localized_name(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
parsed(i, &this, "localizedName", "display")
|
||||
}
|
||||
|
||||
fn path(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
parsed(i, &this, "path", "path")
|
||||
}
|
||||
@@ -1029,6 +1035,7 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
accessor(i, proto, "relativeURI", relative_uri, None)?;
|
||||
accessor(i, proto, "name", name, None)?;
|
||||
accessor(i, proto, "displayName", display_name, None)?;
|
||||
accessor(i, proto, "localizedName", localized_name, None)?;
|
||||
accessor(i, proto, "path", path, None)?;
|
||||
accessor(i, proto, "parent", parent, None)?;
|
||||
accessor(i, proto, "exists", exists, None)?;
|
||||
|
||||
@@ -95,6 +95,14 @@ fn variables_functions_and_closures() {
|
||||
assert_eq!(num("(function(a, b, c) {}).length"), 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comma_adds_no_argument_or_parameter() {
|
||||
assert_eq!(num("function f(a, b,) { return arguments.length * 10 + f.length; } f(1,)"), 12.0);
|
||||
assert_eq!(num("function P(x,) { this.n = arguments.length; } new P(5,).n"), 1.0);
|
||||
assert_eq!(num("var f = new Function('a,', 'return arguments.length'); f(1, 2) * 10 + f.length"), 21.0);
|
||||
assert_eq!(num("Function('a', '', 'return a')(4)"), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_and_apply_set_this_and_arguments() {
|
||||
assert_eq!(num("function f(a, b) { return this.k + a + b; } f.call({k: 1}, 2, 3)"), 6.0);
|
||||
|
||||
@@ -1008,9 +1008,17 @@ impl<'s> Parser<'s> {
|
||||
let default = if self.es2015 && self.eat(Punct::Eq)? { Some(self.parse_assignment(false)?) } else { None };
|
||||
params.push(param);
|
||||
defaults.push(default);
|
||||
// A comma may follow the last parameter (ECMAScript 2017, section 14.1), except in
|
||||
// a setter, which takes one parameter and no comma (section 14.3).
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
if self.at(Punct::RParen) {
|
||||
if kind == FunctionKind::Setter {
|
||||
return Err(self.error_at_token(&self.tok, "a setter must have exactly one parameter"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let close = self.expect(Punct::RParen)?;
|
||||
@@ -1473,7 +1481,8 @@ impl<'s> Parser<'s> {
|
||||
if !self.at(Punct::RParen) {
|
||||
loop {
|
||||
args.push(self.parse_element()?);
|
||||
if !self.eat(Punct::Comma)? {
|
||||
// A comma may follow the last argument (ECMAScript 2017, section 12.3).
|
||||
if !self.eat(Punct::Comma)? || self.at(Punct::RParen) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +134,24 @@ fn accessors_take_the_right_number_of_parameters() {
|
||||
assert!(err("({set a(x, y) {}});").message.contains("setter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comma_may_end_arguments_and_parameters() {
|
||||
let p = ok("f(1,);");
|
||||
assert!(matches!(expr(&p, first_expr(&p)), Expr::Call { args, .. } if args.len() == 1));
|
||||
let p = ok("new F(1, 2,);");
|
||||
assert!(matches!(expr(&p, first_expr(&p)), Expr::New { args, .. } if args.len() == 2));
|
||||
let p = ok("function g(a, b,) {}");
|
||||
let Stmt::FunctionDecl(g) = stmt(&p, p.body[0]) else { panic!() };
|
||||
assert_eq!(p.ast.function(*g).unwrap().params.len(), 2);
|
||||
for src in ["(function (a,) {});", "({get a() {}, m: function (x,) {}});", "f(g(1,),);", "'use strict'; function h(a,) {}"] {
|
||||
ok(src);
|
||||
}
|
||||
for src in ["f(,);", "f(1,,);", "f(, 1);", "function g(,) {}", "function g(a,,) {}", "new F(,);"] {
|
||||
err(src);
|
||||
}
|
||||
assert!(err("({set a(v,) {}});").message.contains("setter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_names_may_repeat() {
|
||||
for src in ["({a: 1, a: 2});", "({a: 1, 'a': 2});", "({get a() {}, set a(v) {}});", "({a: 1, get a() {}});", "({get a() {}, get a() {}});"] {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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<usize> = 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, InscribedError> {
|
||||
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<Inscribed, InscribedError> {
|
||||
// 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::<usize>() > 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<Inscribed, InscribedError> {
|
||||
// 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<Vec<(Point, Point)>, InscribedError> {
|
||||
let mut out = vec![];
|
||||
let (mut start, mut last) = (None, None);
|
||||
let close = |out: &mut Vec<(Point, Point)>, start: Option<Point>, last: Option<Point>| {
|
||||
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<Ordering> {
|
||||
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<Point, InscribedError> {
|
||||
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<Point, InscribedError> {
|
||||
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<Cell>, 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)
|
||||
}
|
||||
@@ -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<Item = Point> {
|
||||
(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));
|
||||
}
|
||||