mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 11:51:05 +01:00
Merge main into feat/color-wheel-opacity
This commit is contained in:
commit
ac75f6ddc5
189 files changed
+12858
-1526
No files matched your search
@@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -146,6 +147,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 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.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
|
||||
@@ -491,6 +491,10 @@ pub struct GraphSpec {
|
||||
pub first_column_in_front: bool,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub filled_lines: bool,
|
||||
/// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws
|
||||
/// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_width: Option<f64>,
|
||||
/// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the
|
||||
/// legend in rows above the plot instead of a column on its right).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -565,6 +569,21 @@ fn is_zero(n: &usize) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and
|
||||
/// greatest widths a graph takes, in points.
|
||||
pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0;
|
||||
pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01;
|
||||
pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0;
|
||||
|
||||
impl GraphSpec {
|
||||
/// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A
|
||||
/// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the
|
||||
/// default.
|
||||
pub fn filled_line_width(&self) -> f64 {
|
||||
self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH)
|
||||
}
|
||||
}
|
||||
|
||||
/// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then.
|
||||
fn edge_to_edge_before_the_option() -> bool {
|
||||
true
|
||||
@@ -704,6 +723,7 @@ impl Default for GraphSpec {
|
||||
first_row_in_front: false,
|
||||
first_column_in_front: false,
|
||||
filled_lines: false,
|
||||
line_width: None,
|
||||
drop_shadow: false,
|
||||
legend_across_top: false,
|
||||
pie_legend_in_wedges: false,
|
||||
|
||||
@@ -96,8 +96,8 @@ pub use compound_shape::ShapeMode;
|
||||
pub use corners::LiveCorners;
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES,
|
||||
PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
|
||||
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH,
|
||||
MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
|
||||
};
|
||||
pub use hit::{Hit, HitKind};
|
||||
pub use links::{LinkInfo, PlacementOptions};
|
||||
|
||||
@@ -50,10 +50,10 @@ pub struct Selection {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
|
||||
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
|
||||
/// move the other selected points relative to it, and it stays in place. Never set with `key`
|
||||
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
|
||||
/// fewer than two points are selected.
|
||||
/// designated by clicking an already-selected anchor point without modifiers (path, anchor in
|
||||
/// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and
|
||||
/// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the
|
||||
/// point is no longer a selected anchor, or fewer than two points are selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_anchor: Option<(NodeId, AnchorRef)>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
@@ -311,7 +311,7 @@ impl Selection {
|
||||
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
|
||||
self.objects.contains(&id)
|
||||
&& !self.segments.contains_key(&id)
|
||||
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
|
||||
&& (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id))
|
||||
&& found
|
||||
.get(&id)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
|
||||
@@ -182,28 +182,28 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
@@ -217,7 +217,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -86,9 +86,9 @@ pub use raster::{
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
|
||||
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
|
||||
outline_text, paint_type_piece, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
|
||||
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
|
||||
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
|
||||
+237
-31
@@ -107,15 +107,66 @@ fn reaches_appearance(e: &Effect) -> bool {
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
|
||||
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
|
||||
/// baked and expanded through that art ([`reshape`]).
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`],
|
||||
/// [`has_copied_row_raster`]), or whose live-effect plug-ins paint what they return
|
||||
/// ([`has_painted_effects`])? It is drawn, baked and expanded through that art ([`reshape`]).
|
||||
pub fn has_transform_art(n: &Node) -> bool {
|
||||
has_gradient_copies(n)
|
||||
|| has_layered_copies(n)
|
||||
|| has_transform_options(n)
|
||||
|| has_painted_effects(n)
|
||||
|| (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some())
|
||||
|| has_copied_row_raster(n)
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are
|
||||
/// carried by copies: one whose own effects list a Transform effect that makes copies after a
|
||||
/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes
|
||||
/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or
|
||||
/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`],
|
||||
/// [`follow_copies`]).
|
||||
pub fn has_copied_row_raster(n: &Node) -> bool {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
|
||||
return false;
|
||||
}
|
||||
// Checked first: this runs for every object drawn.
|
||||
if !n.appearance.items.iter().any(follows_row_raster) {
|
||||
return false;
|
||||
}
|
||||
n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n)
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry a visible raster effect that follows a Transform effect
|
||||
/// ([`crate::raster::follows`])?
|
||||
fn follows_row_raster(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
}
|
||||
|
||||
/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries
|
||||
/// the raster effects listed before it: the index of the first visible Transform effect that makes
|
||||
/// copies (an earlier one that makes copies included) for which a visible raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible
|
||||
/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it
|
||||
/// that makes copies or moves at random holds those raster effects back
|
||||
/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it
|
||||
/// and before a later Transform effect that makes copies or moves at random, which would apply to
|
||||
/// the art that raster effect paints.
|
||||
fn copied_row_raster_at(fx: &[Effect]) -> Option<usize> {
|
||||
let copying =
|
||||
|e: &Effect| e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0;
|
||||
// Is a visible raster effect in `rest` listed before its last Transform effect that holds back?
|
||||
let raster_held = |rest: &[Effect]| {
|
||||
rest.iter().rposition(crate::raster::holds_back).is_some_and(|k| rest[..k].iter().any(|e| e.visible && crate::is_raster(&e.id)))
|
||||
};
|
||||
(0..fx.len()).find(|&t| {
|
||||
let before = &fx[..t];
|
||||
copying(&fx[t])
|
||||
&& !raster_held(&fx[t + 1..])
|
||||
&& crate::raster::held_back(before) == 0
|
||||
&& before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so
|
||||
@@ -900,6 +951,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
|
||||
as_art(doc, n, symbol_art)
|
||||
}
|
||||
|
||||
/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the
|
||||
/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`]
|
||||
/// gives. `None` for other kinds of objects and for an instance without `symbol_art`.
|
||||
pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
return None;
|
||||
}
|
||||
as_art(doc, n, symbol_art)
|
||||
}
|
||||
|
||||
/// [`reshape`] without its checks (no geometry effects: just the art).
|
||||
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
@@ -989,7 +1050,7 @@ fn as_art_opts(
|
||||
}
|
||||
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
|
||||
};
|
||||
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
|
||||
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), paint_doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
@@ -1058,7 +1119,8 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
}
|
||||
None => {
|
||||
let mut art = one_piece(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
|
||||
let rows = has_copied_row_raster(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
@@ -1099,7 +1161,7 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc);
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
@@ -1230,19 +1292,19 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
|
||||
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
|
||||
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
|
||||
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc);
|
||||
}
|
||||
|
||||
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
|
||||
/// strokes) follow the effects ([`crate::Carry`]).
|
||||
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc)
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, &[], budget, false, doc)
|
||||
reshape_leaves_apart(art, fx, &[], budget, (false, false), doc)
|
||||
}
|
||||
|
||||
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
|
||||
@@ -1263,7 +1325,10 @@ fn hoist_copies(art: &mut Node) {
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
|
||||
/// `apart`, a Transform effect's copies of each path are objects
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. With `rows`,
|
||||
/// so are the copies of a path with a fill or stroke whose raster effects follow a Transform effect
|
||||
/// ([`crate::raster::follows`]), and each copy's fills and strokes carry those raster effects moved,
|
||||
/// turned, reflected and scaled with it ([`follow_copies`]). A live-effect
|
||||
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
|
||||
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
|
||||
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
|
||||
@@ -1274,7 +1339,14 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
|
||||
fn reshape_leaves_apart(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
(apart, rows): (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
return whole;
|
||||
@@ -1311,7 +1383,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes, held };
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
@@ -1355,6 +1427,7 @@ struct Step<'a> {
|
||||
seed: u64,
|
||||
effect: Option<usize>,
|
||||
apart: bool,
|
||||
rows: bool,
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
held: bool,
|
||||
@@ -1519,8 +1592,12 @@ impl Step<'_> {
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
|
||||
// Each copy of a path with a linked mask carries the mask, moved with it.
|
||||
// With `rows`, each copy carries the raster effects of its fills and strokes,
|
||||
// following that copy's map.
|
||||
let rows = self.rows && copies > 0 && leaf.appearance.items.iter().any(follows_row_raster);
|
||||
let separate = copies > 0
|
||||
&& (self.apart
|
||||
|| rows
|
||||
|| leaf.appearance.has_unplaced_gradient()
|
||||
|| leaf.appearance.has_placed_gradient()
|
||||
|| paints_copies_apart(&leaf.appearance, rule)
|
||||
@@ -1528,9 +1605,12 @@ impl Step<'_> {
|
||||
// The copies of a path replace it by a group of them, the path included.
|
||||
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
|
||||
if options.reach_appearance() {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some() || rows, None);
|
||||
*used = used.minus(before).plus(made);
|
||||
took |= moved;
|
||||
if moved && rows {
|
||||
follow_copies(leaf, map, None);
|
||||
}
|
||||
if moved {
|
||||
// With Transform Objects off the path stays, and its mask takes the
|
||||
// effect's stroke and pattern changes as its own art.
|
||||
@@ -1546,6 +1626,9 @@ impl Step<'_> {
|
||||
if separate {
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
|
||||
if rows {
|
||||
follow_copies(leaf, m, None);
|
||||
}
|
||||
*used = used.minus(before).plus(made);
|
||||
took = true;
|
||||
moved_ids.insert(leaf.id);
|
||||
@@ -1937,7 +2020,7 @@ fn transform_leaf(
|
||||
kept: Kept,
|
||||
) -> (Budget, bool) {
|
||||
let mut scaling = copy_scaling(options);
|
||||
if follows && copies == 0 {
|
||||
if follows {
|
||||
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
|
||||
}
|
||||
if !options.objects {
|
||||
@@ -2253,7 +2336,8 @@ fn paint_piece(
|
||||
|
||||
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
|
||||
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
|
||||
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`item_transform_options`]) or makes copies that carry the raster effects before it
|
||||
/// ([`copied_row_raster_at`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
|
||||
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
|
||||
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
|
||||
@@ -2270,9 +2354,20 @@ fn makes_piece(e: &Effect) -> bool {
|
||||
reaches_appearance(e) || painted_plugin(e).is_some()
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that [`makes_piece`]?
|
||||
/// Where the fill's or stroke's own effects `fx` make its piece of a path an object of its own: the
|
||||
/// index of the first effect that [`makes_piece`], or of the Transform effect whose copies carry the
|
||||
/// raster effects before it ([`copied_row_raster_at`]), whichever is listed first.
|
||||
fn piece_at(fx: &[Effect]) -> Option<usize> {
|
||||
let copied = copied_row_raster_at(fx);
|
||||
match fx.iter().position(makes_piece) {
|
||||
Some(at) => Some(copied.map_or(at, |t| t.min(at))),
|
||||
None => copied,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that makes its piece an object of its own ([`piece_at`])?
|
||||
fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(makes_piece)
|
||||
crate::paints(item) && piece_at(item.effects()).is_some()
|
||||
}
|
||||
|
||||
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
|
||||
@@ -2282,12 +2377,17 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
|
||||
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
|
||||
/// pattern follow the map, and the raster effects before it that follow it take their followed
|
||||
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
|
||||
/// values ([`follow_piece`]), on each copy the values that copy's map gives them
|
||||
/// ([`follow_copies`]). The effects after it keep their values and apply to what it made
|
||||
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
|
||||
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
|
||||
/// stroke's own effects. The geometry effects after the Transform effect then
|
||||
/// stroke's own effects. A fill or stroke whose first such Transform effect makes copies that carry
|
||||
/// the raster effects before it ([`copied_row_raster_at`]) becomes a path of its own the same way,
|
||||
/// with neither option. The geometry effects after the Transform effect then
|
||||
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
|
||||
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
|
||||
/// effects stay on each of them, except that without either option the raster effects after a
|
||||
/// Transform effect that makes copies paint once around all of them ([`lift_later_raster`]). The
|
||||
/// other fills and strokes stay together on paths of the leaf's
|
||||
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
|
||||
/// what it has spent.
|
||||
///
|
||||
@@ -2333,7 +2433,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
|
||||
for (i, item) in original.appearance.items.iter().enumerate() {
|
||||
let fx = item.effects();
|
||||
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
|
||||
let Some(at) = piece_at(fx).filter(|_| crate::paints(item)) else {
|
||||
plain.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
@@ -2411,13 +2511,24 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
let after = kept_before.len();
|
||||
let keep = |k: usize| k >= after || !options.objects;
|
||||
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
|
||||
*used = used.plus(made);
|
||||
let from = crate::raster::held_back(before);
|
||||
if moved && !held_later {
|
||||
// Each copy carries the raster effects before the Transform effect, following that copy's
|
||||
// map, unless a Transform effect before or after it holds them back.
|
||||
let copied = copies > 0 && !held_later && from == 0;
|
||||
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, copied, Some((&rest, &keep)));
|
||||
*used = used.plus(made);
|
||||
if moved && copied {
|
||||
follow_copies(&mut p, map, Some(0..after));
|
||||
} else if moved && !held_later {
|
||||
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
|
||||
}
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
|
||||
// Without Transform Patterns and Scale Strokes & Effects, the raster effects after the
|
||||
// Transform effect paint once around all the copies, as they paint around the one path of
|
||||
// every copy.
|
||||
if copies > 0 && !options.reach_appearance() {
|
||||
lift_later_raster(&mut p, after);
|
||||
}
|
||||
pieces.push(Arc::new(p));
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
@@ -2468,6 +2579,7 @@ fn transform_piece(
|
||||
count = count.max(item.effects().len());
|
||||
}
|
||||
});
|
||||
let outer = held;
|
||||
// The effects before a Transform effect among the piece's effects that makes copies or moves at
|
||||
// random are held back from the Transform effects before it too.
|
||||
let mut held = held;
|
||||
@@ -2488,7 +2600,7 @@ fn transform_piece(
|
||||
let from = held.min(j);
|
||||
let mut holds = false;
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
|
||||
let at = PieceStage { j, from, seed, bounds, doc, stage };
|
||||
let at = PieceStage { j, from, outer, seed, bounds, doc, stage };
|
||||
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
|
||||
// counts each path it became so, or `None` when it stays as it was.
|
||||
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
|
||||
@@ -2709,12 +2821,14 @@ thread_local! {
|
||||
|
||||
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
|
||||
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
|
||||
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
|
||||
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
|
||||
/// plug-in is listed by.
|
||||
/// effect; `outer`, how many of the piece's effects a Transform effect before them holds back; the
|
||||
/// object's `seed`; the reference box `bounds` of all the piece's paths; the document that painted
|
||||
/// pieces' swatches and patterns must be in; and the `stage` a deferred live-effect plug-in is
|
||||
/// listed by.
|
||||
struct PieceStage<'a> {
|
||||
j: usize,
|
||||
from: usize,
|
||||
outer: usize,
|
||||
seed: u64,
|
||||
bounds: Rect,
|
||||
doc: Option<&'a Document>,
|
||||
@@ -2757,15 +2871,30 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage));
|
||||
}
|
||||
if reaches_appearance(e) {
|
||||
let copied = copies_carry(item.effects(), e, at);
|
||||
if reaches_appearance(e) || copied {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed);
|
||||
let j = at.j;
|
||||
let keep = |k: usize| k > j || (k < j && !options.objects);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
|
||||
if moved {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, copied, Some((item.effects(), &keep)));
|
||||
if moved && copied {
|
||||
// Each copy's raster effects before the Transform effect follow that copy's map. The
|
||||
// Transform effects before it have already moved them, so each run between two of
|
||||
// them follows on its own.
|
||||
let fx = item.effects();
|
||||
let mut start = 0;
|
||||
for k in 0..=j {
|
||||
if k == j || fx.get(k).is_some_and(|f| f.id == "distort.transform") {
|
||||
if start < k {
|
||||
follow_copies(leaf, map, Some(start..k));
|
||||
}
|
||||
start = k + 1;
|
||||
}
|
||||
}
|
||||
} else if moved {
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
}
|
||||
return Some(made);
|
||||
@@ -2790,6 +2919,37 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Does Transform effect `e`, at stage `at` of [`transform_piece`] of a fill or stroke whose effects
|
||||
/// are `fx`, make copies that each carry the raster effects listed before it, following that copy's
|
||||
/// map ([`follow_copies`]), as the copies of the piece's first Transform effect do
|
||||
/// ([`transform_item_leaf`])? It does when it makes copies with Transform Objects on, a visible
|
||||
/// raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed before it,
|
||||
/// and no Transform effect that makes copies or moves at random holds those raster effects back:
|
||||
/// none before the piece's effects, none listed before it after such a raster effect, and none
|
||||
/// after it. Without Transform Patterns and Scale Strokes & Effects, every other visible effect
|
||||
/// before it must also be a geometry effect or such a raster effect, and no visible raster effect
|
||||
/// may be listed after it, as for [`copied_row_raster_at`].
|
||||
fn copies_carry(fx: &[Effect], e: &Effect, at: &PieceStage) -> bool {
|
||||
if !e.visible || e.id != "distort.transform" || at.outer > 0 {
|
||||
return false;
|
||||
}
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
if !crate::distort::TransformOptions::of(¶ms).objects || crate::distort::transform_map(Rect::ZERO, ¶ms, 0).1 == 0 {
|
||||
return false;
|
||||
}
|
||||
let before = fx.get(..at.j).unwrap_or_default();
|
||||
let after = fx.get(at.j + 1..).unwrap_or_default();
|
||||
if crate::raster::held_back(before) > 0
|
||||
|| !before.iter().any(|f| f.visible && crate::raster::follows(&f.id))
|
||||
|| after.iter().any(crate::raster::holds_back)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
reaches_appearance(e)
|
||||
|| (before.iter().all(|f| !f.visible || is_geometry(&f.id) || crate::raster::follows(&f.id))
|
||||
&& !after.iter().any(|f| f.visible && crate::is_raster(&f.id)))
|
||||
}
|
||||
|
||||
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
|
||||
fn same_path(a: &Node, b: &Node) -> bool {
|
||||
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
@@ -2862,6 +3022,52 @@ fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the raster effects that follow a Transform effect ([`crate::raster::follows`]) on the fills
|
||||
/// and strokes of each copy [`copy_leaf`] made of `leaf` with map `m` follow that copy's map: the
|
||||
/// copy `k` places below the original takes the linear part of `m` `k` times
|
||||
/// ([`crate::raster::follow_contents`]), and the original, on top, keeps its effects. `range`, when
|
||||
/// given, is which of each fill's or stroke's effects follow; the others keep their values.
|
||||
fn follow_copies(leaf: &mut Node, m: Affine, range: Option<std::ops::Range<usize>>) {
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
let Some(children) = leaf.children_mut() else { return };
|
||||
let mut a = Affine::IDENTITY;
|
||||
for c in children.iter_mut().rev().skip(1) {
|
||||
a *= step;
|
||||
for item in &mut Arc::make_mut(c).appearance.items {
|
||||
let fx = item.effects_mut();
|
||||
let fx = match &range {
|
||||
Some(r) => fx.get_mut(r.clone()).unwrap_or_default(),
|
||||
None => fx.as_mut_slice(),
|
||||
};
|
||||
crate::raster::follow_contents(fx, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the raster effects from index `after` on of the fills and strokes of the paths under `p`,
|
||||
/// a group of copies of one fill or stroke with the same effects, onto `p` itself, so they paint
|
||||
/// once around all of the copies. The other effects stay where they are.
|
||||
fn lift_later_raster(p: &mut Node, after: usize) {
|
||||
if p.children().is_none() {
|
||||
return;
|
||||
}
|
||||
let mut lifted: Option<Vec<Effect>> = None;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
for item in &mut l.appearance.items {
|
||||
let fx = item.effects_mut();
|
||||
if fx.len() <= after {
|
||||
continue;
|
||||
}
|
||||
let (raster, other): (Vec<Effect>, Vec<Effect>) = fx.split_off(after).into_iter().partition(|e| crate::is_raster(&e.id));
|
||||
fx.extend(other);
|
||||
lifted.get_or_insert(raster);
|
||||
}
|
||||
});
|
||||
if let Some(raster) = lifted {
|
||||
p.appearance.effects.extend(raster);
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
|
||||
/// order. A group inside one of them is part of it.
|
||||
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
@@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
shade: flag(p, "shade", true),
|
||||
smooth_shading: true,
|
||||
cap_ends: flag(p, "cap", true),
|
||||
fill_rule: FillRule::NonZero,
|
||||
curve_samples: None,
|
||||
map_surface: false,
|
||||
}
|
||||
@@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
|
||||
return Ok(());
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ()))
|
||||
paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ()))
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
|
||||
@@ -418,7 +419,7 @@ fn cast_surface(
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
|
||||
caster.revolve(path, options.fill_rule, b, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -449,7 +450,7 @@ fn group_shadow(
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?;
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
|
||||
@@ -703,13 +704,16 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
|
||||
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
|
||||
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
|
||||
/// [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
/// A surface of one object about the bounds of `path`, filled with `rule`, built with options
|
||||
/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast
|
||||
/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of
|
||||
/// `doc`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn object_surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
fx: &Effect,
|
||||
item: &AppearanceItem,
|
||||
expand: bool,
|
||||
@@ -718,10 +722,16 @@ fn object_surface(
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast)
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
|
||||
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
|
||||
}
|
||||
|
||||
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
|
||||
/// leave open the holes `rule` leaves in the profile.
|
||||
fn rule_options(fx: &Effect, rule: FillRule) -> Revolve {
|
||||
Revolve { fill_rule: rule, ..fx_options(fx) }
|
||||
}
|
||||
|
||||
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
|
||||
/// that color: across the face with its smooth shading, under colored lights (`colored`) with
|
||||
/// their color.
|
||||
@@ -840,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
let mut out = vec![];
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, fx, options)?);
|
||||
out.extend(faces(&s.path, b, fx, Revolve { fill_rule: s.rule, ..options })?);
|
||||
}
|
||||
// In wireframe mode the canvas draws no shadow.
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
|
||||
return Ok((out, shadow));
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let (path, rule) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
|
||||
@@ -854,8 +864,8 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&path, b, fx, fx_options(fx))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
|
||||
let surface = faces(&path, b, fx, rule_options(fx, rule))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None)? };
|
||||
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -866,7 +876,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&p, b, fx, fx_options(fx))?;
|
||||
let surface = faces(&p, b, fx, rule_options(fx, rule))?;
|
||||
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
|
||||
}
|
||||
}
|
||||
@@ -884,13 +894,14 @@ fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
}
|
||||
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
|
||||
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
|
||||
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with
|
||||
/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces
|
||||
/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge
|
||||
/// limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = (&'a PathData, FillRule)>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
let mut faces = vec![];
|
||||
for path in paths {
|
||||
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
|
||||
for (path, rule) in paths {
|
||||
faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path));
|
||||
}
|
||||
crate::solids::wireframe::wire_art(id, &faces)
|
||||
}
|
||||
@@ -940,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of the faces, with no shadow.
|
||||
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
|
||||
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
|
||||
} else {
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
@@ -970,18 +981,19 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
|
||||
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
|
||||
Arc::make_mut(&mut art).appearance.effects =
|
||||
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
children.push(art);
|
||||
continue;
|
||||
}
|
||||
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()?
|
||||
{
|
||||
shadow.appearance.effects = art.appearance.effects.clone();
|
||||
// The shadow keeps its own blur (the light's Softness) below the later effects.
|
||||
shadow.appearance.effects.extend(art.appearance.effects.iter().cloned());
|
||||
shadows.push(Arc::new(shadow));
|
||||
}
|
||||
children.push(Arc::new(art));
|
||||
@@ -1127,7 +1139,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of every member's faces, with no shadow.
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
|
||||
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
|
||||
@@ -1157,6 +1169,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let options = Revolve { fill_rule: s.rule, ..options };
|
||||
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
@@ -2088,7 +2101,7 @@ mod tests {
|
||||
let mut fx = crate::new_effect(id, &json!({})).unwrap();
|
||||
fx.params = params.clone();
|
||||
let n = profile_node();
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let mut half = n.clone();
|
||||
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
|
||||
@@ -2096,9 +2109,9 @@ mod tests {
|
||||
}
|
||||
for n in [n, half] {
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap();
|
||||
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
@@ -2164,11 +2177,11 @@ mod tests {
|
||||
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
|
||||
f.opacity = bad;
|
||||
}
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
|
||||
let shadows = group_shadows(&group(bad));
|
||||
|
||||
@@ -2177,7 +2177,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Arc::make_mut(&mut art).appearance.effects = later.clone();
|
||||
art
|
||||
};
|
||||
shadows.extend(shadow.into_iter().map(with_later));
|
||||
// A shadow keeps its own blur (the light's Softness) below the later effects.
|
||||
shadows.extend(shadow.into_iter().map(|mut art| {
|
||||
Arc::make_mut(&mut art).appearance.effects.extend(later.iter().cloned());
|
||||
art
|
||||
}));
|
||||
children.extend(surfaces.into_iter().map(with_later));
|
||||
} else {
|
||||
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the
|
||||
//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it
|
||||
//! draws behind the solids.
|
||||
//! draws behind the solids, blurred by the first light's Softness.
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId};
|
||||
use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition};
|
||||
|
||||
use super::Scope;
|
||||
@@ -15,15 +15,21 @@ use crate::util::{flag, num, text};
|
||||
/// The shadow's paint: black at this opacity. VectorCraft's own values.
|
||||
const SHADOW_OPACITY: f32 = 0.5;
|
||||
|
||||
/// Blur radii below this, in points, leave the shadow hard-edged.
|
||||
const MIN_BLUR: f64 = 0.01;
|
||||
|
||||
/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing
|
||||
/// (Shading is off or its intensity is 0), so that no shadow is built.
|
||||
/// (Shading is off or its intensity is 0), so that no shadow is built. Its softness is the first
|
||||
/// light's.
|
||||
pub(crate) fn options(p: &Value) -> Option<Shadow> {
|
||||
let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0));
|
||||
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
|
||||
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
|
||||
let lit = flag(p, "shade", true) && intensity > 0.0;
|
||||
(lit && flag(p, "shadow", false)).then(|| Shadow {
|
||||
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
|
||||
distance: num(p, "shadowDistance", 0.0) / 100.0,
|
||||
bounds: num(p, "shadowBounds", 100.0) / 100.0,
|
||||
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,8 +70,9 @@ pub(crate) fn casts(opacity: f32) -> bool {
|
||||
}
|
||||
|
||||
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
|
||||
/// `None` when it casts nothing.
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule, and
|
||||
/// with the light's Softness a Gaussian Blur of the plane's radius ([`ShadowPlane::blur`]), which
|
||||
/// is drawn, measured, exported and expanded as that effect is; `None` when it casts nothing.
|
||||
pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> {
|
||||
let all = 0..caster.len();
|
||||
let all = std::slice::from_ref(&all);
|
||||
@@ -78,7 +85,9 @@ fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::BLACK));
|
||||
fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0);
|
||||
fill.blend = ink.blend;
|
||||
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
let blur = plane.blur();
|
||||
let effects = if blur >= MIN_BLUR { vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": blur}), visible: true }] } else { vec![] };
|
||||
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], effects, ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies).
|
||||
|
||||
@@ -87,6 +87,40 @@ fn the_shadow_moves_with_its_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The radius of the Gaussian Blur on shadow `n`; `None` without one.
|
||||
fn shadow_blur(n: &Node) -> Option<f64> {
|
||||
match n.appearance.effects.as_slice() {
|
||||
[] => None,
|
||||
[e] if e.id == "blur.gaussian" && e.visible => e.params["radius"].as_f64(),
|
||||
other => panic!("unexpected effects on the shadow: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first light's Softness blurs the shadow, more with Softness and with Distance from Object;
|
||||
/// at 0 % it stays the hard-edged path. A list of lights takes the first light's Softness.
|
||||
#[test]
|
||||
fn the_first_lights_softness_blurs_the_shadow() {
|
||||
for id in CASTING {
|
||||
let blur = |params: Value| {
|
||||
let mut n = square_node(1, 0.0);
|
||||
n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap());
|
||||
let lit = art(&n, id).unwrap();
|
||||
let shadow = &lit.children().unwrap()[0];
|
||||
assert!(is_shadow(shadow), "{id} {params}");
|
||||
shadow_blur(shadow)
|
||||
};
|
||||
assert_eq!(blur(json!({"shadow": true})), None, "{id}: hard at 0 %");
|
||||
let soft = blur(json!({"shadow": true, "lightSoftness": 50})).unwrap_or_else(|| panic!("{id}"));
|
||||
let softer = blur(json!({"shadow": true, "lightSoftness": 100})).unwrap();
|
||||
let far = blur(json!({"shadow": true, "lightSoftness": 100, "shadowDistance": 100})).unwrap();
|
||||
assert!(soft > 0.0 && softer > soft && far > softer, "{id}: {soft} {softer} {far}");
|
||||
let first = json!({"shadow": true, "lightSoftness": 0, "lights": [{"softness": 100}, {"softness": 0}]});
|
||||
assert_eq!(blur(first), Some(softer), "{id}: the first light's");
|
||||
let second = json!({"shadow": true, "lightSoftness": 100, "lights": [{"softness": 0}, {"softness": 100}]});
|
||||
assert_eq!(blur(second), None, "{id}: only the first light casts");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() {
|
||||
for id in CASTING {
|
||||
@@ -203,6 +237,26 @@ fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's own 3D effect blurs its shadow by the light's Softness too, and the effects after it
|
||||
/// in the fill's list follow the blur.
|
||||
#[test]
|
||||
fn a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects() {
|
||||
for id in CASTING {
|
||||
for later in [None, Some(crate::new_effect("distort.roughen", &json!({})).unwrap())] {
|
||||
let mut n = square_node(1, 0.0);
|
||||
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
fill.effects_mut().push(crate::new_effect(id, &json!({"shadow": true, "lightSoftness": 100})).unwrap());
|
||||
fill.effects_mut().extend(later.clone());
|
||||
let lit = art(&n, id).unwrap_or_else(|| panic!("{id}"));
|
||||
let shadow = &lit.children().unwrap()[0];
|
||||
assert!(is_shadow(shadow), "{id}");
|
||||
let ids: Vec<&str> = shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
let want: Vec<&str> = std::iter::once("blur.gaussian").chain(later.as_ref().map(|e| e.id.as_str())).collect();
|
||||
assert_eq!(ids, want, "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_keeps_the_shadow_as_a_path() {
|
||||
for id in CASTING {
|
||||
|
||||
@@ -816,8 +816,8 @@ fn a_groups_transform_applies_after_its_members_own() {
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
|
||||
/// makes copies leaves them.
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. For one that
|
||||
/// makes copies, see [`each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`].
|
||||
#[test]
|
||||
fn an_objects_transform_moves_its_fills_shadows() {
|
||||
let cases = [
|
||||
@@ -825,7 +825,6 @@ fn an_objects_transform_moves_its_fills_shadows() {
|
||||
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
|
||||
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
|
||||
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
|
||||
@@ -1217,6 +1216,169 @@ fn copies_past_the_budget_each_keep_their_shadow() {
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
|
||||
/// `n` with only its fill (or only a 4 pt blue stroke, with `stroke`), whose own effects are
|
||||
/// `effects`.
|
||||
fn one_row(mut n: Node, stroke: bool, effects: Vec<Effect>) -> Node {
|
||||
let mut item = if stroke {
|
||||
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))
|
||||
} else {
|
||||
n.appearance.items.remove(0)
|
||||
};
|
||||
*item.effects_mut() = effects;
|
||||
n.appearance.items = vec![item];
|
||||
n
|
||||
}
|
||||
|
||||
/// A case of [`copying_cases`]: the params, each copy's offset and each copy's blur.
|
||||
type CopyingCase = (Value, Vec<(f64, f64)>, Vec<f64>);
|
||||
|
||||
/// The cases of a Transform effect that makes copies with a drop shadow (10, 0) and a blur of 4
|
||||
/// before it: the params, each copy's offset and each copy's blur, the last copy first.
|
||||
fn copying_cases() -> Vec<CopyingCase> {
|
||||
vec![
|
||||
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
|
||||
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
|
||||
// Scale Strokes & Effects does not scale the shadow a second time, nor leave it unturned.
|
||||
(
|
||||
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "strokes": true}),
|
||||
vec![(0.0, -20.0), (10.0, 0.0)],
|
||||
vec![8.0, 4.0],
|
||||
),
|
||||
(
|
||||
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "patterns": true}),
|
||||
vec![(0.0, -20.0), (10.0, 0.0)],
|
||||
vec![8.0, 4.0],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Check that `n` is drawn, expanded and baked as `want.len()` paths, each with one shadow at the
|
||||
/// offset and blur `want` and `blurs` give it, the last copy first.
|
||||
fn assert_copies_carry(n: &Node, want: &[(f64, f64)], blurs: &[f64], what: &str) {
|
||||
assert!(crate::has_transform_art(n), "{what}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, n, None).unwrap()), ("expanded", expand_outlined(None, n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
assert_eq!(paths_in(&art), want.len(), "{what}: {how} {art:?}");
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, want), "{what}: {how} {drawn:?}");
|
||||
let b = shadow_blurs_in(&art);
|
||||
assert!(b.len() == blurs.len() && b.iter().zip(blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{what}: {how} blurs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's or stroke's own Transform effect that makes copies gives each copy the shadow listed
|
||||
/// before it in that fill's or stroke's effects, moved, turned, reflected and scaled with that copy,
|
||||
/// the last copy lowest: drawn, expanded and baked. The original keeps the shadow as it is.
|
||||
#[test]
|
||||
fn each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it() {
|
||||
for stroke in [false, true] {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
let n = one_row(square(95, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
// A Transform effect that makes copies before the shadow: its copies make one piece, which
|
||||
// the Transform effect after the shadow copies, each copy with its own shadow.
|
||||
let effects =
|
||||
vec![transform(json!({"moveV": 100, "copies": 1})), shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90, "moveH": 200, "copies": 1}))];
|
||||
let n = one_row(square(95, vec![]), stroke, effects);
|
||||
assert!(crate::has_transform_art(&n), "stroke {stroke}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, &[(0.0, -10.0), (10.0, 0.0)]), "stroke {stroke}: two copying Transform effects, {how} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that makes copies, listed after a fill's or stroke's first Transform effect
|
||||
/// with Transform Patterns on, gives each copy the shadow listed before it, as the first one's
|
||||
/// copies do, with or without options of its own: drawn, expanded and baked.
|
||||
#[test]
|
||||
fn each_copy_of_a_later_copying_transform_carries_the_shadow_before_it() {
|
||||
for stroke in [false, true] {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
let effects = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 4.0), transform(params.clone())];
|
||||
let n = one_row(square(102, vec![]), stroke, effects);
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's or stroke's shadow under its object's Transform effect that makes copies is carried by
|
||||
/// each copy, moved, turned, reflected and scaled with it: for a single fill, a single stroke, and
|
||||
/// a fill and a stroke that paint each copy below the one before. Drawn, expanded and baked.
|
||||
#[test]
|
||||
fn each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow() {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
for stroke in [false, true] {
|
||||
let mut n = one_row(square(96, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0)]);
|
||||
n.appearance.effects = vec![transform(params.clone())];
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
// Both a fill and a stroke: only the fill has the shadow.
|
||||
let mut n = square(97, vec![transform(params.clone())]);
|
||||
if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
|
||||
s.paint = Paint::solid(Color::BLACK);
|
||||
s.width = 2.0;
|
||||
}
|
||||
*n.appearance.items[0].effects_mut() = vec![shadow(10.0, 0.0, 4.0)];
|
||||
assert!(crate::has_transform_art(&n), "{params}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, &want), "layered {params}: {how} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shadow listed after a fill's own Transform effect that makes copies paints once around all of
|
||||
/// them, and one listed before it on each copy. A Transform effect that makes no copies, or has
|
||||
/// Transform Objects off, draws the fill as before, without art.
|
||||
#[test]
|
||||
fn a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies() {
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
|
||||
let n = one_row(square(98, vec![]), false, effects);
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{how}: {:?}", shadows_in(&art));
|
||||
assert_eq!(paths_in(&art), 2, "{how}");
|
||||
}
|
||||
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
|
||||
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
|
||||
assert!(!crate::has_transform_art(&n), "{params}");
|
||||
assert!(!crate::has_copied_row_raster(&n), "{params}");
|
||||
}
|
||||
// A shadow between two Transform effects that make copies paints on what the second one
|
||||
// copies, so the fill is drawn as before, without art.
|
||||
let copies = transform(json!({"rotate": 90, "copies": 1}));
|
||||
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), copies.clone(), shadow(0.0, 5.0, 0.0), copies]);
|
||||
assert!(!crate::has_copied_row_raster(&n));
|
||||
assert!(!crate::has_transform_art(&n));
|
||||
}
|
||||
|
||||
/// Copies of a fill's own Transform effect that stop at the effect budget each keep their shadow,
|
||||
/// and so do those of an object's Transform effect for its fill's shadow.
|
||||
#[test]
|
||||
fn row_copies_past_the_budget_each_keep_their_shadow() {
|
||||
let copies = transform(json!({"moveV": 50, "copies": 1000}));
|
||||
let own = one_row(path_node(100, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0), copies.clone()]);
|
||||
let mut owner = one_row(path_node(101, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0)]);
|
||||
owner.appearance.effects = vec![copies];
|
||||
for n in [own, owner] {
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
let paths = paths_in(&art);
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
}
|
||||
|
||||
/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`.
|
||||
fn type_node(id: u64, effects: Vec<Effect>) -> Node {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
@@ -1309,3 +1471,44 @@ fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() {
|
||||
}));
|
||||
assert_eq!(crate::outer_effects(&filled).len(), 2);
|
||||
}
|
||||
|
||||
/// Type whose own fill's Transform effect makes copies is drawn as its outlines, and each copy
|
||||
/// carries the shadow listed before that Transform effect, as a path's copies do: for the fill's
|
||||
/// first Transform effect and for one listed after a Transform effect with Transform Patterns on.
|
||||
/// Drawn, expanded and baked.
|
||||
#[test]
|
||||
fn type_carries_its_fills_shadow_on_each_copy() {
|
||||
let filled = |mut n: Node, effects: Vec<Effect>| {
|
||||
n.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
|
||||
effects,
|
||||
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
|
||||
}));
|
||||
n
|
||||
};
|
||||
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let later = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
for (what, effects) in [("first", copying), ("later", later)] {
|
||||
let n = filled(type_node(95, vec![]), effects);
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None)), ("expanded", expand_outlined(None, &n, None)), ("baked", Some(baked(n.clone())))]
|
||||
{
|
||||
let art = art.unwrap_or_else(|| panic!("{what}: {how}"));
|
||||
assert!(near(&shadows_in(&art), &[(10.0, 0.0), (10.0, 0.0)]), "{what}: {how} {:?}", shadows_in(&art));
|
||||
// The two shadows are on two objects 100 pt apart: the type and its copy.
|
||||
let mut lefts = vec![];
|
||||
art.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
let shadows = lists.map(|l| l.iter().filter(|e| e.id == "stylize.dropShadow").count()).sum::<usize>();
|
||||
if let Some(b) = m.geometric_bounds() {
|
||||
lefts.extend(std::iter::repeat_n(b.x0, shadows));
|
||||
}
|
||||
});
|
||||
lefts.sort_by(f64::total_cmp);
|
||||
assert!(lefts.len() == 2 && (lefts[1] - lefts[0] - 100.0).abs() < 1e-6, "{what}: {how} {lefts:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`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`]) and Tangent Circle ([`tangent_circle`]).
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
@@ -13,6 +14,7 @@ mod effect_tests;
|
||||
mod shape;
|
||||
mod shared_edge;
|
||||
mod tangent_circle;
|
||||
mod tangents;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod trim;
|
||||
@@ -182,6 +184,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(shared_edge::specs());
|
||||
v.extend(trim::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
|
||||
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
|
||||
//! crossing into either, added as separate open paths, with the line joining their centers if
|
||||
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::Affine;
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The command's id.
|
||||
pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents";
|
||||
/// The undo step's name.
|
||||
const LABEL: &str = "Common Tangents";
|
||||
/// The kinds of tangent `tangents` picks.
|
||||
const KINDS: [&str; 3] = ["external", "internal", "all"];
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.commonTangents",
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
|
||||
/// else the path's one closed convex subpath.
|
||||
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
|
||||
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
if span < 1e-9 || 360.0 - span < 1e-9 {
|
||||
let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]);
|
||||
return pt::Outline::ellipse(unit).map_err(refusal);
|
||||
}
|
||||
}
|
||||
pt::Outline::convex(sp).map_err(refusal)
|
||||
}
|
||||
|
||||
fn refusal(e: pt::OutlineError) -> EngineError {
|
||||
bad(
|
||||
COMMON_TANGENTS,
|
||||
match e {
|
||||
pt::OutlineError::Open => "a selected path is open",
|
||||
pt::OutlineError::NotConvex => "a selected path is not convex",
|
||||
pt::OutlineError::Empty => "a selected path has no area",
|
||||
pt::OutlineError::TooComplex => "a selected path has more than 10000 segments",
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all");
|
||||
let centerline = switch_or(p, "centerline", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let ordered = d.paint_order(roots.iter().copied());
|
||||
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
|
||||
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
|
||||
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
|
||||
let keep = |t: &&pt::Tangent| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
};
|
||||
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
|
||||
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
|
||||
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
if lines.is_empty() {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
|
||||
// external tangent means one path lies inside the other and touches it there; paths that
|
||||
// overlap without one inside the other have at least two.
|
||||
let warning = match external {
|
||||
0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()),
|
||||
1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()),
|
||||
_ => EngineError::Other("The paths overlap, so they have no internal tangents".into()),
|
||||
};
|
||||
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
|
||||
}
|
||||
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center()));
|
||||
let fill = Paint::None;
|
||||
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
|
||||
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
|
||||
// The new art's look may carry more fills than the top one: none of them is kept.
|
||||
look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
|
||||
let top = *second;
|
||||
let (ids, center_id) = s.edit(LABEL, |d, sel| {
|
||||
let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
|
||||
let mut ids = vec![];
|
||||
let mut center_id = None;
|
||||
for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() {
|
||||
let id = d.alloc_id();
|
||||
let path = PathData::single(SubPath::polyline(&[from, to], false));
|
||||
let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false });
|
||||
look.apply(d, &mut n);
|
||||
d.insert(parent, idx + 1 + k, n)?;
|
||||
if k == lines.len() {
|
||||
center_id = Some(id);
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok((ids, center_id))
|
||||
})?;
|
||||
Ok(json!({
|
||||
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"external": external_kept,
|
||||
"internal": internal_kept,
|
||||
"centerline": center_id.map(|i| i.0),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline,
|
||||
//! the paint, one undo step, the cases with no tangent, and refused selections and params.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Vec2};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = super::COMMON_TANGENTS;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The ends of each new line, as `ids` lists them.
|
||||
fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
r["ids"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let n = d.node(NodeId(v.as_u64().unwrap())).unwrap();
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") };
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
let sp = &path.subpaths[0];
|
||||
assert!(!sp.closed);
|
||||
assert_eq!(sp.anchors.len(), 2);
|
||||
(sp.anchors[0].p, sp.anchors[1].p)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn near(p: Point, q: Point) -> bool {
|
||||
p.distance(q) < 1e-6
|
||||
}
|
||||
|
||||
fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool {
|
||||
found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 200.0, 20.0);
|
||||
let b = circle(&mut s, 300.0, 200.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 4);
|
||||
let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
|
||||
// External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3.
|
||||
for (nx, external) in [(-0.1f64, true), (0.3, false)] {
|
||||
for sy in [1.0, -1.0] {
|
||||
let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt());
|
||||
let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 };
|
||||
assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}");
|
||||
}
|
||||
}
|
||||
// The lines are the selection, above the two circles.
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), 4);
|
||||
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
|
||||
let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied()));
|
||||
assert_eq!(&order[..2], &[a, b]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_ellipses_are_measured_exactly() {
|
||||
let mut s = session();
|
||||
let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap();
|
||||
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap());
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
let r = s.execute(C, &json!({"tangents": "all"})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
|
||||
// Each end lies on its ellipse, where the ellipse runs along the line: turned back about the
|
||||
// center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line.
|
||||
let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| {
|
||||
let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians());
|
||||
// `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms.
|
||||
let page = |v: Vec2| Vec2::new(v.x, -v.y);
|
||||
let q = page((turn * page(p - center).to_point()).to_vec2());
|
||||
let d = page((turn * page(dir).to_point()).to_vec2());
|
||||
let value = (q.x / rx).powi(2) + (q.y / ry).powi(2);
|
||||
let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry));
|
||||
(value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7
|
||||
};
|
||||
for (p, q) in lines(&s, &r) {
|
||||
let dir = q - p;
|
||||
assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse");
|
||||
assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_convex_bezier_path_and_the_centerline() {
|
||||
let mut s = session();
|
||||
let anchors = json!([
|
||||
{"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]},
|
||||
{"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]},
|
||||
{"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]},
|
||||
{"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]}
|
||||
]);
|
||||
let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap());
|
||||
let round = circle(&mut s, 300.0, 200.0, 30.0);
|
||||
let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 5, "four tangents and the centerline");
|
||||
// The centerline is the last line and its id is given: from the blob's center of area to the
|
||||
// circle's center.
|
||||
assert_eq!(r["centerline"], r["ids"][4]);
|
||||
let (from, to) = found[4];
|
||||
assert!(near(to, Point::new(300.0, 200.0)), "{to:?}");
|
||||
assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}");
|
||||
// A tangent touches without crossing: every point of both paths is on one side of it.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let points = |id: NodeId| {
|
||||
let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
|
||||
let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect();
|
||||
segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::<Vec<_>>()
|
||||
};
|
||||
let (pa, pb) = (points(blob), points(round));
|
||||
for (p, q) in &found[..4] {
|
||||
let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize();
|
||||
for pts in [&pa, &pb] {
|
||||
let side: Vec<f64> = pts.iter().map(|x| (*x - *p).dot(n)).collect();
|
||||
let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
|
||||
// The circle is measured as an exact circle, which its four curves follow to within
|
||||
// about 0.03% of the radius.
|
||||
assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lines_take_the_current_stroke_and_no_fill() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 300.0, 100.0, 20.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for v in r["ids"].as_array().unwrap() {
|
||||
let n = d.node(NodeId(v.as_u64().unwrap())).unwrap();
|
||||
assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill");
|
||||
let st = n.appearance.stroke().expect("stroked");
|
||||
assert!(!st.paint.is_none(), "black when the stroke is None");
|
||||
}
|
||||
// A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill.
|
||||
let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0);
|
||||
let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
|
||||
look.items.push(fill);
|
||||
s.paint.appearance = Some(look);
|
||||
s.paint.inherited = false;
|
||||
let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap();
|
||||
let d2 = &s.doc().unwrap().doc;
|
||||
for v in r2["ids"].as_array().unwrap() {
|
||||
let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap();
|
||||
assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all");
|
||||
assert!(n.appearance.stroke().is_some());
|
||||
}
|
||||
// Two equal circles: the external tangents run along their tops and bottoms.
|
||||
assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0)));
|
||||
assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_and_overlapping_paths_change_nothing_and_say_why() {
|
||||
let mut s = session();
|
||||
let big = circle(&mut s, 200.0, 200.0, 100.0);
|
||||
let small = circle(&mut s, 220.0, 200.0, 20.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
// Overlapping circles have external tangents only.
|
||||
let a = circle(&mut s, 100.0, 100.0, 30.0);
|
||||
let b = circle(&mut s, 140.0, 100.0, 30.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap();
|
||||
assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before);
|
||||
let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
// Circles that touch share the tangent where they touch.
|
||||
let c = circle(&mut s, 100.0, 300.0, 10.0);
|
||||
let e = circle(&mut s, 130.0, 300.0, 20.0);
|
||||
let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap();
|
||||
assert_eq!(r["internal"].as_u64(), Some(1), "{r}");
|
||||
let (p, q) = lines(&s, &r)[0];
|
||||
assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}");
|
||||
// A circle touching the inside of a larger one: no internal tangent, and the message says the
|
||||
// one lies inside the other rather than that they overlap.
|
||||
let outer = circle(&mut s, 400.0, 200.0, 50.0);
|
||||
let inner = circle(&mut s, 430.0, 200.0, 20.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before);
|
||||
let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_selections_and_params_are_refused() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 300.0, 100.0, 20.0);
|
||||
let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap());
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
|
||||
let group_of = |s: &mut Session, ids: &[NodeId]| {
|
||||
select(s, ids);
|
||||
id_of(&s.execute("object.group", &json!({})).unwrap())
|
||||
};
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused");
|
||||
assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open"));
|
||||
assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap());
|
||||
assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline"));
|
||||
let g = group_of(&mut s, &[b]);
|
||||
assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths"));
|
||||
}
|
||||
@@ -703,7 +703,7 @@ impl Relink {
|
||||
self.name(Res::ParaStyle, s);
|
||||
}
|
||||
}
|
||||
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten() {
|
||||
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() {
|
||||
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Path",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}",
|
||||
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
|
||||
has_doc,
|
||||
split
|
||||
),
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -196,6 +196,9 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) {
|
||||
return Err(bad(C, "invalid t"));
|
||||
}
|
||||
if !(0.0..=1.0).contains(&t) {
|
||||
return Err(bad(C, "`t` must be from 0 to 1"));
|
||||
}
|
||||
let ids = s.edit("Split Path", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
@@ -295,7 +298,13 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
}
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !(1.0..=100.0).contains(&roundness) {
|
||||
return Err(bad(C, "`roundness` must be from 1 to 100%"));
|
||||
}
|
||||
let vary = eraser_variations(p, C)?;
|
||||
if varies_beyond_size_pressure(&vary) {
|
||||
return erase_varied(s, &samples, [angle, roundness, size], vary);
|
||||
@@ -305,7 +314,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0));
|
||||
let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0;
|
||||
let short = narrowest * roundness / 100.0;
|
||||
let st = s.doc()?;
|
||||
// A point is under the tip when, with the tip squashed back into a circle, it is within the
|
||||
// circle's radius of the squashed drag.
|
||||
|
||||
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool {
|
||||
|
||||
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at
|
||||
/// the document's raster effects resolution or a Rasterize effect's finer one, with whether they
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them). A group's or
|
||||
/// layer's image leaves out its members' raster effects, which are expanded with them. `None`
|
||||
/// when it has none.
|
||||
fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them, and paints with
|
||||
/// their blend mode when they all use one). A group's or layer's image leaves out its members'
|
||||
/// raster effects, which are expanded with them. `None` when it has none.
|
||||
/// `Err` when that image would take `budget` past its limits: the object then stays as it is.
|
||||
fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result<Option<(Node, bool)>, OverBudget> {
|
||||
let fx = rasterfx::raster_fx(n);
|
||||
if fx.is_empty() {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
let below = fx.iter().all(effects::RasterFx::is_below);
|
||||
Some((rasterfx::raster_image(d, n, below, true)?, below))
|
||||
let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?;
|
||||
let mut image = rasterfx::raster_image(d, n, below, true);
|
||||
if image.is_none() {
|
||||
// No image was made: it takes nothing from the budget.
|
||||
budget.images += 1;
|
||||
budget.pixels += pixels;
|
||||
}
|
||||
// Rendered alone, over nothing, the shadows and glows can't blend with the art below the
|
||||
// object, so the image does, as the canvas draws them.
|
||||
let mut modes = fx.iter().filter_map(effects::RasterFx::mode);
|
||||
if below
|
||||
&& let (Some(mode), Some(image)) = (modes.next(), image.as_mut())
|
||||
&& modes.all(|m| m == mode)
|
||||
{
|
||||
image.blend = mode;
|
||||
}
|
||||
Ok(image.map(|image| (image, below)))
|
||||
}
|
||||
|
||||
/// The most images of raster effects one Expand Appearance makes.
|
||||
const MAX_RASTER_IMAGES: u32 = 1_024;
|
||||
|
||||
/// The most pixels the images of raster effects one Expand Appearance makes hold in all.
|
||||
const MAX_RASTER_PIXELS: u64 = 256_000_000;
|
||||
|
||||
/// The note when objects keep their raster effects because their images would take an Expand
|
||||
/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`].
|
||||
pub(crate) const RASTER_EFFECTS_LEFT: &str =
|
||||
"some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all";
|
||||
|
||||
/// An image of raster effects that would take a [`RasterBudget`] past its limits.
|
||||
#[derive(Debug)]
|
||||
struct OverBudget;
|
||||
|
||||
/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the
|
||||
/// objects whose raster effects it left as they are because their images would go past them.
|
||||
pub(crate) struct RasterBudget {
|
||||
images: u32,
|
||||
pixels: u64,
|
||||
pub(crate) left: usize,
|
||||
}
|
||||
|
||||
impl RasterBudget {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 }
|
||||
}
|
||||
|
||||
/// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return
|
||||
/// them; `Err`, with its object counted in `left`, when it would go past what is left.
|
||||
fn take(&mut self, pixels: u64) -> std::result::Result<u64, OverBudget> {
|
||||
if self.images == 0 || pixels > self.pixels {
|
||||
self.left += 1;
|
||||
return Err(OverBudget);
|
||||
}
|
||||
self.images -= 1;
|
||||
self.pixels -= pixels;
|
||||
Ok(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
|
||||
@@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
m: &mut Node,
|
||||
@@ -991,6 +1050,7 @@ fn expand_pieces(
|
||||
skip: &[NodeId],
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
@@ -1005,7 +1065,7 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip));
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1029,38 +1089,87 @@ fn expand_pieces(
|
||||
expanded
|
||||
}
|
||||
|
||||
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
|
||||
/// shadow blurred by the light's Softness) expanded as Expand Appearance expands it on its own:
|
||||
/// a blurred shadow becomes an image. Groups in `m` without effects that hold such an object are
|
||||
/// looked into; the rest are left as they are. The objects `skip` lists are not expanded.
|
||||
fn expand_raster_pieces(d: &mut Document, mut m: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Node {
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
if !c.appearance.effects.is_empty() {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, &mut vec![], raster) {
|
||||
*c = Arc::new(e);
|
||||
}
|
||||
} else if c.children().is_some() {
|
||||
let mut holds = false;
|
||||
c.walk(&mut |n| holds |= !n.appearance.effects.is_empty());
|
||||
if holds {
|
||||
*c = Arc::new(expand_raster_pieces(d, (**c).clone(), brushes, skip, raster));
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
|
||||
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
|
||||
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
|
||||
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
|
||||
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
|
||||
/// would take the objects placed so far past `budget`.
|
||||
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
|
||||
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
|
||||
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
|
||||
/// that art in turn, so [`expand_pieces`] bakes their effects with the rest.
|
||||
fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) {
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
|
||||
if c.children().is_some() {
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
continue;
|
||||
}
|
||||
*budget -= count;
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget);
|
||||
if let Some(a) = expanded_instance(d, c, depth, budget, raster) {
|
||||
*c = Arc::new(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster
|
||||
/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art
|
||||
/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as
|
||||
/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when
|
||||
/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance
|
||||
/// staying as it is, when its active fill and stroke have no such effect, it is more than
|
||||
/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would
|
||||
/// take the objects placed so far past `budget`, or the image of its raster effects would take
|
||||
/// `raster` past its limits. When that image can't be made, they stay on the art its geometry
|
||||
/// effects make, and without one it stays as it is.
|
||||
fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None };
|
||||
let has_raster = effects::has_instance_row_raster(c);
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) {
|
||||
return None;
|
||||
}
|
||||
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
return None;
|
||||
}
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
let image = if has_raster { raster_image(d, c, raster).ok()? } else { None };
|
||||
*budget -= count;
|
||||
let mut v = c.clone();
|
||||
if image.is_some() {
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
}
|
||||
let below = match image {
|
||||
Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)),
|
||||
Some((image, true)) => Some(image),
|
||||
None => None,
|
||||
};
|
||||
let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art))
|
||||
.or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?;
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget, raster);
|
||||
if let Some(image) = below {
|
||||
rasterfx::put_below(d, &mut a, image);
|
||||
}
|
||||
Some(a)
|
||||
}
|
||||
|
||||
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
|
||||
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
@@ -1075,9 +1184,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
type Listed = (NodeId, usize);
|
||||
|
||||
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec<Listed> {
|
||||
let mut listed = vec![];
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) {
|
||||
*c = e;
|
||||
}
|
||||
listed
|
||||
@@ -1099,18 +1208,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
|
||||
/// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and
|
||||
/// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art),
|
||||
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
|
||||
/// transparency.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
|
||||
expand_node_except(d, id, brushes, &[], out);
|
||||
/// transparency. An object whose raster effects' image would take `raster` past its limits stays
|
||||
/// as it is, with what is inside it.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>, raster: &mut RasterBudget) {
|
||||
expand_node_except(d, id, brushes, &[], out, raster);
|
||||
}
|
||||
|
||||
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
|
||||
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
|
||||
/// copies of it that such an effect makes are left as they are too.
|
||||
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
|
||||
fn expand_node_except(
|
||||
d: &mut Document,
|
||||
id: NodeId,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<NodeId>,
|
||||
raster: &mut RasterBudget,
|
||||
) {
|
||||
let Some(n) = d.node(id).cloned() else { return };
|
||||
let mut listed = vec![];
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed);
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed, raster);
|
||||
out.extend(listed.into_iter().map(|(id, _)| id));
|
||||
if let Some(mut m) = m {
|
||||
// Art made from type takes its emoji's pixels into the document.
|
||||
@@ -1124,11 +1241,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
fn expanded_node(
|
||||
d: &mut Document,
|
||||
mut n: Node,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<Listed>,
|
||||
raster: &mut RasterBudget,
|
||||
) -> Option<Node> {
|
||||
let id = n.id;
|
||||
if skip.contains(&id) || !expandable(&n) {
|
||||
return None;
|
||||
}
|
||||
// What `out` held before `n`: an object left by the raster budget lists nothing.
|
||||
let listed_before = out.len();
|
||||
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
|
||||
// recoloured copy), then the rest of the appearance expands.
|
||||
let mut changed = false;
|
||||
@@ -1141,6 +1267,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
|
||||
// is: the recolored copies the adjustment adds then go again.
|
||||
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1163,7 +1293,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
expanded = expand_in_place(d, c, brushes, skip);
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1186,7 +1316,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let image = raster_image(d, &n);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
|
||||
let Ok(image) = raster_image(d, &n, raster) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
let mut stroke_art =
|
||||
@@ -1206,7 +1344,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
@@ -1224,13 +1362,21 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
// A symbol instance whose active fill or stroke has only effects that paint below it
|
||||
// (now in the image) becomes its art as well.
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
};
|
||||
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
|
||||
// expands in turn, to an image.
|
||||
let m = if effects::has_solid(&v) || effects::has_revolve(&v) { m.map(|m| expand_raster_pieces(d, m, brushes, skip, raster)) } else { m };
|
||||
match image {
|
||||
Some((image, _)) => {
|
||||
let mut m = m.unwrap_or(v);
|
||||
@@ -1262,7 +1408,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
None => {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) {
|
||||
*c = Arc::new(e);
|
||||
changed = true;
|
||||
}
|
||||
@@ -1336,6 +1482,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let mut raster = RasterBudget::new();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
let before = d.clone();
|
||||
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
|
||||
@@ -1351,7 +1498,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out);
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster);
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
@@ -1360,6 +1507,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// stays type under a new id takes its frame's place.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
if out.is_empty() || (kept && d.layers == before.layers) {
|
||||
if raster.left > 0 {
|
||||
return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into()));
|
||||
}
|
||||
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
|
||||
}
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
|
||||
@@ -1367,8 +1517,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
let mut out = json!({ "ids": ids_json(&ids) });
|
||||
// Raster effects become images rendered from the art.
|
||||
if let Some(w) = rasterfx::undecoded_warning(failed) {
|
||||
out["warning"] = json!(w);
|
||||
let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
if raster.left > 0 {
|
||||
out["rasterLeft"] = json!(raster.left);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1017,6 +1017,49 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
|
||||
assert_eq!(shadows, 1);
|
||||
}
|
||||
|
||||
/// With the light's Softness, the 3D shadow is blurred: the canvas paints past the hard shadow's
|
||||
/// edge, the object's bounds take the blur in, SVG export blurs it as it does a Gaussian Blur
|
||||
/// effect, and Expand Appearance keeps it as an image with no live effect left.
|
||||
#[test]
|
||||
fn a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap();
|
||||
let set = |s: &mut Session, params: serde_json::Value| {
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap();
|
||||
};
|
||||
let draw = |s: &Session| {
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let bounds = |s: &Session| {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
vectorcraft_render::effect_bounds(&doc.symbol_boxes(), doc.node(id).unwrap()).unwrap()
|
||||
};
|
||||
let blurs = |s: &mut Session| {
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
svg.matches("<feGaussianBlur").count()
|
||||
};
|
||||
let none = draw(&s);
|
||||
set(&mut s, json!({"shadow": true, "shadowDistance": 50}));
|
||||
let (hard, hard_bounds, hard_blurs) = (draw(&s), bounds(&s), blurs(&mut s));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
set(&mut s, json!({"lightSoftness": 100}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
let (soft, soft_bounds) = (draw(&s), bounds(&s));
|
||||
// Pixels the hard shadow leaves as they are, the soft one paints.
|
||||
let spread = none.chunks(4).zip(hard.chunks(4)).zip(soft.chunks(4)).filter(|((n, h), s)| n == h && n != s).count();
|
||||
assert!(spread > 100, "{spread}");
|
||||
assert!(soft_bounds.contains_rect(hard_bounds) && soft_bounds.area() > hard_bounds.area(), "{hard_bounds:?} {soft_bounds:?}");
|
||||
assert_eq!(blurs(&mut s), hard_blurs + 1, "SVG export blurs the shadow as a Gaussian Blur effect");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
let (mut live, mut pictures) = (0, 0);
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
live += usize::from(!n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()));
|
||||
pictures += usize::from(matches!(n.kind, NodeKind::Image(_)));
|
||||
});
|
||||
assert_eq!((live, pictures), (0, 1), "the blurred shadow expands to an image");
|
||||
}
|
||||
|
||||
/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
|
||||
/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
|
||||
#[test]
|
||||
@@ -1082,3 +1125,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
|
||||
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
|
||||
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
|
||||
}
|
||||
|
||||
/// The raster budget charges each image its pixels before it is made: an image past what is left
|
||||
/// is refused and counted, and the object keeps its blur.
|
||||
#[test]
|
||||
fn an_image_past_the_pixels_left_stays_unmade() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap();
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let n = d.node(id).cloned().unwrap();
|
||||
let pixels = super::rasterfx::raster_pixels(&d, &n, false, true);
|
||||
assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err());
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels, left: 0 };
|
||||
let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made");
|
||||
let NodeKind::Image(img) = &image.kind else { panic!("not an image") };
|
||||
assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size");
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0));
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
|
||||
}
|
||||
@@ -129,9 +129,9 @@ mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
pub(crate) use access::check_images_in;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{check_images_in, check_scripts_of};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
|
||||
@@ -121,22 +121,54 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
|
||||
/// The error for a file that would name a JavaScript file the document links outside the read roots.
|
||||
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
|
||||
/// and those too unless read roots are in force and the document links a JavaScript file outside
|
||||
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
|
||||
/// which the file's `<script>` element would name. The error names no file or folder.
|
||||
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
/// `cmd` may write `st`'s document in format `format` (a format id) with options `p` (presets
|
||||
/// written out): always, unless read roots are in force, the document links a JavaScript file
|
||||
/// outside them (`svg_scripts`, a relative path taken from the document's folder; a URL is not
|
||||
/// checked) and the file names it ([`names_linked_scripts`], with the artboards `p` picks counted
|
||||
/// in `st`'s document): an SVG's `<script>` element, or the native document that a native file, a
|
||||
/// `.ai` file, an EPS file or a PDF with Preserve Editing carries. The error names no file or folder.
|
||||
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState, p: &Value) -> Result<()> {
|
||||
check_scripts_of(cmd, &st.doc, st.path.as_deref(), || names_linked_scripts(cmd, format, p, st.doc.artboards.len()))
|
||||
}
|
||||
|
||||
/// `doc`, saved at `doc_path`, may be written by `cmd` in a file that names its linked JavaScript
|
||||
/// files when `names` says so: as [`check_linked_scripts`] allows it.
|
||||
pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_path: Option<&str>, names: impl FnOnce() -> bool) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) || !names() {
|
||||
return Ok(());
|
||||
}
|
||||
let doc_path = st.path.as_deref();
|
||||
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
|
||||
return Err(bad(cmd, SCRIPT_OUTSIDE));
|
||||
Err(bad(cmd, SCRIPT_OUTSIDE))
|
||||
}
|
||||
|
||||
/// Does a file of a document with `artboards` artboards, written in format `format` with options
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
|
||||
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
|
||||
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
|
||||
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
|
||||
/// refuses count as naming them.
|
||||
pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards: usize) -> bool {
|
||||
use serde::Deserialize;
|
||||
let every_artboard = || {
|
||||
let pick = if p.is_object() { super::ArtboardPick::deserialize(p).ok() } else { Some(super::ArtboardPick::default()) };
|
||||
pick.and_then(|pick| pick.resolve(artboards).ok()).is_none_or(|v| v.is_none_or(|v| v.iter().copied().eq(0..artboards)))
|
||||
};
|
||||
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
|
||||
match format {
|
||||
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
|
||||
"ai" | "ait" => {
|
||||
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
|
||||
!legacy && !(format == "ai" && art_page()) && every_artboard()
|
||||
}
|
||||
"pdf" => {
|
||||
let editing = super::pdf::settings(cmd, p).ok().is_none_or(|s| s.preserve_editing);
|
||||
editing && !art_page() && every_artboard()
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -53,10 +53,10 @@ pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool {
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes("document.serialize", f, p);
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
check_linked_scripts("document.serialize", f.id, s.doc()?, &p)?;
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
let doc = &*doc;
|
||||
let mut q = p.clone();
|
||||
@@ -97,10 +97,10 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
check_linked_scripts("document.export", f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes("document.export", f, p);
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
check_linked_scripts("document.export", f.id, s.doc()?, &p)?;
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
let doc = &*doc;
|
||||
let mut q = p.clone();
|
||||
@@ -375,10 +375,11 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
check_linked_scripts(C, f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes(C, f, p);
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
// The selection is written on one artboard of its own: every artboard, whatever `p` picks.
|
||||
check_linked_scripts(C, f.id, s.doc()?, &without_artboards(&p))?;
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The selected objects' links are looked for from the document they are in.
|
||||
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
|
||||
|
||||
@@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption {
|
||||
name: "layers",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent",
|
||||
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way",
|
||||
};
|
||||
|
||||
const MAX_EDITABILITY: FormatOption = FormatOption {
|
||||
|
||||
@@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
let one = super::save::artboard_doc(doc, b);
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(&one);
|
||||
let mut d = full.into_owned();
|
||||
expand_appearances(&mut d);
|
||||
if expand_appearances(&mut d) {
|
||||
note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT);
|
||||
}
|
||||
if mode == SeeThrough::Flatten {
|
||||
expand_image_patterns(&mut d)?;
|
||||
}
|
||||
@@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold.
|
||||
fn expand_appearances(d: &mut Document) {
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether
|
||||
/// objects kept raster effects whose images would go past Expand Appearance's limits.
|
||||
fn expand_appearances(d: &mut Document) -> bool {
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
|
||||
let mut out = vec![];
|
||||
let mut raster = super::super::effectcmd::RasterBudget::new();
|
||||
for id in layers {
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out);
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster);
|
||||
}
|
||||
raster.left > 0
|
||||
}
|
||||
|
||||
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
@@ -499,6 +499,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expanded = expand_preset(s, C, p)?;
|
||||
let p = &*expanded;
|
||||
let st = s.doc()?;
|
||||
super::check_linked_scripts(C, "pdf", st, p)?;
|
||||
let display_doc_title = super::has_own_title(&st.doc);
|
||||
let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf");
|
||||
let mut q = p.clone();
|
||||
|
||||
@@ -889,7 +889,6 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
|
||||
|
||||
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
@@ -934,6 +933,14 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
o.insert("range".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
// A saved `.ai` or `.ait` file has the artboards as its pages, whatever `useArtboards` says.
|
||||
let checked = match (¶ms, plan.format.id) {
|
||||
(Value::Object(o), "ai" | "ait") => {
|
||||
std::borrow::Cow::Owned(Value::Object(o.iter().filter(|(k, _)| *k != "useArtboards").map(|(k, v)| (k.clone(), v.clone())).collect()))
|
||||
}
|
||||
_ => std::borrow::Cow::Borrowed(¶ms),
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
}
|
||||
|
||||
@@ -1318,7 +1325,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
@@ -1345,7 +1352,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save as Template…",
|
||||
["File"],
|
||||
None,
|
||||
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
|
||||
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}. Under automation read roots, it is refused, before any file is written, while the document links a JavaScript file outside them, as document.save refuses it",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Template, p)
|
||||
),
|
||||
|
||||
@@ -764,7 +764,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) {
|
||||
|
||||
/// Export settings kept in the document or a preset, as the request being served may see them: a
|
||||
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
|
||||
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
@@ -1089,6 +1089,29 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does the file of `item` that row `r` writes carry the native document, and with it the
|
||||
/// JavaScript files the document links ([`super::access::names_linked_scripts`])? A PDF holds the
|
||||
/// artboards it is written with: those of `single` (Export PDFs As › Single file), every artboard
|
||||
/// (Full Document), else the item's artboard of its document.
|
||||
fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
|
||||
if r.format.id != "pdf" {
|
||||
return super::access::names_linked_scripts(C, r.format.id, &r.options, item.doc.artboards.len());
|
||||
}
|
||||
let (doc, options) = match (single, &item.every_artboard) {
|
||||
(Some(boards), _) => {
|
||||
let mut options = r.options.clone();
|
||||
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
|
||||
(&item.doc, options)
|
||||
}
|
||||
(None, Some(all)) => (all, r.options.clone()),
|
||||
(None, None) => match r.options_for(item.region, item.artboard) {
|
||||
Ok(options) => (&item.doc, options),
|
||||
Err(_) => return true,
|
||||
},
|
||||
};
|
||||
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
|
||||
}
|
||||
|
||||
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
@@ -1105,10 +1128,6 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
o.one_source()?;
|
||||
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
|
||||
let st = s.doc()?;
|
||||
// Before the folder is made or any row is written.
|
||||
for r in &rows {
|
||||
super::check_linked_scripts(C, r.format.id, st)?;
|
||||
}
|
||||
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
|
||||
let selection = o.selection_mode()?;
|
||||
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
|
||||
@@ -1125,6 +1144,10 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// Before the folder is made or any row is written, with the artboards each file holds.
|
||||
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
|
||||
let st = s.doc()?;
|
||||
super::check_scripts_of(C, &st.doc, st.path.as_deref(), || rows.iter().any(|r| items.iter().any(|i| names_scripts(i, r, single.as_deref()))))?;
|
||||
// The file each item writes for each SVG row, before the folder is made or any row is written.
|
||||
let base = crate::cmd::links::LinkBase::of(s.doc()?);
|
||||
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
|
||||
|
||||
@@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
|
||||
})
|
||||
}
|
||||
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
vectorcraft_format::save(&kept, false)
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
/// link to and the writer's warnings.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
|
||||
let (opts, boards, chosen) = plan(doc, p)?;
|
||||
// Preserve editing embeds the native document (once, shared by every file).
|
||||
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
|
||||
let native = opts.preserve_editing.then(|| native_attachment(doc));
|
||||
// Draw linked files as vectors when available, or their previews with a warning. Keep
|
||||
// that preparation out of the native attachment so missing links remain relinkable.
|
||||
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
|
||||
@@ -511,3 +511,75 @@ fn damaged_slices_never_panic() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The PSD file `document.export` writes from `s`, with its layers or flat.
|
||||
fn export(s: &mut Session, layers: bool) -> Vec<u8> {
|
||||
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_files_slices_survive_a_psd_export() {
|
||||
let link =
|
||||
S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) };
|
||||
let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) };
|
||||
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) };
|
||||
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
|
||||
let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[]));
|
||||
let (mut s, _) = open(&f, json!({}));
|
||||
let opened = slices(&s);
|
||||
assert_eq!(opened.len(), 3);
|
||||
for layers in [true, false] {
|
||||
let out = export(&mut s, layers);
|
||||
let (again, r) = open(&out, json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
// The same rectangles and options; the auto slices are laid out again around them.
|
||||
let mut got = slices(&again);
|
||||
let mut want = opened.clone();
|
||||
let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0)));
|
||||
order(&mut got);
|
||||
order(&mut want);
|
||||
assert_eq!(got, want);
|
||||
let layout = again.doc().unwrap().doc.slice_layout();
|
||||
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
|
||||
assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
let rect = r["id"].as_u64().unwrap();
|
||||
s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "<i>x</i>", "background": "#00ff00"})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.slice.make", &json!({"ids": [t]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap();
|
||||
let (again, _) = open(&export(&mut s, false), json!({}));
|
||||
let got = slices(&again);
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap();
|
||||
let boxed = got.iter().find(|g| g.1.name == "box").unwrap();
|
||||
// Within a pixel of the object's bounds.
|
||||
for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] {
|
||||
assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0);
|
||||
}
|
||||
assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "<i>x</i>", "#00ff00"));
|
||||
let text = got.iter().find(|g| g.1.name.is_empty()).unwrap();
|
||||
assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A & B"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() {
|
||||
let columns: Vec<S> = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect();
|
||||
let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({}));
|
||||
assert_eq!(slices(&s).len(), 20);
|
||||
let (again, r) = open(&export(&mut s, true), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
assert_eq!(slices(&again), slices(&s));
|
||||
}
|
||||
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
font_list
|
||||
),
|
||||
cmd!(
|
||||
query "text.similarFonts",
|
||||
"Show Similar Fonts",
|
||||
[],
|
||||
None,
|
||||
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
|
||||
always,
|
||||
similar_fonts
|
||||
),
|
||||
cmd!(
|
||||
query "text.glyphCategories",
|
||||
"Glyph Categories",
|
||||
@@ -1146,6 +1155,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most families `text.similarFonts` takes as its `limit`.
|
||||
const MAX_SIMILAR: u64 = 100_000;
|
||||
|
||||
fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.similarFonts";
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let family = match p.get("family") {
|
||||
Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(),
|
||||
Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")),
|
||||
Some(_) => return Err(bad(C, "`family` must be a string")),
|
||||
};
|
||||
let limit = match p.get("limit") {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
v.as_u64()
|
||||
.filter(|n| (1..=MAX_SIMILAR).contains(n))
|
||||
.ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?,
|
||||
),
|
||||
};
|
||||
// Any of the family's names, spelled as the font menus list it; a family they don't list is not available.
|
||||
let menu = db.menu_family_list();
|
||||
let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned());
|
||||
let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) };
|
||||
let mut families = db.similar_families(&family, &menu);
|
||||
if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) {
|
||||
families.truncate(n);
|
||||
}
|
||||
Ok(json!({ "family": family, "families": families }))
|
||||
}
|
||||
|
||||
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
|
||||
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
|
||||
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Type…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones",
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as bands `lineWidth` wide filled with the series colour), lineWidth?: pt (Line Width of Draw Filled Lines: 0.01–1000; 3), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; options that leave the graph as it is record no step of history; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones",
|
||||
has_selection,
|
||||
set_type
|
||||
),
|
||||
|
||||
@@ -230,6 +230,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value
|
||||
"prefix": one_line(&spec.prefix), "suffix": one_line(&spec.suffix), "rightPrefix": one_line(&spec.right_prefix),
|
||||
"rightSuffix": one_line(&spec.right_suffix), "dropShadow": spec.drop_shadow, "legendAcrossTop": spec.legend_across_top,
|
||||
"firstRowInFront": spec.first_row_in_front, "firstColumnInFront": spec.first_column_in_front, "filledLines": spec.filled_lines,
|
||||
"lineWidth": spec.filled_line_width(),
|
||||
});
|
||||
// Only the options this graph's types use: overlap order for columns and bars, filled lines for lines.
|
||||
let kinds: Vec<GraphKind> = (0..count.max(1)).map(|i| spec.series_kind(i)).collect();
|
||||
@@ -241,6 +242,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value
|
||||
}
|
||||
if !has(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]) {
|
||||
o.remove("filledLines");
|
||||
o.remove("lineWidth");
|
||||
}
|
||||
}
|
||||
// Pie graphs: Legend, Position and Sort (their Legend stands for the legend checkbox).
|
||||
@@ -266,6 +268,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graph.setType";
|
||||
let id = target(s, p, C)?;
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let stored = spec.clone();
|
||||
// The series to retype: `seriesIndexes`, else, with no `id`, a selection made only of this graph's series (Group
|
||||
// Selection). Anything else selected, the graph itself for one, is the whole graph.
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
@@ -311,6 +314,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"firstRowInFront",
|
||||
"firstColumnInFront",
|
||||
"filledLines",
|
||||
"lineWidth",
|
||||
"pieLegend",
|
||||
"piePosition",
|
||||
"pieSort",
|
||||
@@ -404,6 +408,15 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?;
|
||||
spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?;
|
||||
spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?;
|
||||
if let Some(w) = p.get("lineWidth").filter(|v| !v.is_null()) {
|
||||
let w = w.as_f64().ok_or_else(|| bad(C, format!("`lineWidth` must be a number, not {w}")))?;
|
||||
let (min, max) = (vectorcraft_doc::MIN_FILLED_LINE_WIDTH, vectorcraft_doc::MAX_FILLED_LINE_WIDTH);
|
||||
if !(min..=max).contains(&w) {
|
||||
return Err(bad(C, format!("`lineWidth` must be from {min} to {max} pt, not {w}")));
|
||||
}
|
||||
// The default width is stored as no width.
|
||||
spec.line_width = (w != vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH).then_some(w);
|
||||
}
|
||||
spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?;
|
||||
// After `legend`, which the Graph Type dialog sends too.
|
||||
if let Some(v) = text_param(p, "pieLegend", C)? {
|
||||
@@ -418,6 +431,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?;
|
||||
spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?;
|
||||
spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks);
|
||||
// Options that leave the graph as it is record no step of history.
|
||||
if spec == stored {
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
let label = format!("{} Graph", spec.kind.label());
|
||||
s.edit("Graph Type", |d, sel| {
|
||||
regenerate(d, id, spec)?;
|
||||
|
||||
@@ -230,10 +230,11 @@ impl Gen<'_> {
|
||||
Arc::new(g)
|
||||
}
|
||||
/// A series' line joining its data points (Connect Data Points): a 1 pt stroke in the series colour, or with Draw
|
||||
/// Filled Lines a band FILLED_LINE_WIDTH wide filled with it and outlined in black.
|
||||
/// Filled Lines a band as wide as the graph's Line Width ([`GraphSpec::filled_line_width`]) filled with it and outlined
|
||||
/// in black.
|
||||
pub(super) fn data_line(&mut self, g: &GraphSpec, s: usize, pd: PathData, filled: bool) -> Arc<Node> {
|
||||
let band = if filled {
|
||||
vectorcraft_pathops::outline_stroke(&pd, FILLED_LINE_WIDTH, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0)
|
||||
vectorcraft_pathops::outline_stroke(&pd, g.filled_line_width(), vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0)
|
||||
} else {
|
||||
PathData::default()
|
||||
};
|
||||
@@ -287,9 +288,6 @@ const SHADOW_OFFSET: f64 = 2.0;
|
||||
|
||||
pub(super) const SHADOW_OPACITY: f32 = 0.35;
|
||||
|
||||
/// Draw Filled Lines: how wide a filled line is.
|
||||
const FILLED_LINE_WIDTH: f64 = 3.0;
|
||||
|
||||
const FILLED_LINE_BUDGET: usize = 20_000;
|
||||
|
||||
/// Does graph `g`, with `series` series, draw Filled Lines (up to FILLED_LINE_BUDGET data points)?
|
||||
|
||||
@@ -1492,7 +1492,11 @@ pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = line_slot(&mut spec.label_styles, line);
|
||||
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
|
||||
let was_unpainted = stroke_unpainted(&rows);
|
||||
merge_row_edits(&mut rows, &old, &new);
|
||||
if old.paint.stroke != new.paint.stroke {
|
||||
keep_painted_stroke_weight(&mut rows, was_unpainted, &new.paint);
|
||||
}
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
@@ -1547,9 +1551,10 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = line_slot(&mut spec.label_styles, line);
|
||||
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
|
||||
let was_unpainted = stroke_unpainted(&rows);
|
||||
let k = &mut rows.paint;
|
||||
if on_fill.paint {
|
||||
k.fill = shown.fill;
|
||||
k.fill = shown.fill.clone();
|
||||
}
|
||||
if on_fill.opacity {
|
||||
k.fill_opacity = shown.fill_opacity;
|
||||
@@ -1558,7 +1563,7 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
|
||||
k.fill_blend = shown.fill_blend;
|
||||
}
|
||||
if on_stroke.paint {
|
||||
k.stroke = shown.stroke;
|
||||
k.stroke = shown.stroke.clone();
|
||||
}
|
||||
if on_stroke.weight {
|
||||
k.stroke_width = shown.stroke_width;
|
||||
@@ -1569,6 +1574,9 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
|
||||
if on_stroke.blend {
|
||||
k.stroke_blend = shown.stroke_blend;
|
||||
}
|
||||
if on_stroke.paint {
|
||||
keep_painted_stroke_weight(&mut rows, was_unpainted, &shown);
|
||||
}
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
@@ -1576,6 +1584,24 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
|
||||
changed
|
||||
}
|
||||
|
||||
/// Give kept line rows whose stroke an edit painted the painted line's stroke weight (`shown`) when the kind kept no
|
||||
/// stroke paint before the edit (`was_unpainted`) and keeps the zero weight a stroke set to None left. A non-zero kept
|
||||
/// weight stays, and so do a zero weight kept with a painted stroke and a zero weight the painted line shows.
|
||||
fn keep_painted_stroke_weight(rows: &mut vectorcraft_doc::LabelRows, was_unpainted: bool, shown: &vectorcraft_doc::SeriesPaint) {
|
||||
if was_unpainted
|
||||
&& !stroke_unpainted(rows)
|
||||
&& rows.paint.stroke_width.is_some_and(|w| w <= 0.0)
|
||||
&& let Some(w) = shown.stroke_width.filter(|w| *w > 0.0)
|
||||
{
|
||||
rows.paint.stroke_width = Some(w);
|
||||
}
|
||||
}
|
||||
|
||||
/// Do kept line rows keep no stroke paint?
|
||||
fn stroke_unpainted(rows: &vectorcraft_doc::LabelRows) -> bool {
|
||||
rows.paint.stroke.as_ref().is_none_or(Paint::is_none)
|
||||
}
|
||||
|
||||
/// Is `id` a graph line: a path directly in a graph's Axes group?
|
||||
pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool {
|
||||
graph_line(doc, id).is_some()
|
||||
|
||||
@@ -6740,6 +6740,54 @@ fn filled_lines_keep_the_line_colour_and_fall_back_to_thin_lines() {
|
||||
assert!(series_parts(&s, big, 0)[0].appearance.fill_paint().is_none());
|
||||
}
|
||||
|
||||
/// Line Width sets how wide Draw Filled Lines draws the bands and is kept through save and open. A width outside 0.01
|
||||
/// to 1000 pt is refused, the same width again records no undo step, and the default 3 pt is stored as no width.
|
||||
#[test]
|
||||
fn filled_lines_take_a_line_width() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = make(&mut s, "line", ",a\nQ1,2\nQ2,2\nQ3,2");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "filledLines": true})).unwrap();
|
||||
let height = |s: &Session| series_parts(s, id, 0)[0].geometric_bounds().unwrap().height();
|
||||
assert!((height(&s) - 3.0).abs() < 1e-6, "3 pt by default: {}", height(&s));
|
||||
assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(3.0));
|
||||
s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 8})).unwrap();
|
||||
assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s));
|
||||
assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(8.0));
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
for p in [json!({"id": id.0, "lineWidth": 8}), json!({"id": id.0, "lineWidth": 8.0, "filledLines": true}), json!({"id": id.0, "lineWidth": null})]
|
||||
{
|
||||
s.execute("graph.setType", &p).unwrap();
|
||||
assert_eq!(steps(&s), before, "nothing changed: {p}");
|
||||
}
|
||||
for w in [json!(0), json!(-2), json!(0.005), json!(1000.5)] {
|
||||
let e = s.execute("graph.setType", &json!({"id": id.0, "lineWidth": w})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("`lineWidth` must be from 0.01 to 1000 pt, not {}", w.as_f64().unwrap())), "{e}");
|
||||
assert_eq!((steps(&s), spec(&s, id).line_width), (before, Some(8.0)), "{w}");
|
||||
}
|
||||
s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 0.01})).unwrap();
|
||||
assert_eq!(spec(&s, id).line_width, Some(0.01));
|
||||
s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 1000})).unwrap();
|
||||
assert_eq!(spec(&s, id).line_width, Some(1000.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).line_width, Some(8.0));
|
||||
// Kept through save and open.
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-line-width");
|
||||
let path = dir.join("width.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(spec(&s, id).line_width, Some(8.0));
|
||||
assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s));
|
||||
// The default width is stored as no width, so the file keeps no `lineWidth`.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 3})).unwrap();
|
||||
assert_eq!(spec(&s, id).line_width, None);
|
||||
assert!(serde_json::to_value(spec(&s, id)).unwrap().get("lineWidth").is_none());
|
||||
assert!((height(&s) - 3.0).abs() < 1e-6, "{}", height(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_columns_keep_clear_of_the_legend_and_options_follow_the_graph_type() {
|
||||
let mut s = Session::new();
|
||||
@@ -7897,6 +7945,28 @@ fn recoloring_a_graph_keeps_its_axis_lines_paint() {
|
||||
assert!(!label_paint.is_empty() && label_paint.iter().all(|l| *l == ("#ffffff".to_string(), true)), "{label_paint:?}");
|
||||
}
|
||||
|
||||
/// Swap Fill and Stroke on an axis line keeps the swapped paint for every axis line and leaves the fill opacity the axis
|
||||
/// lines keep from another line, though the line swapped still shows 100%.
|
||||
#[test]
|
||||
fn swapping_an_axis_lines_paint_keeps_the_fill_opacity_its_kind_keeps() {
|
||||
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);
|
||||
let (first, second) = (lines[0].id, lines[1].id);
|
||||
s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#00ff00"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [first.0], "item": top_row(&s, first, true), "opacity": 40})).unwrap();
|
||||
let shown = s.doc().unwrap().doc.node(second).unwrap().appearance.fill().map(|f| f.opacity);
|
||||
assert!(shown.is_none_or(|o| o == 1.0), "the other lines show 100% until the graph is drawn again: {shown:?}");
|
||||
s.execute("paint.swap", &json!({"ids": [second.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
for n in line_nodes(&s, id) {
|
||||
let fill = n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity));
|
||||
assert!(fill.as_ref().is_some_and(|(c, o)| c.as_deref() == Some("#000000") && (*o - 0.4).abs() < 1e-6), "{fill:?}");
|
||||
assert!(n.appearance.stroke_paint().is_none(), "the swapped line had no fill, so the lines have no stroke");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke given the whole graph, or its Axes group, is kept for its axis lines.
|
||||
#[test]
|
||||
fn a_stroke_given_the_whole_graph_or_its_axes_group_is_kept_for_its_axis_lines() {
|
||||
@@ -8039,6 +8109,56 @@ fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke painted on an axis line after another axis line's stroke was set to None is kept for every axis line with
|
||||
/// the painted line's weight, not the zero weight the unpainted stroke left on its kind.
|
||||
#[test]
|
||||
fn a_stroke_painted_after_an_axis_line_lost_its_stroke_keeps_a_weight() {
|
||||
let cases = ["paint.setStroke", "addon.color.fillToStroke", "appearance.setItem"];
|
||||
every_case(cases, |cmd| {
|
||||
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);
|
||||
let weight = line_look(&lines[1]).1;
|
||||
assert!(weight > 0.0, "{cmd}: the line has a stroke weight: {weight}");
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "none": true})).unwrap();
|
||||
let b = lines[1].id.0;
|
||||
match *cmd {
|
||||
"paint.setStroke" => s.execute(cmd, &json!({"ids": [b], "color": "#ff0000"})).unwrap(),
|
||||
"addon.color.fillToStroke" => {
|
||||
s.execute("paint.setFill", &json!({"ids": [b], "color": "#ff0000"})).unwrap();
|
||||
s.execute(cmd, &json!({"ids": [b]})).unwrap()
|
||||
}
|
||||
_ => s.execute(cmd, &json!({"ids": [b], "index": top_row(&s, lines[1].id, false), "color": "#ff0000"})).unwrap(),
|
||||
};
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.1 - weight).abs() < 1e-9), "{cmd}: {looks:?}");
|
||||
});
|
||||
}
|
||||
|
||||
/// A zero stroke weight set together with a stroke color on an axis line is kept for every axis line as set, also when
|
||||
/// a stroke is painted on another axis line before the graph is drawn again.
|
||||
#[test]
|
||||
fn a_zero_weight_set_with_a_stroke_color_on_an_axis_line_is_kept() {
|
||||
every_case([false, true], |repaint| {
|
||||
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], "none": true})).unwrap();
|
||||
let at = top_row(&s, lines[1].id, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [lines[1].id.0], "index": at, "color": "#ff0000", "weight": 0})).unwrap();
|
||||
let color = if *repaint {
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[2].id.0], "color": "#0000ff"})).unwrap();
|
||||
"#0000ff"
|
||||
} else {
|
||||
"#ff0000"
|
||||
};
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == color && l.1 == 0.0), "repaint {repaint}: {looks:?}");
|
||||
});
|
||||
}
|
||||
|
||||
/// A reorder that leaves an axis line's rows as they were keeps what its kind keeps from another line and is no edit.
|
||||
#[test]
|
||||
fn a_reorder_that_changes_nothing_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
|
||||
@@ -9256,6 +9376,7 @@ fn graph_commands_refuse_params_of_the_wrong_type() {
|
||||
("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"),
|
||||
("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"),
|
||||
("filledLines", json!("on"), "`filledLines` must be true or false"),
|
||||
("lineWidth", json!("4"), "`lineWidth` must be a number, not \"4\""),
|
||||
("dropShadow", json!(1), "`dropShadow` must be true or false"),
|
||||
("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"),
|
||||
("type", json!(5), "`type` must be a string"),
|
||||
|
||||
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Crop Image",
|
||||
["Object"],
|
||||
None,
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
has_image,
|
||||
crop_image
|
||||
),
|
||||
@@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData {
|
||||
PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true))
|
||||
}
|
||||
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and
|
||||
/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or
|
||||
/// `r` not on the pixel grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> {
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when
|
||||
/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel
|
||||
/// grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> {
|
||||
let blob = doc.images.get(&im.key)?;
|
||||
let [a, b, c, d, _, _] = im.xf.as_coeffs();
|
||||
if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 {
|
||||
@@ -996,9 +996,85 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op
|
||||
return None;
|
||||
}
|
||||
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
|
||||
Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as
|
||||
/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive
|
||||
/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as
|
||||
/// Rasterize's.
|
||||
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<(f64, bool)>> {
|
||||
const C: &str = "object.cropImage";
|
||||
let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?;
|
||||
if !(1.0..=2400.0).contains(&ppi) {
|
||||
return Err(bad(C, "ppi must be between 1 and 2400"));
|
||||
}
|
||||
let (_, max) = vectorcraft_tools::cropimage::image_ppi(im);
|
||||
if ppi > max + 1e-6 {
|
||||
let max = (max * 100.0 + 1e-6).floor() / 100.0;
|
||||
return Err(bad(C, format!("ppi can't be more than {max} for this image")));
|
||||
}
|
||||
// An image whose pixels are not square is resampled on both sides, even at its denser side's resolution.
|
||||
Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6))))
|
||||
}
|
||||
|
||||
/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and
|
||||
/// no side past the renderer's).
|
||||
fn check_crop_size(w: f64, h: f64) -> Result<()> {
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
if w * h > MAX_PIXELS || w > side || h > side {
|
||||
let (w, h) = (w as u64, h as u64);
|
||||
return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully
|
||||
/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in
|
||||
/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when
|
||||
/// the working copies would not fit ([`check_resample_size`]).
|
||||
fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result<image::RgbaImage> {
|
||||
check_resample_size(img.width(), img.height(), w, h)?;
|
||||
let mut pre = image::ImageBuffer::<image::Rgba<u16>, Vec<u16>>::new(img.width(), img.height());
|
||||
for (d, s) in pre.pixels_mut().zip(img.pixels()) {
|
||||
let a = u32::from(s[3]);
|
||||
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
|
||||
// c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted.
|
||||
*dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16;
|
||||
}
|
||||
d.0[3] = (a * 257) as u16;
|
||||
}
|
||||
let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3);
|
||||
let mut res = image::RgbaImage::new(out.width(), out.height());
|
||||
for (d, s) in res.pixels_mut().zip(out.pixels()) {
|
||||
let a = u64::from(s[3]);
|
||||
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
|
||||
// c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a.
|
||||
*dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8;
|
||||
}
|
||||
d.0[3] = ((a + 128) / 257).min(255) as u8;
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and
|
||||
/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes
|
||||
/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`).
|
||||
pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> {
|
||||
let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h));
|
||||
let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12));
|
||||
if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC {
|
||||
return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` as PNG bytes.
|
||||
fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> {
|
||||
let mut png = Vec::new();
|
||||
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1014,9 +1090,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if switch_or(p, "trim", false, C)? {
|
||||
if p.get("ppi").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
|
||||
}
|
||||
return trim_image(s, id, (**im).clone());
|
||||
}
|
||||
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
|
||||
let asked = crop_resolution(p, im)?;
|
||||
// The resolution the image's pixels are resampled to when they are cut straight.
|
||||
let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t));
|
||||
let rect = match p.get("rect").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) if a.len() == 4 => {
|
||||
let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
|
||||
@@ -1038,16 +1120,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Err(bad(C, "crop rectangle doesn't overlap the image"));
|
||||
}
|
||||
if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 {
|
||||
// A box over the whole image still resamples it to a new resolution.
|
||||
let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6;
|
||||
// A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image.
|
||||
let [_, xb, xc, _, _, _] = im.xf.as_coeffs();
|
||||
let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9;
|
||||
if whole && target.is_none() && (asked.is_none() || !turned) {
|
||||
return Err(bad(C, "nothing to crop"));
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled.
|
||||
if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
put_pixels(s, id, png, cw, ch, xf)?;
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a
|
||||
// resolution is asked for.
|
||||
if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
let (cut, xf) = match target {
|
||||
Some(t) => {
|
||||
let (cw, ch) = cut.dimensions();
|
||||
let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&cut, w, h)?;
|
||||
(resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h)))
|
||||
}
|
||||
None => (cut, xf),
|
||||
};
|
||||
let (cw, ch) = cut.dimensions();
|
||||
put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?;
|
||||
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
|
||||
}
|
||||
// Keep the image's pixel density.
|
||||
let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
// A drawn crop is made at a resolution asked for even when it is the image's own: the box of a
|
||||
// turned or skewed image holds fewer of its pixels a point than the image does.
|
||||
let target = asked.map(|(t, _)| t);
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more
|
||||
// than the image's own, measured on its pixel grid however it is turned, nor past the size a
|
||||
// drawing may have), and resampled to it.
|
||||
let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
let scale = target.map_or(native, |t| {
|
||||
let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0);
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9));
|
||||
(2.0 * t).min(own).min(budget).max(t.min(own))
|
||||
});
|
||||
let mut bare = node.clone();
|
||||
bare.opacity = 1.0;
|
||||
bare.blend = Default::default();
|
||||
@@ -1058,23 +1173,41 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(e) = bare.extras_if_any() {
|
||||
e.color_mask = None;
|
||||
}
|
||||
let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0));
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale);
|
||||
// At a resolution asked for, the drawing is fitted to the box below: the image is stretched
|
||||
// about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn.
|
||||
if target.is_some()
|
||||
&& let NodeKind::Image(bi) = &mut bare.kind
|
||||
{
|
||||
let o = r.origin().to_vec2();
|
||||
bi.xf = Affine::translate(o)
|
||||
* Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height())
|
||||
* Affine::translate(-o)
|
||||
* bi.xf;
|
||||
}
|
||||
let tmp = isolated_doc(&st.doc, vec![bare]);
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
|
||||
let (png, w, h, warning) =
|
||||
render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?;
|
||||
// At a resolution asked for, the drawing is resampled to the box's size at that resolution and
|
||||
// fitted to the box, so the image keeps its size.
|
||||
let (png, w, h, xf) = match target {
|
||||
Some(t) => {
|
||||
let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8();
|
||||
// Only the decoded pixels are held while they are resampled.
|
||||
drop(png);
|
||||
let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&drawn, tw, th)?;
|
||||
let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th));
|
||||
(encode_png(&resized)?, tw, th, xf)
|
||||
}
|
||||
None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)),
|
||||
};
|
||||
s.edit("Crop Image", |d, _| {
|
||||
let key = unique_key(d, "crop");
|
||||
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: w,
|
||||
height: h,
|
||||
xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
}));
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Align",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
|
||||
has_selection_or_guides,
|
||||
align
|
||||
),
|
||||
|
||||
@@ -166,15 +166,18 @@ const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
|
||||
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
|
||||
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
|
||||
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
|
||||
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
|
||||
/// A document without pixel-aligned symbols is not walked.
|
||||
/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by
|
||||
/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked.
|
||||
fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was = before.pixel_aligned_symbols();
|
||||
// The symbol whose editing mode this edit ended, if any.
|
||||
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned);
|
||||
let mut every = false;
|
||||
for name in &aligned {
|
||||
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
@@ -184,22 +187,29 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
_ => true,
|
||||
};
|
||||
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
|
||||
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
|
||||
if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed {
|
||||
snap_symbol_art(doc, name);
|
||||
every = true;
|
||||
}
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
// The symbol editing layer holds another symbol's art.
|
||||
let editing = doc.symbol_edit.as_ref().map(|e| e.layer);
|
||||
if every {
|
||||
for layer in doc.layers.iter_mut() {
|
||||
if holds_instance(layer, &natural) {
|
||||
if Some(layer.id) != editing && holds_instance(layer, &natural) {
|
||||
snap_instances_in(Arc::make_mut(layer), &natural);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
if let Some(layer) = editing {
|
||||
let outside = |layers: &[Arc<Node>]| layers.iter().filter(|l| l.id != layer).cloned().collect::<Vec<_>>();
|
||||
changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked);
|
||||
} else {
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
}
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
snap_instance(n, &natural);
|
||||
@@ -358,9 +368,10 @@ fn snap_mask(n: &mut Node) -> bool {
|
||||
|
||||
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
|
||||
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
|
||||
/// rotated (a half turn included) or sheared instance stays where it is.
|
||||
/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any
|
||||
/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it.
|
||||
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return };
|
||||
let Some(nat) = natural.get(symbol.as_str()) else { return };
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let [na, _, _, nd, _, _] = nat.as_coeffs();
|
||||
@@ -373,7 +384,12 @@ fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
return;
|
||||
}
|
||||
let (x, y) = (e.round(), f.round());
|
||||
if x != e || y != f {
|
||||
if x == e && y == f {
|
||||
return;
|
||||
}
|
||||
n.transform(Affine::translate((x - e, y - f)), Scaling::default());
|
||||
// Whole points exactly, which adding the offset to the old position need not give.
|
||||
if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind {
|
||||
*xf = Affine::new([a, b, c, d, x, y]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -113,6 +113,30 @@ thread_local! {
|
||||
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
|
||||
}
|
||||
let data =
|
||||
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
|
||||
vectorcraft_format::load(&data?).ok()
|
||||
}
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
|
||||
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
|
||||
/// relative path taken from the file's folder): the copy would name it.
|
||||
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
@@ -291,6 +315,7 @@ impl<'a> Collector<'a> {
|
||||
// read from its editing data links are copied beside it.
|
||||
let pages = placed.get(&file.path);
|
||||
let placed_file = pages.is_some();
|
||||
check_carried_scripts(&file.name, &bytes, found_path)?;
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
@@ -471,6 +496,8 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let given_name = text_param(p, "name", C)?;
|
||||
let folder = text_param(p, "folder", C)?;
|
||||
let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?;
|
||||
// Before anything is collected or written, here where the request's read roots are in force.
|
||||
super::fileio::check_linked_scripts(C, "vectorcraft", s.doc()?, &Value::Null)?;
|
||||
let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
|
||||
let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string);
|
||||
if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swap Fill and Stroke",
|
||||
[],
|
||||
Some("Shift+X"),
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters 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 (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
swap
|
||||
),
|
||||
|
||||
@@ -45,6 +45,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.commonTangents",
|
||||
"addon.pathtools.corner",
|
||||
"addon.pathtools.cornerRemove",
|
||||
"addon.pathtools.cornerSet",
|
||||
@@ -704,8 +705,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, run
|
||||
/// plug-ins again, or read a file and report where it is on disk.
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
|
||||
/// report where it is on disk.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
@@ -718,5 +720,6 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"object.pathfinder.options",
|
||||
"stroke.arrowheads.edit",
|
||||
"stroke.arrowheads.list",
|
||||
"text.similarFonts",
|
||||
"type.compositeFonts.set",
|
||||
];
|
||||
@@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 {
|
||||
(doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0)
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or
|
||||
/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints
|
||||
/// nothing, when the area it covers overflows `f64` or the scale is not positive.
|
||||
fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> {
|
||||
// What it paints (its members' effects included), and how far its fills' and strokes' raster
|
||||
// effects reach beyond that.
|
||||
let b = vectorcraft_render::painted_bounds(out, whole)?;
|
||||
let look = out.raster_effects.clone();
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let b = vectorcraft_render::painted_bounds(d, whole)?;
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around;
|
||||
let b = b.inflate(reach, reach);
|
||||
// An area too large for f64 gives a zero scale and an image transform that is not finite.
|
||||
let area = b.width() * b.height();
|
||||
@@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N
|
||||
return None;
|
||||
}
|
||||
let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale);
|
||||
Some((region, scale))
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
let (region, scale) = effect_region(out, whole, scale)?;
|
||||
let look = out.raster_effects.clone();
|
||||
// Anti-alias off: hard edges (the effects themselves stay smooth).
|
||||
let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None };
|
||||
let mut img = render(out, vec![whole.clone()], region, scale, anti_alias);
|
||||
@@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
if !below && let Some(image) = rasterize_effect_image(d, n) {
|
||||
return Some(image);
|
||||
}
|
||||
let whole = effect_art(n, below, members);
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
effect_image(d, &whole, bare.as_ref(), image_scale(d, n))
|
||||
}
|
||||
|
||||
/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`:
|
||||
/// `n` without its transparency, a group's or layer's members without their raster effects when
|
||||
/// both are set.
|
||||
fn effect_art(n: &Node, below: bool, members: bool) -> Node {
|
||||
let mut whole = n.clone();
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
@@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
strip_raster(Arc::make_mut(c), true);
|
||||
}
|
||||
}
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
// A Rasterize effect at a finer resolution than the document's is rendered at its own.
|
||||
let scale = raster_fx(n)
|
||||
.iter()
|
||||
.filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None })
|
||||
.fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0));
|
||||
effect_image(d, &whole, bare.as_ref(), scale)
|
||||
whole
|
||||
}
|
||||
|
||||
/// Pixels per point of the image of the raster effects of `n`: the document's raster effects
|
||||
/// resolution, or a Rasterize effect's finer one, which is rendered at its own.
|
||||
fn image_scale(d: &Document, n: &Node) -> f64 {
|
||||
raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0))
|
||||
}
|
||||
|
||||
/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below`
|
||||
/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the
|
||||
/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]);
|
||||
/// 0 when it paints nothing.
|
||||
pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 {
|
||||
if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) {
|
||||
// Measured as Object › Rasterize measures it.
|
||||
let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0;
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| {
|
||||
let b = b.inflate(r.add_around, r.add_around);
|
||||
((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0))
|
||||
});
|
||||
// Past Object › Rasterize's limits that image is not made, and the effect's image is.
|
||||
if let Some((w, h)) = size
|
||||
&& w * h <= super::menucmds::MAX_PIXELS
|
||||
&& w <= side
|
||||
&& h <= side
|
||||
{
|
||||
return (w * h) as u64;
|
||||
}
|
||||
}
|
||||
effect_region(d, &effect_art(n, below, members), image_scale(d, n))
|
||||
.map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64)
|
||||
}
|
||||
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
@@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
"clippingMask": r.clipping_mask,
|
||||
"addAround": r.add_around,
|
||||
});
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some((_, map)) = staged {
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
/// image takes its place with its id, name and transparency (a layer keeps the image as its only
|
||||
/// member).
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and 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, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and 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, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1384,6 +1384,9 @@ struct Row {
|
||||
tint: f32,
|
||||
/// The row's own `model`, which takes the place of the command's for its colors.
|
||||
model: Option<ModelRule>,
|
||||
/// `added`: with no current colors, the new color is a color added to the group, which it
|
||||
/// joins after the colors of the rows with current colors.
|
||||
added: bool,
|
||||
}
|
||||
|
||||
/// The color model a row's colors take (`model`): each color's own, the new color's, or the
|
||||
@@ -1437,9 +1440,10 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
|
||||
};
|
||||
let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}")));
|
||||
match p.get("map") {
|
||||
Some(Value::Object(m)) => {
|
||||
m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None })).collect()
|
||||
}
|
||||
Some(Value::Object(m)) => m
|
||||
.iter()
|
||||
.map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false }))
|
||||
.collect(),
|
||||
Some(Value::Array(rows)) => rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
@@ -1450,7 +1454,8 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
|
||||
};
|
||||
let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let model = ModelRule::param(r, cmd)?;
|
||||
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model })
|
||||
let added = switch_or(r, "added", false, cmd)?;
|
||||
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added })
|
||||
})
|
||||
.collect(),
|
||||
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
|
||||
@@ -1487,6 +1492,10 @@ struct ColorMap {
|
||||
group: Vec<GroupSwatch>,
|
||||
keys: HashMap<ColorKey, usize>,
|
||||
hexes: HashMap<String, usize>,
|
||||
/// The current colors of the rows whose new color was removed (`to: null`, not excluded),
|
||||
/// which keep their colors.
|
||||
removed_keys: std::collections::HashSet<ColorKey>,
|
||||
removed_hexes: std::collections::HashSet<String>,
|
||||
/// Set when a colour took a new colour of another model in its own model.
|
||||
converted: std::cell::Cell<bool>,
|
||||
/// The Global Adjust every mapped colour takes after its row's new colour.
|
||||
@@ -1505,11 +1514,23 @@ impl ColorMap {
|
||||
group,
|
||||
keys: HashMap::new(),
|
||||
hexes: HashMap::new(),
|
||||
removed_keys: Default::default(),
|
||||
removed_hexes: Default::default(),
|
||||
converted: Default::default(),
|
||||
adjust,
|
||||
};
|
||||
for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) {
|
||||
let Some(to) = r.new_color() else { continue };
|
||||
let Some(to) = r.new_color() else {
|
||||
if !r.exclude {
|
||||
for m in &r.from {
|
||||
match m {
|
||||
Match::Key(k) => out.removed_keys.insert(*k),
|
||||
Match::Hex(h) => out.removed_hexes.insert(h.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let i = out.rows.len();
|
||||
let colors: Vec<Color> = r.from.iter().map(Match::color).collect();
|
||||
let link = links.get(n).cloned().flatten();
|
||||
@@ -1550,9 +1571,18 @@ impl ColorMap {
|
||||
/// the row gives it the new color in that color's model and the Global Adjust gives it the
|
||||
/// swatch's new color at that tint;
|
||||
/// other rows map the colour, which loses its link when it changes or when the group's rewrite
|
||||
/// would change it. True when anything changed.
|
||||
/// would change it; a color of a row whose new color was removed keeps its color and loses its
|
||||
/// link to a swatch of the group whose rewrite would change it. True when anything changed.
|
||||
fn map_link(&self, c: &mut Color, link: &mut Option<String>, tint: &mut f32) -> bool {
|
||||
let Some(i) = self.row_of(*c) else { return false };
|
||||
let Some(i) = self.row_of(*c) else {
|
||||
let removed = self.removed_keys.contains(&ColorKey::of(c)) || self.removed_hexes.contains(&c.to_hex());
|
||||
let rewritten = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)).is_some_and(|g| g.shown.tinted(*tint) != *c);
|
||||
if removed && rewritten {
|
||||
*link = None;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
let (Some(row), Some(l)) = (self.rows.get(i), self.links.get(i)) else { return false };
|
||||
if l.is_none()
|
||||
&& let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n))
|
||||
@@ -1650,18 +1680,27 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
let new: Vec<Color> = match group_colors {
|
||||
// A null in groupColors removes the group's swatch at its place.
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| {
|
||||
color_value(v)
|
||||
.map(|v| match v {
|
||||
Value::Null => Ok(None),
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))
|
||||
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors")))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))),
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
// A row with no current colors gives the group no color.
|
||||
None => rows.iter().filter(|r| !r.from.is_empty()).filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
|
||||
// A row with no current colors gives the group no color, unless it is a color added to
|
||||
// the group: those follow the colors of the rows with current colors.
|
||||
None => rows
|
||||
.iter()
|
||||
.filter(|r| !r.from.is_empty())
|
||||
.chain(rows.iter().filter(|r| r.from.is_empty() && r.added))
|
||||
.filter_map(Row::new_color)
|
||||
.map(|c| Some(mapped_adjust.apply(c)))
|
||||
.collect(),
|
||||
};
|
||||
let rename = text_param(p, "rename", C)?;
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
@@ -1696,7 +1735,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.zip(&new)
|
||||
.filter(|(w, _)| w.global && !w.is_reserved())
|
||||
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: *c, shown: d.linked_color(*c, w.spot) })
|
||||
.filter_map(|(w, c)| Some((w, (*c)?)))
|
||||
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: c, shown: d.linked_color(c, w.spot) })
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
@@ -1779,6 +1819,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(m) = model {
|
||||
row["model"] = json!(m.id());
|
||||
}
|
||||
if r.added {
|
||||
row["added"] = json!(true);
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -82,19 +82,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cancel Key Object",
|
||||
[],
|
||||
None,
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)",
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; a click without modifiers on an already-selected anchor point makes it the key anchor)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)",
|
||||
has_doc,
|
||||
key
|
||||
),
|
||||
cmd!(
|
||||
"select.anchors",
|
||||
"Select Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)",
|
||||
has_doc,
|
||||
anchors
|
||||
),
|
||||
cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors),
|
||||
cmd!(
|
||||
"select.segments",
|
||||
"Select Segments",
|
||||
@@ -734,17 +726,32 @@ fn key_anchor(s: &mut Session, id: Option<NodeId>, guide: Option<usize>, v: &Val
|
||||
let st = s.doc()?;
|
||||
let sel = &st.selection;
|
||||
let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len()));
|
||||
if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) {
|
||||
let is_selected_anchor = on_path
|
||||
&& !sel.segments.contains_key(&id)
|
||||
&& (sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) || (!sel.anchors.contains_key(&id) && sel.contains(id)));
|
||||
if !is_selected_anchor {
|
||||
return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1)));
|
||||
}
|
||||
// Check the new key on a copy first, so a request that fails leaves the key as it was.
|
||||
let mut trial = sel.clone();
|
||||
if !trial.anchors.contains_key(&id)
|
||||
&& let Some(p) = st.doc.node(id).and_then(|n| n.path_data())
|
||||
{
|
||||
trial.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect());
|
||||
}
|
||||
trial.key_anchor = Some((id, r));
|
||||
trial.prune(&st.doc);
|
||||
if trial.key_anchor.is_none() {
|
||||
return Err(bad(C, "select another anchor point to align to the key anchor"));
|
||||
}
|
||||
s.select(|_, sel| sel.key_anchor = Some((id, r)))?;
|
||||
s.select(|d, sel| {
|
||||
if !sel.anchors.contains_key(&id)
|
||||
&& let Some(p) = d.node(id).and_then(|n| n.path_data())
|
||||
{
|
||||
sel.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect());
|
||||
}
|
||||
sel.key_anchor = Some((id, r));
|
||||
})?;
|
||||
key_result(s)
|
||||
}
|
||||
|
||||
@@ -891,23 +898,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) {
|
||||
e.extend(path.anchors().map(|(s, i, _)| (s, i)));
|
||||
}
|
||||
// One point that add or toggle selects becomes the key anchor (a Shift-click with Direct
|
||||
// Selection); `prune` drops it unless another point is selected too.
|
||||
let single = refs.len() == 1;
|
||||
let mut newest = None;
|
||||
for r in refs {
|
||||
if mode == "toggle" && e.contains(&r) {
|
||||
e.remove(&r);
|
||||
} else if e.insert(r) && single {
|
||||
newest = Some(r);
|
||||
} else {
|
||||
e.insert(r);
|
||||
}
|
||||
}
|
||||
if e.is_empty() {
|
||||
sel.remove(id);
|
||||
} else if mode != "set"
|
||||
&& let Some(r) = newest
|
||||
{
|
||||
sel.key_anchor = Some((id, r));
|
||||
}
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -7,17 +7,20 @@
|
||||
//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All
|
||||
//! (`text.spelling.ignoreAll`) skips a word in the active document only.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_proof::{IssueKind, Options, ProofLang};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::menucmds::whole_or;
|
||||
use super::textedit::text_mut;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::typemenu::{all_texts, text_ids};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
|
||||
/// Most unknown words one check lists; past it the result says `more`.
|
||||
pub const MAX_WORDS: usize = 10_000;
|
||||
@@ -36,10 +39,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Spelling",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one",
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
cmd!(
|
||||
"text.spelling.change",
|
||||
"Change All",
|
||||
[],
|
||||
None,
|
||||
"{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}",
|
||||
has_doc,
|
||||
change_words
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.suggest",
|
||||
"Spelling Suggestions",
|
||||
@@ -107,22 +119,42 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked
|
||||
/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them.
|
||||
/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at
|
||||
/// `from` when it is given.
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.check";
|
||||
// Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than
|
||||
// a check of the whole document.
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
let mut ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)),
|
||||
None => all_texts(&s.doc()?.doc),
|
||||
};
|
||||
let max = whole_or(p, "max", MAX_WORDS as u64, C)?;
|
||||
let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?;
|
||||
let st = s.doc()?;
|
||||
// Where the last check stopped: the objects before it are skipped, and the bytes of its object
|
||||
// before `byte`.
|
||||
let mut from_byte = 0;
|
||||
if let Some(from) = p.get("from").filter(|v| !v.is_null()) {
|
||||
let (id, byte) = from_param(from, C)?;
|
||||
let Some(pos) = ids.iter().position(|i| i.0 == id) else {
|
||||
return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked")));
|
||||
};
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else {
|
||||
return Err(bad(C, format!("`from.id` {id} is not a type object")));
|
||||
};
|
||||
let len = t.plain_text().len();
|
||||
from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?;
|
||||
ids.drain(..pos);
|
||||
}
|
||||
let mut words = vec![];
|
||||
let mut more = false;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = t.plain_text();
|
||||
let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len());
|
||||
// Only the first object listed starts part way.
|
||||
let from = std::mem::take(&mut from_byte);
|
||||
let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len());
|
||||
for m in found {
|
||||
let Some(word) = text.get(m.range.clone()) else { continue };
|
||||
words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() }));
|
||||
@@ -135,6 +167,87 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "words": words, "more": more }))
|
||||
}
|
||||
|
||||
/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers.
|
||||
fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> {
|
||||
let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) };
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) {
|
||||
return Err(bad(command, format!("`from` takes id and byte, not `{k}`")));
|
||||
}
|
||||
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?;
|
||||
let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?;
|
||||
Ok((id, byte))
|
||||
}
|
||||
|
||||
/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words
|
||||
/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out
|
||||
/// once at the end rather than once for each word.
|
||||
fn change_words(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.change";
|
||||
let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string();
|
||||
let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?;
|
||||
let mut by_id: BTreeMap<NodeId, Vec<(usize, usize)>> = BTreeMap::new();
|
||||
for w in list {
|
||||
let (id, start, end) = word_param_range(w, C)?;
|
||||
by_id.entry(NodeId(id)).or_default().push((start, end));
|
||||
}
|
||||
// Every word checked against its object before anything changes.
|
||||
let st = s.doc()?;
|
||||
for (id, ranges) in &mut by_id {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else {
|
||||
return Err(bad(C, format!("{} is not a type object", id.0)));
|
||||
};
|
||||
let text = t.plain_text();
|
||||
ranges.sort_unstable();
|
||||
let mut last_end = 0;
|
||||
for &(a, b) in ranges.iter() {
|
||||
if a >= b || text.get(a..b).is_none() {
|
||||
return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0)));
|
||||
}
|
||||
if a < last_end {
|
||||
return Err(bad(C, format!("words of {} overlap at byte {a}", id.0)));
|
||||
}
|
||||
last_end = b;
|
||||
}
|
||||
// A word that already reads as `to` is left alone, so a list of only those makes no edit.
|
||||
ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str()));
|
||||
}
|
||||
by_id.retain(|_, ranges| !ranges.is_empty());
|
||||
let changed: usize = by_id.values().map(Vec::len).sum();
|
||||
if changed == 0 {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
s.edit("Change All", |d, _| {
|
||||
for (id, ranges) in &by_id {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
for &(a, b) in ranges.iter().rev() {
|
||||
// Paragraph styles and ruby follow each edit, as in `text.editRange`.
|
||||
t.splice_paras(a, b, &to);
|
||||
edit::replace_range(&mut t.runs, a, b, &to);
|
||||
t.ruby_after_replace(a, b, to.len());
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers.
|
||||
fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> {
|
||||
let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) };
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) {
|
||||
return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`")));
|
||||
}
|
||||
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?;
|
||||
let byte = |k: &str| {
|
||||
o.get(k)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|b| usize::try_from(b).ok())
|
||||
.ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number")))
|
||||
};
|
||||
Ok((id, byte("start")?, byte("end")?))
|
||||
}
|
||||
|
||||
/// One word of a type object its dictionaries don't know ([`misspellings`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Misspelling {
|
||||
@@ -149,6 +262,13 @@ pub struct Misspelling {
|
||||
/// All words). At most `max` of them; the flag says the list was cut short there. What
|
||||
/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines.
|
||||
pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
misspellings_from(t, ignored, 0, max)
|
||||
}
|
||||
|
||||
/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at
|
||||
/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since
|
||||
/// craft-proof reads a paragraph's language from all of it.
|
||||
pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
let text = t.plain_text();
|
||||
// Each run in its own language, at its bytes of the plain text.
|
||||
let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len());
|
||||
@@ -166,6 +286,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
|
||||
let mut para_start = 0;
|
||||
for para in text.split('\n') {
|
||||
let para_end = para_start + para.len();
|
||||
// No word of a paragraph that ends at `from` starts there or later.
|
||||
if para_end <= from {
|
||||
para_start = para_end + 1;
|
||||
continue;
|
||||
}
|
||||
let para_spans: Vec<(Range<usize>, ProofLang)> = spans
|
||||
.iter()
|
||||
.filter_map(|(r, lang)| {
|
||||
@@ -178,6 +303,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (para_start + issue.start, para_start + issue.end);
|
||||
if start < from {
|
||||
continue;
|
||||
}
|
||||
let Some(word) = text.get(start..end) else { continue };
|
||||
if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) {
|
||||
continue;
|
||||
|
||||
@@ -1255,43 +1255,54 @@ impl GroupEdit {
|
||||
}
|
||||
|
||||
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
|
||||
/// names, kinds and global or spot flags), extra colours are added as new swatches and swatches
|
||||
/// past the end are removed. Paints linked to its global swatches follow (a removed swatch's are
|
||||
/// unlinked); `rename` renames the group. A built-in swatch (None, Registration) it would change or
|
||||
/// remove is refused.
|
||||
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
|
||||
/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors
|
||||
/// are added as new swatches and swatches past the end are removed. Paints linked to its global
|
||||
/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch
|
||||
/// (None, Registration) it would change or remove is refused.
|
||||
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
|
||||
let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?;
|
||||
let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) {
|
||||
Some(n) => d.free_swatch_name(n),
|
||||
None => group.to_string(),
|
||||
};
|
||||
let old = &d.swatch_groups[gi].swatches;
|
||||
if let Some(w) = old.iter().enumerate().find(|(i, w)| w.is_reserved() && colors.get(*i).is_none_or(|c| w.paint.color() != Some(*c))).map(|x| x.1)
|
||||
if let Some(w) = old
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c)))
|
||||
.map(|x| x.1)
|
||||
{
|
||||
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
|
||||
}
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let mut relinks = vec![];
|
||||
let mut swatches = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
for gone in swatches.split_off(colors.len().min(swatches.len())) {
|
||||
if gone.global {
|
||||
relinks.push(Relink { from: gone.name.clone(), to: gone.name, color: None, keep: false });
|
||||
let old = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
let old_len = old.len();
|
||||
// The swatches that stay, each with its new color.
|
||||
let mut kept: Vec<(Swatch, Color)> = vec![];
|
||||
for (i, w) in old.into_iter().enumerate() {
|
||||
match colors.get(i).copied().flatten() {
|
||||
Some(c) => kept.push((w, c)),
|
||||
None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
for (w, c) in swatches.iter_mut().zip(colors) {
|
||||
if w.paint.color() != Some(*c) {
|
||||
let mut swatches = Vec::with_capacity(kept.len());
|
||||
for (mut w, c) in kept {
|
||||
if w.paint.color() != Some(c) {
|
||||
// A tint swatch becomes a colour of its own.
|
||||
w.paint = Paint::solid(*c);
|
||||
w.paint = Paint::solid(c);
|
||||
if w.global {
|
||||
// Art linked to a Lab spot shows it as the Spot Colors options say.
|
||||
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(*c, w.spot)), keep: true });
|
||||
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(c, w.spot)), keep: true });
|
||||
}
|
||||
}
|
||||
swatches.push(w);
|
||||
}
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
swatches.iter().for_each(|w| free.insert(&w.name));
|
||||
for c in colors.iter().skip(swatches.len()) {
|
||||
for c in colors.iter().skip(old_len).flatten() {
|
||||
let nm = free.take(&color_name(*c));
|
||||
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
|
||||
}
|
||||
@@ -1320,6 +1331,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let colors: Vec<Color> =
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let rename = str_param(p, "rename");
|
||||
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
|
||||
@@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
|
||||
let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) {
|
||||
None => return Ok(()),
|
||||
Some(b) => match art_of(before) {
|
||||
Some(old) if same(&old) => return Ok(()),
|
||||
// Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped.
|
||||
Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()),
|
||||
old => (old.unwrap_or_default(), b.group),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -197,6 +197,7 @@ mod symbol_nine_slice;
|
||||
mod symbolbounds;
|
||||
mod symboledit;
|
||||
mod symbollib;
|
||||
mod tangent_line;
|
||||
mod targeting;
|
||||
mod textcombos;
|
||||
mod textedit;
|
||||
|
||||
@@ -468,7 +468,7 @@ fn styles_symbols_and_images_of_the_same_name_are_renamed() {
|
||||
assert_eq!(key(&s, img2), src_key);
|
||||
}
|
||||
|
||||
/// A graph whose series fill, value labels and legend rows paint with global swatch "Brand" and
|
||||
/// A graph whose series fill, value labels, legend rows and axis and ring line rows paint with global swatch "Brand" and
|
||||
/// whose value labels are set in character style "Emphasis" and paragraph style "Body", as a
|
||||
/// later redraw would give them to its marks and labels.
|
||||
fn styled_graph(s: &mut Session) -> NodeId {
|
||||
@@ -484,8 +484,9 @@ fn styled_graph(s: &mut Session) -> NodeId {
|
||||
let l = &mut g.label_styles;
|
||||
l.values = Some(vectorcraft_doc::CharStyle { fill: brand.clone(), style_name: Some("Emphasis".into()), ..Default::default() });
|
||||
l.values_para = Some(vectorcraft_doc::ParaStyle { style_name: Some("Body".into()), ..Default::default() });
|
||||
let rows = vectorcraft_doc::SeriesPaint { stroke: Some(brand), ..Default::default() };
|
||||
l.legend_rows = Some(vectorcraft_doc::graph::LabelRows { paint: rows, ..Default::default() });
|
||||
let paint = vectorcraft_doc::SeriesPaint { stroke: Some(brand), ..Default::default() };
|
||||
let rows = vectorcraft_doc::graph::LabelRows { paint, ..Default::default() };
|
||||
(l.legend_rows, l.axis_rows, l.ring_rows) = (Some(rows.clone()), Some(rows.clone()), Some(rows));
|
||||
id
|
||||
}
|
||||
|
||||
@@ -515,7 +516,7 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() {
|
||||
let d = doc(&s);
|
||||
assert!(d.swatch("Brand").is_some(), "{v}");
|
||||
assert!(d.char_styles.iter().any(|x| x.name == "Emphasis") && d.para_styles.iter().any(|x| x.name == "Body"), "{v}");
|
||||
let brand = vec!["Brand".to_string(); 3];
|
||||
let brand = vec!["Brand".to_string(); 5];
|
||||
assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand.clone(), Some("Emphasis".into()), Some("Body".into())));
|
||||
|
||||
// Into a document that gives each name something else: they come in renamed.
|
||||
@@ -524,15 +525,15 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() {
|
||||
s.execute("charStyle.new", &json!({"name": "Emphasis", "attrs": {"size": 8.0}})).unwrap();
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"space_after": 2.0}})).unwrap();
|
||||
let v = s.execute("edit.pasteInPlace", &json!({"swatchConflict": "add"})).unwrap();
|
||||
let brand2 = vec!["Brand 2".to_string(); 3];
|
||||
let brand2 = vec!["Brand 2".to_string(); 5];
|
||||
assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand2, Some("Emphasis 2".into()), Some("Body 2".into())), "{v}");
|
||||
|
||||
// Without formatting: the labels' text styles stay behind.
|
||||
new_doc(&mut s);
|
||||
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
|
||||
assert!(doc(&s).char_styles.is_empty() && doc(&s).para_styles.is_empty(), "{v}");
|
||||
// The value labels' red characters stay behind too; the series fill and the legend rows keep Brand.
|
||||
assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 2], None, None));
|
||||
// The value labels' red characters stay behind too; the series fill, the legend rows and the line rows keep Brand.
|
||||
assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 4], None, None));
|
||||
}
|
||||
|
||||
/// Each label of graph `id` (the text of its Axes and Legend groups) with its size and its first paragraph's format.
|
||||
@@ -596,8 +597,8 @@ fn a_graph_pasted_without_formatting_keeps_plain_labels_when_drawn_again() {
|
||||
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
|
||||
let off = [r.x0 - plot.x0 - 10.0, r.y0 - plot.y0 - 20.0, r.x1 - plot.x1 - 10.0, r.y1 - plot.y1 - 20.0];
|
||||
assert!(off.iter().all(|d| d.abs() < 1e-6), "the plot moves by the offset and keeps its size: {plot:?} → {r:?}");
|
||||
s.execute("graph.setType", &json!({"id": p.0, "type": "column"})).unwrap();
|
||||
assert_eq!(graph_label_looks(&s, p), pasted, "a change of type draws them the same way");
|
||||
s.execute("graph.setType", &json!({"id": p.0, "type": "column", "dropShadow": true})).unwrap();
|
||||
assert_eq!(graph_label_looks(&s, p), pasted, "a change of graph type options draws them the same way");
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
@@ -1504,9 +1504,76 @@ fn the_eraser_tip_takes_its_angle_and_roundness() {
|
||||
// At 45°, half axes 10 and 2.5: the band is 2·√((10² + 2.5²) / 2), about 14.58 pt, and the
|
||||
// chord 2 / √(0.5 / 10² + 0.5 / 2.5²), about 6.86 pt.
|
||||
close(erase(json!({"angle": 45, "roundness": 25})), 2.0 * ((100.0f64 + 6.25) / 2.0).sqrt(), 2.0 / (0.5f64 / 100.0 + 0.5 / 6.25).sqrt());
|
||||
// A roundness past 100 is kept to 100, and one below 1 to 1.
|
||||
close(erase(json!({"angle": 90, "roundness": 400})), 20.0, 20.0);
|
||||
close(erase(json!({"angle": 90, "roundness": 0})), 0.2, 0.2);
|
||||
// The ends of the Roundness range: 100% is round, and 1% leaves a tip 0.2 pt across.
|
||||
close(erase(json!({"angle": 90, "roundness": 100})), 20.0, 20.0);
|
||||
close(erase(json!({"angle": 90, "roundness": 1})), 0.2, 0.2);
|
||||
}
|
||||
|
||||
/// The Eraser refuses an `angle` outside -180 to 180 degrees and a `roundness` outside 1 to 100%,
|
||||
/// naming the key and the range, and erases nothing. The ends of each range erase, and a key left
|
||||
/// out or null takes its default: 0 degrees and 100%.
|
||||
#[test]
|
||||
fn the_eraser_refuses_an_angle_or_roundness_outside_its_range() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let stroke = json!({"points": [[90, 150], [210, 150]], "size": 10});
|
||||
for angle in [json!(-181), json!(-180.001), json!(180.001), json!(200), json!(1e300), json!(-1e300)] {
|
||||
refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": angle})), "`angle` must be from -180 to 180 degrees");
|
||||
}
|
||||
for roundness in [json!(0), json!(0.999), json!(-25), json!(100.001), json!(400), json!(1e300)] {
|
||||
refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"roundness": roundness})), "`roundness` must be from 1 to 100%");
|
||||
}
|
||||
// A key out of its range is refused when the other key is in range.
|
||||
refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 90, "roundness": 400})), "`roundness` must be from 1 to 100%");
|
||||
refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 540, "roundness": 25})), "`angle` must be from -180 to 180 degrees");
|
||||
// The pieces a stroke leaves, undone again.
|
||||
let mut erased = |tip: serde_json::Value| {
|
||||
let r = s.execute("path.eraseRegion", &with(&stroke, tip.clone())).unwrap();
|
||||
assert_eq!(r["ids"].as_array().map(Vec::len), Some(2), "{tip}: the stroke cuts the square in two: {r}");
|
||||
let pieces: Vec<PathData> = paths(&s).into_iter().map(|p| p.1).collect();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
pieces
|
||||
};
|
||||
// Both ends of each range are inside it.
|
||||
for tip in [json!({"angle": -180}), json!({"angle": 180}), json!({"angle": 90, "roundness": 1}), json!({"roundness": 100})] {
|
||||
erased(tip);
|
||||
}
|
||||
let default = erased(json!({}));
|
||||
assert_eq!(erased(json!({"angle": 0, "roundness": 100})), default, "left out, the tip is round at 0 degrees");
|
||||
assert_eq!(erased(json!({"angle": null, "roundness": null})), default, "null is read as a key left out");
|
||||
assert!(erased(json!({"angle": 0, "roundness": 25})) != default, "a quarter-round level tip erases a narrower band");
|
||||
}
|
||||
|
||||
/// The Scissors command refuses a `t` outside 0 to 1 instead of cutting at the nearer end of the
|
||||
/// segment, with or without an `anchor` beside it; 0 and 1 cut at the segment's two anchors.
|
||||
#[test]
|
||||
fn scissors_refuse_a_t_outside_the_segment() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let before = path(&s, id);
|
||||
for t in [json!(-0.1), json!(-1e-9), json!(1.000001), json!(1.1), json!(1e300), json!(-1e300)] {
|
||||
refuses_with(&mut s, "path.split", &json!({"id": id.0, "segment": 0, "t": t}), "`t` must be from 0 to 1");
|
||||
refuses_with(&mut s, "path.split", &json!({"id": id.0, "anchor": 1, "t": t}), "`t` must be from 0 to 1");
|
||||
}
|
||||
// 0 opens the square at the segment's first anchor, 1 at its second, and 0.5 at a new anchor
|
||||
// between them.
|
||||
for (t, anchors, start) in [
|
||||
(json!(0), 5, before.subpaths[0].anchors[0].p),
|
||||
(json!(1), 5, before.subpaths[0].anchors[1].p),
|
||||
(json!(0.5), 6, before.subpaths[0].anchors[0].p.midpoint(before.subpaths[0].anchors[1].p)),
|
||||
] {
|
||||
s.execute("path.split", &json!({"id": id.0, "segment": 0, "t": t})).unwrap();
|
||||
let cut = path(&s, id);
|
||||
assert!(!cut.subpaths[0].closed && cut.subpaths[0].anchors.len() == anchors, "t {t}: {cut:?}");
|
||||
assert!((cut.subpaths[0].anchors[0].p - start).hypot() < 1e-9, "t {t}: the cut starts at {:?}", cut.subpaths[0].anchors[0].p);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path(&s, id), before, "t {t}: undo");
|
||||
}
|
||||
// Left out, `t` is 0.5.
|
||||
s.execute("path.split", &json!({"id": id.0, "segment": 0})).unwrap();
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() {
|
||||
|
||||
assert!(expandable(&s), "the fill's shadow can be expanded");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let ch = node(&s, id).children().cloned().expect("the instance becomes a group");
|
||||
let n = node(&s, id);
|
||||
let ch = n.children().cloned().expect("the instance becomes a group");
|
||||
assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label());
|
||||
assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label());
|
||||
no_effects_left(&ch[1]);
|
||||
n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance"));
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
@@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() {
|
||||
assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100));
|
||||
}
|
||||
|
||||
/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner`
|
||||
/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new
|
||||
/// fill without paint on top. Returns the Outer instance and its new row's index.
|
||||
fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) {
|
||||
let (inner_id, inner_row) = instance_with_row(s, "Inner", true);
|
||||
inner(s, inner_id, inner_row);
|
||||
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
|
||||
run(s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(s, id).appearance.items.len() - 1;
|
||||
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
|
||||
(id, row)
|
||||
}
|
||||
|
||||
/// The symbol instances and the images in `n`.
|
||||
fn instances_and_images(n: &Node) -> (usize, usize) {
|
||||
let mut found = (0, 0);
|
||||
n.walk(&mut |part| match part.kind {
|
||||
NodeKind::SymbolInstance { .. } => found.0 += 1,
|
||||
NodeKind::Image(_) => found.1 += 1,
|
||||
_ => {}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Replace the art of every symbol with an empty group.
|
||||
fn empty_symbols(s: &mut Session) {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
for (i, sym) in d.symbols.iter_mut().enumerate() {
|
||||
sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![]));
|
||||
}
|
||||
}
|
||||
|
||||
/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art
|
||||
/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result
|
||||
/// no longer follows either symbol.
|
||||
#[test]
|
||||
fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert!(images >= 1, "the inner shadow is an image");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
empty_symbols(&mut s);
|
||||
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
|
||||
}
|
||||
|
||||
/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's
|
||||
/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in
|
||||
/// one undo step.
|
||||
#[test]
|
||||
fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
shadow_row(&mut s, id, row);
|
||||
let before = render(&s);
|
||||
assert!(expandable(&s));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert!(images >= 2, "the outer and inner shadows are images: {images}");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
empty_symbols(&mut s);
|
||||
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
|
||||
}
|
||||
|
||||
/// A blur on the nested instance's fill: the nested instance becomes the image.
|
||||
#[test]
|
||||
fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() {
|
||||
let mut s = session();
|
||||
let blur = |s: &mut Session, id: NodeId, row: usize| {
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, blur);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert_eq!(images, 1, "the blurred inner art is one image");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it.
|
||||
fn blue_backdrop(s: &mut Session) {
|
||||
run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200}));
|
||||
run(s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
}
|
||||
|
||||
/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`.
|
||||
fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) {
|
||||
let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"});
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params}));
|
||||
}
|
||||
|
||||
/// The blend modes of the images in `n`, in the order the walk visits them.
|
||||
fn image_modes(n: &Node) -> Vec<BlendMode> {
|
||||
let mut modes = vec![];
|
||||
n.walk(&mut |part| {
|
||||
if matches!(part.kind, NodeKind::Image(_)) {
|
||||
modes.push(part.blend);
|
||||
}
|
||||
});
|
||||
modes
|
||||
}
|
||||
|
||||
/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below
|
||||
/// as the shadow did, rather than painting red over it.
|
||||
#[test]
|
||||
fn a_nested_instance_multiply_shadow_image_keeps_its_mode() {
|
||||
let mut s = session();
|
||||
blue_backdrop(&mut s);
|
||||
let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply"));
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art");
|
||||
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100));
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply.
|
||||
#[test]
|
||||
fn an_instance_multiply_shadow_image_keeps_its_mode() {
|
||||
let mut s = session();
|
||||
blue_backdrop(&mut s);
|
||||
let (id, row) = instance_with_row(&mut s, "Square", true);
|
||||
red_shadow_row(&mut s, id, row, "multiply");
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
|
||||
let after = render(&s);
|
||||
assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100));
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it.
|
||||
#[test]
|
||||
fn a_hidden_nested_instance_fill_shadow_makes_no_image() {
|
||||
let mut s = session();
|
||||
let hidden = |s: &mut Session, id: NodeId, row: usize| {
|
||||
shadow_row(s, id, row);
|
||||
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, hidden);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow");
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image");
|
||||
no_effects_left(&n);
|
||||
}
|
||||
|
||||
/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art
|
||||
/// expands around it.
|
||||
#[test]
|
||||
fn a_nested_instance_of_a_missing_symbol_stays_an_instance() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.symbols.retain(|sym| sym.name != "Inner");
|
||||
}
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image");
|
||||
}
|
||||
|
||||
/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand
|
||||
/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which
|
||||
/// the result reports.
|
||||
#[test]
|
||||
fn nested_instance_raster_effects_stop_at_the_image_limit() {
|
||||
let mut s = session();
|
||||
// Images of a pixel or two each.
|
||||
run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1}));
|
||||
let blur = |s: &mut Session, id: NodeId, row: usize| {
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, blur);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap();
|
||||
let inner = (*d.symbols[outer].art).clone();
|
||||
assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance");
|
||||
let copies = (0..1_100)
|
||||
.map(|_| {
|
||||
let mut copy = inner.clone();
|
||||
copy.id = d.alloc_id();
|
||||
std::sync::Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies));
|
||||
}
|
||||
|
||||
let r = run(&mut s, "effect.expandAppearance", json!({}));
|
||||
assert_eq!(r["rasterLeft"], 76, "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}");
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay");
|
||||
n.walk(&mut |part| {
|
||||
if matches!(part.kind, NodeKind::SymbolInstance { .. }) {
|
||||
assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which
|
||||
/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was
|
||||
/// before expanding.
|
||||
fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node {
|
||||
// Images of a pixel or two each.
|
||||
run(s, "document.rasterEffectsSettings", json!({"resolution": 1}));
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}}));
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap());
|
||||
run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
let before = node(s, id);
|
||||
let group = {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let blurred = d.node(sq).unwrap().clone();
|
||||
d.remove(sq).unwrap();
|
||||
let mut members: Vec<_> = (0..1_024)
|
||||
.map(|_| {
|
||||
let mut copy = blurred.clone();
|
||||
copy.id = d.alloc_id();
|
||||
std::sync::Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
members.push(std::sync::Arc::new(before.clone()));
|
||||
let group = d.alloc_id();
|
||||
*d.node_mut(id).unwrap() = Node::group(group, members);
|
||||
group
|
||||
};
|
||||
|
||||
let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]}));
|
||||
assert_eq!(r["rasterLeft"], 1, "{r}");
|
||||
before
|
||||
}
|
||||
|
||||
/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance
|
||||
/// of its symbol, with both effects.
|
||||
#[test]
|
||||
fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap());
|
||||
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
|
||||
assert!(matches!(before.kind, NodeKind::SymbolInstance { .. }));
|
||||
assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur");
|
||||
}
|
||||
|
||||
/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is,
|
||||
/// and the document keeps no recolored copy of its pixels.
|
||||
#[test]
|
||||
fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() {
|
||||
let mut s = session();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let images: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
|
||||
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
|
||||
assert!(matches!(before.kind, NodeKind::Image(_)));
|
||||
assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur");
|
||||
// Besides the squares' images, the document holds the image's pixels alone.
|
||||
let after: Vec<String> = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect();
|
||||
assert_eq!(after, images, "no recolored copy stays in the document");
|
||||
}
|
||||
|
||||
/// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the
|
||||
/// shadow on the art's fill, not its stroke, and PDF export makes an image of it.
|
||||
#[test]
|
||||
|
||||
@@ -34,6 +34,59 @@ fn the_font_list_names_every_available_family_with_its_styles() {
|
||||
assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err());
|
||||
}
|
||||
|
||||
/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the
|
||||
/// order the font menus show; bad params are refused.
|
||||
#[test]
|
||||
fn similar_fonts_lists_every_family_by_likeness() {
|
||||
let mut s = Session::new();
|
||||
let db = FontDb::global();
|
||||
let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap();
|
||||
assert_eq!(r["family"], "Source Sans 3");
|
||||
let order = names(&r["families"]);
|
||||
assert_eq!(order.first().map(String::as_str), Some("Source Sans 3"));
|
||||
let mut sorted = order.clone();
|
||||
sorted.sort();
|
||||
let mut listed = db.menu_family_list().to_vec();
|
||||
listed.sort();
|
||||
// Other tests running at the same time add and remove composite fonts; the installed families are compared.
|
||||
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
|
||||
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
|
||||
// The two answers are compared whole when the available fonts did not change while both were
|
||||
// made (the same `FontDb::generation`), and by their installed families when they changed
|
||||
// during every try.
|
||||
let mut answers = (vec![], vec![], false);
|
||||
for _ in 0..20 {
|
||||
let generation = db.generation();
|
||||
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
|
||||
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
|
||||
let unchanged = db.generation() == generation;
|
||||
answers = (all, two, unchanged);
|
||||
if unchanged {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (all, two, unchanged) = answers;
|
||||
assert_eq!(two.len(), 2);
|
||||
if unchanged {
|
||||
assert_eq!(two, all[..2], "the first families, in order");
|
||||
} else {
|
||||
let (two, all) = (installed_only(&two), installed_only(&all));
|
||||
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
|
||||
}
|
||||
for (params, error) in [
|
||||
(json!({}), "`family` is required"),
|
||||
(json!({"family": " "}), "`family` is required"),
|
||||
(json!({"family": 3}), "`family` must be a string"),
|
||||
(json!({"family": "No Such Font"}), "font family `No Such Font` is not available"),
|
||||
(json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"),
|
||||
(json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"),
|
||||
(json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"),
|
||||
] {
|
||||
let e = s.execute("text.similarFonts", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(error), "{params}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -341,3 +341,139 @@ fn svg_output_keeps_linked_javascript_files_a_caller_may_read() {
|
||||
let text = run(&mut s, "document.serialize", json!({"format": "svg"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains(&format!("<script xlink:href=\"{outside}\"/>")), "{text}");
|
||||
}
|
||||
|
||||
/// The JavaScript files that the native document a `document.serialize` reply carries links.
|
||||
fn carried_scripts(r: &Value) -> Vec<String> {
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let native = if bytes.starts_with(b"%PDF") { vectorcraft_pdf::editing(&bytes).expect("editing data").data } else { bytes };
|
||||
vectorcraft_format::load(&native).unwrap().svg_scripts
|
||||
}
|
||||
|
||||
/// A caller confined to read roots: every output that carries the native document (a native file
|
||||
/// or template, a `.ai` or EPS file, a PDF with Preserve Editing, a package) of a document that
|
||||
/// links a JavaScript file outside them is refused before a file or folder is written, with an
|
||||
/// error that names no file or folder, and the document keeps the link.
|
||||
#[test]
|
||||
fn confined_native_output_refuses_a_linked_javascript_file_outside_the_read_roots() {
|
||||
let away = Folder::new("native-script-away");
|
||||
let home = Folder::new("native-script-home");
|
||||
let script = away.file("menu.js");
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": script}));
|
||||
run(&mut s, "assets.add", json!({"ids": [a.0]}));
|
||||
let own = home.file("own.vectorcraft");
|
||||
run(&mut s, "file.saveAs", json!({"path": own}));
|
||||
let before = std::fs::read(&own).unwrap();
|
||||
rect(&mut s, 50.0);
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()];
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).expect_err(cmd);
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
};
|
||||
let file = |name: &str| home.file(name);
|
||||
let out = file("out");
|
||||
refused(&mut s, "document.serialize", json!({}));
|
||||
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
|
||||
refused(&mut s, "document.serialize", json!({"format": format}));
|
||||
refused(&mut s, "document.export", json!({"format": format}));
|
||||
refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true}));
|
||||
refused(&mut s, "document.exportSelection", json!({"format": format}));
|
||||
}
|
||||
// Every artboard picked, and Preserve Editing asked for.
|
||||
refused(&mut s, "document.serialize", json!({"format": "pdf", "range": "1", "preserveEditing": true}));
|
||||
refused(&mut s, "document.serialize", json!({"format": "ai", "artboards": [0], "pdfCompatible": false}));
|
||||
refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")}));
|
||||
refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")}));
|
||||
refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")}));
|
||||
refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")}));
|
||||
refused(&mut s, "document.exportPdf", json!({}));
|
||||
refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")}));
|
||||
refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")}));
|
||||
refused(&mut s, "document.save", json!({}));
|
||||
refused(&mut s, "document.save", json!({"path": file("save.pdf")}));
|
||||
refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")}));
|
||||
// A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says.
|
||||
refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false}));
|
||||
refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")}));
|
||||
refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")}));
|
||||
refused(&mut s, "file.saveAsTemplate", json!({}));
|
||||
refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"}));
|
||||
refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]}));
|
||||
refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
|
||||
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]}));
|
||||
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]}));
|
||||
refused(&mut s, "file.package", json!({"folder": out}));
|
||||
refused(&mut s, "file.package", json!({}));
|
||||
assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was");
|
||||
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(written, ["own.vectorcraft"]);
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [script]);
|
||||
}
|
||||
|
||||
/// A confined caller still writes the outputs that carry no native document (a PDF without
|
||||
/// Preserve Editing, a PDF or `.ai` file of the art's bounds or of some artboards, a legacy `.ai`
|
||||
/// file, an image), and
|
||||
/// native outputs that link only JavaScript files it may read keep them as stored. A caller without
|
||||
/// roots writes a file outside them too.
|
||||
#[test]
|
||||
fn confined_output_without_the_document_or_with_scripts_the_caller_may_read_is_written() {
|
||||
let away = Folder::new("native-script-kept-away");
|
||||
let home = Folder::new("native-script-kept-home");
|
||||
let outside = away.file("menu.js");
|
||||
let mut s = session();
|
||||
rect(&mut s, 10.0);
|
||||
run(&mut s, "artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 100}));
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": outside}));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let written = |s: &mut Session, cmd: &str, p: Value| {
|
||||
crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
};
|
||||
for p in [
|
||||
json!({"format": "pdf", "preserveEditing": false}),
|
||||
json!({"format": "pdf", "useArtboards": false}),
|
||||
json!({"format": "pdf", "range": "2"}),
|
||||
json!({"format": "ai", "artboards": [1]}),
|
||||
json!({"format": "ai", "useArtboards": false}),
|
||||
json!({"format": "ai", "aiVersion": "7"}),
|
||||
json!({"format": "png"}),
|
||||
] {
|
||||
written(&mut s, "document.serialize", p);
|
||||
}
|
||||
written(&mut s, "document.exportPdf", json!({"preserveEditing": false}));
|
||||
written(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf"}]}));
|
||||
// A PDF of each artboard leaves the editing data out: it holds one of the two.
|
||||
written(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute("document.exportForScreens", &p)).expect_err("refused").to_string();
|
||||
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{p}: {e}");
|
||||
};
|
||||
// One PDF of both artboards, and Full Document's PDF of every artboard, carry it.
|
||||
refused(&mut s, json!({"zip": true, "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}));
|
||||
refused(&mut s, json!({"zip": true, "fullDocument": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
|
||||
// Without roots, the native document keeps a file outside them.
|
||||
let r = run(&mut s, "document.serialize", json!({}));
|
||||
assert_eq!(carried_scripts(&r), [outside.as_str()]);
|
||||
// Files the caller may read: inside the read roots, relative to the document's folder, a URL.
|
||||
let inside = home.file("menu.js");
|
||||
let url = "https://example.com/scripts/menu.js";
|
||||
let kept = [inside.as_str(), "lib/tools.js", url];
|
||||
let mut s = session();
|
||||
rect(&mut s, 10.0);
|
||||
for file in kept {
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": file}));
|
||||
}
|
||||
run(&mut s, "file.saveAs", json!({"path": home.file("doc.vectorcraft")}));
|
||||
for format in ["vectorcraft", "pdf"] {
|
||||
let r = written(&mut s, "document.serialize", json!({"format": format}));
|
||||
assert_eq!(carried_scripts(&r), kept, "{format}");
|
||||
}
|
||||
written(&mut s, "document.exportPdf", json!({"path": home.file("doc.pdf")}));
|
||||
written(&mut s, "file.package", json!({}));
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! #1636: the key anchor. With Direct Selection, the point a Shift-click adds to two or more
|
||||
//! selected anchor points is the key anchor; Align moves the other points to it, Distribute with a
|
||||
//! spacing places them from it, and it stays in place.
|
||||
//! #1636: the key anchor. When multiple anchors are selected with Direct Selection,
|
||||
//! clicking an already-selected anchor point without modifiers designates it as the key anchor;
|
||||
//! Align moves the other points to it, Distribute with a spacing places them from it, and it stays in place.
|
||||
//! Deselecting, pressing Escape, or clicking canvas clears the key anchor designation.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
@@ -34,56 +35,148 @@ fn click(s: &mut Session, x: f64, y: f64, shift: bool) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shift_click_makes_the_key_anchor_and_a_plain_click_narrows_the_selection() {
|
||||
fn clicking_an_already_selected_anchor_makes_it_the_key_anchor() {
|
||||
let mut s = session();
|
||||
let id = path(&mut s, "M100 40 L200 60 L150 160 Z");
|
||||
s.select_tool("directSelection", ViewInfo::default()).unwrap();
|
||||
// 1st click selects point (0, 0) alone.
|
||||
click(&mut s, 100.0, 40.0, false);
|
||||
assert_eq!(key_anchor(&s), None, "one point: no key anchor");
|
||||
// Shift-click adds point (0, 2) to selection. No key anchor yet.
|
||||
click(&mut s, 150.0, 160.0, true);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 2))), "the point the Shift-click added");
|
||||
assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection");
|
||||
// Shift-click adds point (0, 1) to selection. No key anchor yet.
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 1))), "the last point added");
|
||||
assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection");
|
||||
|
||||
// Clicking an already-selected anchor without modifiers designates it as the Key Anchor.
|
||||
click(&mut s, 200.0, 60.0, false);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 1))), "clicking selected anchor designates key anchor");
|
||||
let inspect = s.execute("document.inspect", &json!({})).unwrap();
|
||||
assert_eq!(inspect["keyAnchor"], json!({"id": id.0, "anchor": [0, 1]}));
|
||||
// A Shift-click on the key anchor deselects it, and there is no key anchor.
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
assert_eq!(key_anchor(&s), None);
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
// A plain click on one of the selected points selects that point alone.
|
||||
click(&mut s, 100.0, 40.0, false);
|
||||
|
||||
// Clicking the key anchor again cancels the key anchor.
|
||||
click(&mut s, 200.0, 60.0, false);
|
||||
assert_eq!(key_anchor(&s), None, "clicking key anchor again cancels it");
|
||||
let inspect = s.execute("document.inspect", &json!({})).unwrap();
|
||||
assert!(inspect["keyAnchor"].is_null());
|
||||
|
||||
// Clicking another selected anchor designates that one as the key anchor.
|
||||
click(&mut s, 150.0, 160.0, false);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 2))));
|
||||
|
||||
// Pressing Escape cancels the key anchor designation while keeping points selected.
|
||||
s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), ViewInfo::default()).unwrap();
|
||||
assert_eq!(key_anchor(&s), None, "Escape cancels key anchor");
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!(sel.anchors.get(&id).map(|a| a.iter().copied().collect::<Vec<_>>()), Some(vec![(0, 0)]));
|
||||
assert_eq!(sel.key_anchor, None);
|
||||
assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(3), "points remain selected");
|
||||
|
||||
// Designate key anchor:
|
||||
click(&mut s, 150.0, 160.0, false);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 2))));
|
||||
|
||||
// Canvas click clears selection and key anchor.
|
||||
click(&mut s, 500.0, 500.0, false); // canvas click
|
||||
assert_eq!(key_anchor(&s), None, "canvas click clears key anchor");
|
||||
assert!(s.doc().unwrap().selection.is_empty(), "canvas click clears selection");
|
||||
|
||||
// Re-select multiple anchors:
|
||||
click(&mut s, 100.0, 40.0, false); // select (0, 0)
|
||||
click(&mut s, 200.0, 60.0, true); // add (0, 1)
|
||||
assert_eq!(key_anchor(&s), None);
|
||||
click(&mut s, 200.0, 60.0, false); // make (0, 1) key anchor
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 1))));
|
||||
|
||||
// Shift-click on the key anchor deselects it, clearing the key anchor.
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
assert_eq!(key_anchor(&s), None, "deselecting key anchor clears it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_moves_the_other_points_to_the_key_anchor() {
|
||||
let mut s = session();
|
||||
let id = path(&mut s, "M100 40 L200 60 L150 160 L60 120 Z");
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), None, "a set selects no key anchor");
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "add"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), None, "set selects no key anchor");
|
||||
s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 2))));
|
||||
|
||||
// Horizontal Left aligns other selected points to key anchor's x (150).
|
||||
s.execute("object.align", &json!({"horizontal": "left"})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(150.0, 40.0), (150.0, 60.0), (150.0, 160.0), (60.0, 120.0)], "to the key anchor's x");
|
||||
|
||||
// Vertical Bottom aligns other selected points to key anchor's y (160).
|
||||
s.execute("object.align", &json!({"vertical": "bottom"})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(150.0, 160.0), (150.0, 160.0), (150.0, 160.0), (60.0, 120.0)], "the key anchor stays");
|
||||
|
||||
let steps = super::history(&s);
|
||||
s.execute("object.align", &json!({"vertical": "top"})).unwrap();
|
||||
assert_eq!(super::history(&s), steps, "nothing moved: no undo step");
|
||||
// `to: "selection"` aligns to the points' bounds instead.
|
||||
|
||||
// `to: "selection"` aligns to the points' collective bounds instead.
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]], "mode": "add"})).unwrap();
|
||||
s.execute("object.align", &json!({"horizontal": "left", "to": "selection"})).unwrap();
|
||||
assert_eq!(pts(&s, id).iter().map(|p| p.0).collect::<Vec<_>>(), [60.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_commands_across_paths_without_moving_key_anchor() {
|
||||
let mut s = session();
|
||||
let a = path(&mut s, "M100 100 L200 100 L200 200 Z");
|
||||
let b = path(&mut s, "M300 300 L400 350 Z");
|
||||
// Select point (0, 1) on path a (at 200, 100) and point (0, 0) on path b (at 300, 300).
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
|
||||
// Set point (0, 1) of a as the key anchor.
|
||||
s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((a, (0, 1))));
|
||||
|
||||
// Align Horizontal Center: point (0, 0) of b moves to x=200, while point on a does not move!
|
||||
s.execute("object.align", &json!({"horizontal": "center"})).unwrap();
|
||||
assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a does not move");
|
||||
assert_eq!(pts(&s, b)[0].0, 200.0, "survivor point on b aligned to key anchor x");
|
||||
assert_eq!(pts(&s, b)[1], (400.0, 350.0), "unselected point on b was not moved");
|
||||
|
||||
// Align Vertical Center / Middle: point (0, 0) of b moves to y=100.
|
||||
s.execute("object.align", &json!({"vertical": "center"})).unwrap();
|
||||
assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a still did not move");
|
||||
assert_eq!(pts(&s, b)[0].1, 100.0, "survivor point on b aligned to key anchor y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_step_undo_redo_for_key_anchor_alignment() {
|
||||
let mut s = session();
|
||||
let a = path(&mut s, "M100 100 L200 150 Z");
|
||||
let b = path(&mut s, "M300 300 L400 350 Z");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
|
||||
s.execute("select.key", &json!({"id": a.0, "anchor": [0, 0]})).unwrap();
|
||||
|
||||
let initial_a = pts(&s, a);
|
||||
let initial_b = pts(&s, b);
|
||||
|
||||
// Run align:
|
||||
s.execute("object.align", &json!({"horizontal": "right"})).unwrap();
|
||||
assert_eq!(pts(&s, a)[0], (100.0, 100.0), "key anchor did not move");
|
||||
assert_eq!(pts(&s, b)[0].0, 100.0, "survivor moved to key anchor x");
|
||||
|
||||
// Undo reverts to initial in one step:
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(pts(&s, a), initial_a, "undo restored a");
|
||||
assert_eq!(pts(&s, b), initial_b, "undo restored b");
|
||||
|
||||
// Redo re-aligns in one step:
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(pts(&s, a)[0], (100.0, 100.0));
|
||||
assert_eq!(pts(&s, b)[0].0, 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distribute_with_a_spacing_places_the_points_from_the_key_anchor() {
|
||||
let mut s = session();
|
||||
let id = path(&mut s, "M10 10 L20 50 L100 30 L60 90");
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
|
||||
s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap();
|
||||
s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 20})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(60.0, 10.0), (80.0, 50.0), (100.0, 30.0), (60.0, 90.0)], "20 apart, outward from the key anchor");
|
||||
s.execute("object.distribute", &json!({"vertical": "center", "spacing": 5})).unwrap();
|
||||
@@ -100,6 +193,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() {
|
||||
let b = path(&mut s, "M300 300 L400 300");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
s.execute("select.key", &json!({"id": b.0, "anchor": [0, 1]})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((b, (0, 1))), "a point of another path");
|
||||
assert!(s.doc().unwrap().selection.has_key());
|
||||
let r = s.execute("select.key", &json!({})).unwrap();
|
||||
@@ -114,6 +208,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() {
|
||||
let c = path(&mut s, "M500 500 L600 500");
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((a, (0, 1))), "beside a path selected whole");
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
@@ -154,6 +249,7 @@ fn a_rejected_select_key_keeps_the_key_anchor() {
|
||||
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 9]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((a, (0, 1))));
|
||||
// [0, 9] is in the selection but not on the path.
|
||||
let err = s.execute("select.key", &json!({"id": a.0, "anchor": [0, 9]})).expect_err("a point the path does not have").to_string();
|
||||
|
||||
@@ -2168,6 +2168,64 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read()
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's SVG and SVGZ with Preserve Editing Capabilities carry a native document
|
||||
/// without the Export for Screens folder when it is outside the read roots, with the other export
|
||||
/// settings and the art; the open document keeps the folder. A folder inside the roots, and any
|
||||
/// folder without roots, stays in the attachment.
|
||||
#[test]
|
||||
fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-export-folder-away");
|
||||
let home = Folder::new("svg-export-folder-home");
|
||||
let outside = away.0.to_string_lossy().into_owned();
|
||||
let inside = home.file("screens");
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
|
||||
let set_folder = |s: &mut Session, folder: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap();
|
||||
};
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
// The native document an SVG's text carries.
|
||||
let attached = |text: &str| {
|
||||
let data = vectorcraft_svg::editing_data(text).expect("editing data");
|
||||
vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap()
|
||||
};
|
||||
let check = |d: &Document, folder: Option<&str>, what: &str| {
|
||||
assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}");
|
||||
assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}");
|
||||
assert!(d.node(rect).is_some(), "{what}: no art");
|
||||
};
|
||||
// Every way an SVG is asked for with Preserve Editing, its text and its native document.
|
||||
let every = |s: &mut Session, confined: bool, folder: Option<&str>| {
|
||||
let run = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) };
|
||||
r.unwrap()
|
||||
};
|
||||
for format in ["svg", "svgz"] {
|
||||
let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true}));
|
||||
check(&attached(&svg_text(&r)), folder, &format!("{format} serialize"));
|
||||
let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}}));
|
||||
check(&attached(&svg_text(&r)), folder, &format!("{format} options object"));
|
||||
let path = home.file(&format!("export.{format}"));
|
||||
run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true}));
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export"));
|
||||
}
|
||||
};
|
||||
set_folder(&mut s, &outside);
|
||||
every(&mut s, true, None);
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str()));
|
||||
every(&mut s, false, Some(&outside));
|
||||
// Without Preserve Editing the SVG carries no native document.
|
||||
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
|
||||
assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}");
|
||||
set_folder(&mut s, &inside);
|
||||
every(&mut s, true, Some(&inside));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
|
||||
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
|
||||
/// written. Any output that names no file is written.
|
||||
|
||||
@@ -1588,6 +1588,235 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() {
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size.
|
||||
#[test]
|
||||
fn crop_image_resamples_the_cut_to_the_resolution_asked_for() {
|
||||
let (mut s, img, px) = busy_image_at_two_points_a_pixel();
|
||||
// The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image();
|
||||
// Resampled in 16 bits a channel: within a level of the 8-bit resampling.
|
||||
let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3);
|
||||
assert_eq!(out.dimensions(), want.dimensions());
|
||||
assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1));
|
||||
}
|
||||
|
||||
/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not
|
||||
/// tint the partly transparent edge of what is opaque.
|
||||
#[test]
|
||||
fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() {
|
||||
// Opaque white on the left half, fully transparent red on the right.
|
||||
let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) });
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
// 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear.
|
||||
s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap();
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent");
|
||||
for p in out.pixels().filter(|p| p[3] > 0) {
|
||||
assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest
|
||||
/// alpha comes out as that color, not black.
|
||||
#[test]
|
||||
fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() {
|
||||
let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1]));
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
for p in out.pixels() {
|
||||
let near = |a: u8, b: u8| a.abs_diff(b) <= 1;
|
||||
assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its
|
||||
/// place: the edge of the image's content lands where it was in the box.
|
||||
#[test]
|
||||
fn crop_image_between_pixels_keeps_the_content_at_its_place() {
|
||||
// White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt.
|
||||
let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) });
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
// 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into
|
||||
// the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::<f64>() / f64::from(out.height());
|
||||
let want = 49.0 * 79.0 / 101.0;
|
||||
assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// A box between pixels is drawn at the resolution asked for, and lands on the box.
|
||||
#[test]
|
||||
fn crop_image_between_pixels_draws_at_the_resolution_asked_for() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
// 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box.
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// A box over the whole image with a new resolution resamples it; with the image's own there is
|
||||
/// nothing to do.
|
||||
#[test]
|
||||
fn crop_image_over_the_whole_image_only_resamples_it() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let before = undo_len(&s);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
|
||||
assert_eq!(undo_len(&s), before);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}");
|
||||
assert_eq!(undo_len(&s), before + 1, "one undo step");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// An image scaled more down than across is resampled on both sides at the resolution of its denser
|
||||
/// side, so its pixels come out square.
|
||||
#[test]
|
||||
fn crop_image_resamples_pixels_that_are_not_square() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
// 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt.
|
||||
s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one
|
||||
/// with trim; the image stays as it was.
|
||||
#[test]
|
||||
fn crop_image_refuses_a_resolution_it_cannot_give() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let before = (undo_len(&s), node(&s, img));
|
||||
let refused = |s: &mut Session, p: Value, want: &str| {
|
||||
let r = s.execute("object.cropImage", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
|
||||
};
|
||||
for v in [json!(0), json!(-72), json!("high"), json!(true)] {
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}"));
|
||||
}
|
||||
for v in [0.5, 1e-310, 2401.0] {
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400");
|
||||
}
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image");
|
||||
refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi");
|
||||
assert_eq!((undo_len(&s), node(&s, img)), before);
|
||||
// A null ppi keeps the image's own, as a missing one does.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}");
|
||||
}
|
||||
|
||||
/// A turned image keeps its own resolution as the limit (not the density across its bounding box),
|
||||
/// and its drawn cut is resampled to the box's size at the resolution asked for.
|
||||
#[test]
|
||||
fn crop_image_of_a_turned_image_resamples_its_drawing() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}");
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}");
|
||||
let c = bounds(&s, img);
|
||||
assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}");
|
||||
}
|
||||
|
||||
/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower
|
||||
/// density of the box around it.
|
||||
#[test]
|
||||
fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}");
|
||||
// Over the whole box around it, its own resolution draws it square to the page.
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap();
|
||||
assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}");
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
|
||||
}
|
||||
|
||||
/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it.
|
||||
#[test]
|
||||
fn crop_image_takes_a_linked_image_up_to_300_ppi() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.edit("Link", |d, _| {
|
||||
let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") };
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new("art.png"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}");
|
||||
// 72 ppi: a pixel a point.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
assert!(im.link.is_none());
|
||||
}
|
||||
|
||||
/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and
|
||||
/// changes nothing.
|
||||
#[test]
|
||||
fn crop_image_tool_options_refuse_values_they_cannot_use() {
|
||||
let (mut s, _, _) = busy_image_at_two_points_a_pixel();
|
||||
s.select_tool("cropImage", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap();
|
||||
// 72 ppi is above the selected 36 ppi image's own.
|
||||
for (key, value) in
|
||||
[("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))]
|
||||
{
|
||||
assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}");
|
||||
}
|
||||
let o = s.tool_options();
|
||||
assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}");
|
||||
s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap();
|
||||
assert!(s.tool_options().get("ppi").is_none());
|
||||
}
|
||||
|
||||
/// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a
|
||||
/// null `rect` crops to the artboard as a missing one does.
|
||||
#[test]
|
||||
@@ -5331,6 +5560,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() {
|
||||
assert!(within.contains("the image's pixels can't be read"), "{within}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_image_resampling_is_held_to_the_raster_allowance() {
|
||||
use crate::cmd::menucmds::check_resample_size;
|
||||
let max = crate::cmd::fileio::MAX_RASTER_ALLOC;
|
||||
// 40 bytes a pixel resampled to the same size (12 + 16 + 12).
|
||||
let side = ((max / 40) as f64).sqrt() as u32;
|
||||
assert!(check_resample_size(side, side, side, side).is_ok());
|
||||
let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}");
|
||||
// A large source counts even when the result is small.
|
||||
let wide = ((max / 12) as f64).sqrt() as u32 + 1;
|
||||
assert!(check_resample_size(wide, wide, 1, 1).is_err());
|
||||
assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err());
|
||||
assert!(check_resample_size(100, 100, 50, 50).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_image_trim_leaves_a_cmyk_image_alone() {
|
||||
// CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error.
|
||||
|
||||
@@ -278,6 +278,30 @@ fn each_copys_shadow_expands_as_the_canvas_draws_it() {
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
}
|
||||
|
||||
/// Each copy of a fill's own Transform effect, and each copy of its object's Transform effect,
|
||||
/// draws the fill's drop shadow under itself, scaled with it, and Expand Appearance keeps those
|
||||
/// shadows: the copy (10..50 across, 90..130 down) has its own shadow 40 pt to its right.
|
||||
#[test]
|
||||
fn each_copys_fill_shadow_expands_as_the_canvas_draws_it() {
|
||||
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
let copies = json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1});
|
||||
for own in [true, false] {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "item": 0}));
|
||||
let item = if own { json!(0) } else { json!(null) };
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": copies, "item": item}));
|
||||
let before = render(&s);
|
||||
assert_eq!(before.pixel(80, 110), [0, 255, 0, 255], "own {own}: the copy's shadow");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let after = render(&s);
|
||||
let diff = differing(&before, &after, 64);
|
||||
assert_eq!(diff, 0, "own {own}: {diff} pixels differ");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy of type's Transform effect draws the drop shadow listed before the effect under
|
||||
/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 %
|
||||
/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's
|
||||
|
||||
@@ -351,6 +351,60 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() {
|
||||
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
|
||||
}
|
||||
|
||||
/// A confined request packages no document that links, or places a native document or a PDF with
|
||||
/// Preserve Editing that links, a JavaScript file outside its read roots: the package is refused
|
||||
/// before anything is written, with an error that names no file or folder. A JavaScript file inside
|
||||
/// them is packaged, and so is one outside them when the person packages.
|
||||
#[test]
|
||||
fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() {
|
||||
let away = Folder::new("package-script-away");
|
||||
let home = Folder::new("package-script-home");
|
||||
let script = away.file("menu.js");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()];
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)).expect_err("refused");
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{p} names {h}: {e}");
|
||||
}
|
||||
};
|
||||
let mut part = session();
|
||||
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
|
||||
run(&mut part, "svgInteractivity.addFile", json!({"file": script}));
|
||||
std::fs::create_dir_all(home.0.join("art")).unwrap();
|
||||
let native = home.file("art/part.vectorcraft");
|
||||
save(&mut part, &native);
|
||||
let r = run(&mut part, "document.serialize", json!({"format": "pdf"}));
|
||||
let pdf = home.file("art/part.pdf");
|
||||
write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
let out = home.file("out");
|
||||
refused(&mut part, json!({"folder": out}));
|
||||
refused(&mut part, json!({}));
|
||||
for placed in [&native, &pdf] {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
save(&mut s, &home.file("poster.vectorcraft"));
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({}));
|
||||
assert!(!std::path::Path::new(&out).exists(), "{placed}");
|
||||
// The person's package copies it.
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "{placed}");
|
||||
}
|
||||
// A JavaScript file inside the read roots.
|
||||
run(&mut part, "svgInteractivity.removeFile", json!({"file": script}));
|
||||
run(&mut part, "svgInteractivity.addFile", json!({"file": home.file("menu.js")}));
|
||||
save(&mut part, &native);
|
||||
let mut s = session();
|
||||
run(&mut s, "file.place", json!({"path": native, "link": true}));
|
||||
save(&mut s, &home.file("poster.vectorcraft"));
|
||||
let r = crate::file_access::confine(Some(&roots), || s.execute("file.package", &json!({"folder": out}))).unwrap();
|
||||
assert_eq!(r["links"], 1, "{r}");
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
|
||||
@@ -1436,6 +1436,40 @@ fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
|
||||
assert!(whole(&[(e, f)]), "{e} {f}");
|
||||
}
|
||||
|
||||
/// An instance snapped to whole points takes the art of its linked opacity mask along by the same
|
||||
/// amount, as a move does; the art of an unlinked mask stays where it is.
|
||||
#[test]
|
||||
fn an_instance_snapped_to_the_grid_moves_its_linked_mask() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
|
||||
let place = |s: &mut Session, x: f64, linked: bool| {
|
||||
let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
|
||||
let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0);
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let art = d.remove(NodeId(m)).unwrap();
|
||||
let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) };
|
||||
d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask));
|
||||
inst
|
||||
};
|
||||
let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false));
|
||||
let mask_points = |s: &Session, inst: u64| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap();
|
||||
mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::<Vec<_>>()
|
||||
};
|
||||
let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked));
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
let [.., e0, f0] = xf_before.as_coeffs();
|
||||
let [.., e, f] = instance_xf(&s, linked).as_coeffs();
|
||||
assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}");
|
||||
let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect();
|
||||
let after = mask_points(&s, linked);
|
||||
assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}");
|
||||
assert!(whole(&placed_points(&s, unlinked)));
|
||||
assert_eq!(mask_points(&s, unlinked), unlinked_before);
|
||||
}
|
||||
|
||||
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
|
||||
/// on the pixel grid, so its instances stay on it.
|
||||
#[test]
|
||||
@@ -1459,3 +1493,49 @@ fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid
|
||||
/// on the editing layer at once, and its instance stays on it after editing ends.
|
||||
#[test]
|
||||
fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
|
||||
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
|
||||
let before = points(&s, part);
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let xf = d.symbol_edit.as_ref().unwrap().xf;
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
|
||||
let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect();
|
||||
let shown = points(&s, part);
|
||||
assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}");
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that
|
||||
/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are.
|
||||
#[test]
|
||||
fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("symbol.edit", &json!({"ids": [b]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
|
||||
let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
|
||||
let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone();
|
||||
let shown = instance_xf(&s, inner);
|
||||
assert!(!whole(&placed_points(&s, inner)));
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
assert_eq!(instance_xf(&s, inner), shown);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art));
|
||||
}
|
||||
@@ -359,6 +359,35 @@ fn an_empty_row_adds_no_swatch_and_no_group_color() {
|
||||
assert_eq!(hexes, ["#ff0000", "#0000ff"]);
|
||||
}
|
||||
|
||||
/// An empty row with `added` (a color the Add Color tool added) recolors nothing, and without
|
||||
/// `groupColors` gives a rewritten group its new color after the colors of the rows with current
|
||||
/// colors; randomize keeps the flag, and an `added` that is not true or false is refused.
|
||||
#[test]
|
||||
fn an_added_empty_row_gives_the_group_its_color_after_the_others() {
|
||||
let mut s = session();
|
||||
let red = rect(&mut s, json!("#ff0000"));
|
||||
let blue = rect(&mut s, json!("#0000ff"));
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Pair", "colors": ["#ff0000", "#0000ff"]}));
|
||||
select_all(&mut s);
|
||||
let map = json!([
|
||||
{"from": [], "to": "rgb 0 255 0", "added": true},
|
||||
{"from": [], "to": "rgb 9 9 9"},
|
||||
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
|
||||
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
|
||||
]);
|
||||
let shuffled = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1}));
|
||||
assert_eq!(shuffled["map"][0]["added"], json!(true), "{shuffled}");
|
||||
assert_eq!(shuffled["map"][1].get("added"), None, "{shuffled}");
|
||||
run(&mut s, "recolor.apply", json!({"map": map, "group": "Pair"}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let g = d.swatch_groups.iter().find(|g| g.name == "Pair").unwrap();
|
||||
let hexes: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
|
||||
assert_eq!(hexes, ["#ff0000", "#0000ff", "#00ff00"]);
|
||||
assert_eq!((fill(&s, red).to_hex(), fill(&s, blue).to_hex()), ("#ff0000".into(), "#0000ff".into()), "no art is recolored");
|
||||
let bad = json!([{"from": [], "to": "rgb 0 255 0", "added": "yes"}]);
|
||||
assert!(s.execute("recolor.apply", &json!({"map": bad})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
|
||||
let mut s = session();
|
||||
@@ -765,6 +794,65 @@ fn recolor_of_everything_counts_locked_art_that_only_loses_its_group_swatch_link
|
||||
assert_eq!(r["notChanged"], json!({"locked": 1, "hidden": 0}), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_places() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000", "#00ff00"]}));
|
||||
let group = |s: &Session| -> Vec<(String, String)> {
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone();
|
||||
g.iter().map(|w| (w.name.clone(), w.paint.color().unwrap().to_hex())).collect()
|
||||
};
|
||||
let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect();
|
||||
for name in &names {
|
||||
run(&mut s, "swatch.edit", json!({"name": name, "global": true}));
|
||||
}
|
||||
let red = rect(&mut s, json!("#000000"));
|
||||
let green = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [red.0], "swatch": names[1]}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]}));
|
||||
select_all(&mut s);
|
||||
// The middle swatch goes; the last keeps its name and color, and a color added after them is new.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["#2878f0", null, "#00ff00", "#123456"]}));
|
||||
let g = group(&s);
|
||||
assert_eq!(g.len(), 3, "{g:?}");
|
||||
assert_eq!(g[..2], [(names[0].clone(), "#2878f0".into()), (names[2].clone(), "#00ff00".into())]);
|
||||
assert_eq!(g[2].1, "#123456");
|
||||
let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
|
||||
vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch),
|
||||
p => panic!("{p:?}"),
|
||||
};
|
||||
assert_eq!(link(&s, red), ("#ff0000".into(), None), "art linked to the removed swatch keeps its color, unlinked");
|
||||
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
|
||||
}
|
||||
|
||||
/// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of
|
||||
/// the group, which the rewrite gives another color, loses the link instead of following it.
|
||||
#[test]
|
||||
fn art_of_a_row_without_a_new_color_keeps_its_color_when_its_swatch_takes_another() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff", "#00ff00"]}));
|
||||
let names: Vec<String> =
|
||||
s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.iter().map(|w| w.name.clone()).collect();
|
||||
for name in &names {
|
||||
run(&mut s, "swatch.edit", json!({"name": name, "global": true}));
|
||||
}
|
||||
let blue = rect(&mut s, json!("#000000"));
|
||||
let green = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [blue.0], "swatch": names[1]}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]}));
|
||||
select_all(&mut s);
|
||||
// The rows are blue, red and green; the blue row's new color is removed, so the group's first
|
||||
// swatch goes and its second takes the red row's new color.
|
||||
let map = json!([{"from": ["#0000ff"], "to": null}, {"from": ["#ff0000"], "to": "#ff0000"}, {"from": ["#00ff00"], "to": "#00ff00"}]);
|
||||
run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand", "groupColors": [null, "#ff0000", "#00ff00"]}));
|
||||
let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
|
||||
vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch),
|
||||
p => panic!("{p:?}"),
|
||||
};
|
||||
assert_eq!(link(&s, blue), ("#0000ff".into(), None), "the art keeps its color, unlinked");
|
||||
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art of another row keeps its link");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recolor_of_everything_does_not_count_locked_art_whose_pattern_the_group_rewrite_recolors() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -345,6 +345,134 @@ fn misspellings_of_one_object_are_what_the_check_lists() {
|
||||
assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]);
|
||||
}
|
||||
|
||||
/// The (id, start, word) of each word a check lists, and its `more`.
|
||||
fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) {
|
||||
let r = run(s, "text.spelling.check", p);
|
||||
let words = r["words"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
|
||||
.collect();
|
||||
(words, r["more"].as_bool().unwrap())
|
||||
}
|
||||
|
||||
/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of
|
||||
/// that type object first, then the objects after it, and nothing listed twice.
|
||||
#[test]
|
||||
fn a_check_goes_on_from_where_the_last_one_stopped() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx");
|
||||
let b = text(&mut s, 100.0, "zzqqx");
|
||||
let (first, more) = listed(&mut s, json!({"max": 2}));
|
||||
assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true));
|
||||
// From the end of the second word: the third, in the next paragraph of the same object, not
|
||||
// the start of the next object.
|
||||
let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2}));
|
||||
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false));
|
||||
// A byte inside a word starts from the next word.
|
||||
let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}}));
|
||||
assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string())));
|
||||
// `from` follows the ids given, groups' type included.
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1}));
|
||||
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true));
|
||||
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1}));
|
||||
assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false));
|
||||
let bad = [
|
||||
json!({"from": {"id": a.0}}),
|
||||
json!({"from": {"id": a.0, "byte": -1}}),
|
||||
json!({"from": {"id": a.0, "byte": 1000}}),
|
||||
json!({"from": {"id": a.0, "byte": 0, "x": 1}}),
|
||||
json!({"from": a.0}),
|
||||
json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}),
|
||||
json!({"max": 0}),
|
||||
json!({"max": 10_001}),
|
||||
json!({"max": "2"}),
|
||||
];
|
||||
for p in bad {
|
||||
assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused");
|
||||
}
|
||||
}
|
||||
|
||||
/// One type object with one unknown word more than a check lists: going on from the last word
|
||||
/// listed reaches the last one.
|
||||
#[test]
|
||||
fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() {
|
||||
use crate::cmd::spelling::MAX_WORDS;
|
||||
let mut s = session();
|
||||
let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" "));
|
||||
let r = run(&mut s, "text.spelling.check", json!({}));
|
||||
let words = r["words"].as_array().unwrap();
|
||||
assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true)));
|
||||
let end = words.last().unwrap()["end"].as_u64().unwrap();
|
||||
let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}}));
|
||||
assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false));
|
||||
}
|
||||
|
||||
/// The plain text of type object `id`.
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not type"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change All's command replaces every word listed, in several objects, as one undo step, and
|
||||
/// refuses a list with any word not in its object's text, changing nothing.
|
||||
#[test]
|
||||
fn change_all_replaces_every_word_listed_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw");
|
||||
let b = text(&mut s, 100.0, "é qzxvw");
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]);
|
||||
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}));
|
||||
assert_eq!(r["changed"], 4);
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string()));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string()));
|
||||
let bad = [
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}),
|
||||
json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}),
|
||||
json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}),
|
||||
json!({"to": "x", "words": {"id": a.0}}),
|
||||
json!({"words": []}),
|
||||
];
|
||||
for p in bad {
|
||||
assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused");
|
||||
}
|
||||
assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list");
|
||||
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0);
|
||||
}
|
||||
|
||||
/// A listed word that already reads as `to` is left alone: with no other word, no edit and no
|
||||
/// undo step, so the redo history stays.
|
||||
#[test]
|
||||
fn change_all_skips_words_that_already_read_as_the_replacement() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "fixed qzxvw");
|
||||
run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
let (undo, redo) = {
|
||||
let h = &s.doc().unwrap().history;
|
||||
(h.undo.len(), h.redo.len())
|
||||
};
|
||||
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]}));
|
||||
assert_eq!(r["changed"], 0);
|
||||
let h = &s.doc().unwrap().history;
|
||||
assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept");
|
||||
let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]);
|
||||
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1);
|
||||
assert_eq!(plain(&s, a), "fixed fixed");
|
||||
}
|
||||
|
||||
/// Each change to the custom dictionary moves its generation on, whether it is saved or not, so
|
||||
/// what Auto Spell Check found before is checked again.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Snap to Tangent with the Line Segment tool: a line dragged from one circle to another lands on
|
||||
//! their common tangent, drawn by `shape.line` as one undo step.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_geom::{Point, Vec2};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
use PointerKind::{Down, Drag, Up};
|
||||
|
||||
#[test]
|
||||
fn a_line_segment_drag_draws_the_common_tangent_as_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 60, "y": 210, "width": 80, "height": 80})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 240, "y": 190, "width": 120, "height": 120})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
|
||||
assert_eq!(count(&s), 2);
|
||||
// Circles about (100, 250), radius 40, and (300, 250), radius 60: the outer tangent above them
|
||||
// has the normal (-0.1, -√0.99) and touches them at center + radius × normal.
|
||||
let n = Vec2::new(-0.1, -(0.99f64).sqrt());
|
||||
let (on_a, on_b) = (Point::new(100.0, 250.0) + n * 40.0, Point::new(300.0, 250.0) + n * 60.0);
|
||||
s.select_tool("lineSegment", ViewInfo::default()).unwrap();
|
||||
let to = on_b + Vec2::new(0.5, 0.7);
|
||||
for (k, x, y) in [(Down, 100.0, 210.0), (Drag, 200.0, 200.0), (Drag, to.x, to.y), (Up, to.x, to.y)] {
|
||||
s.pointer(&PointerEvent::new(k, x, y), ViewInfo::default()).unwrap();
|
||||
}
|
||||
assert_eq!(count(&s), 3);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") };
|
||||
let ends: Vec<Point> = path.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends.len(), 2);
|
||||
// Within what the drawn circles' 0.03% radius error allows.
|
||||
assert!((ends[0] - on_a).hypot() < 0.15 && (ends[1] - on_b).hypot() < 0.15, "{ends:?}, want {on_a:?} {on_b:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 2, "one undo removes the line");
|
||||
}
|
||||
@@ -1347,6 +1347,18 @@ impl Session {
|
||||
}
|
||||
// Every value is checked before any is set, so an invalid one changes nothing.
|
||||
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
|
||||
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
|
||||
use vectorcraft_tools::cropimage as crop;
|
||||
// The most the selected image can be cropped to, when one is selected.
|
||||
let max = self.doc().ok().and_then(|st| {
|
||||
let (id, _) = crop::selected_image(&st.doc, &st.selection)?;
|
||||
match &st.doc.node(id)?.kind {
|
||||
vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
crop::check_options(&values, max)?;
|
||||
}
|
||||
// The Place queue is read later, by a click outside any automation scope: its files must
|
||||
// be readable now, under the roots of whoever sets it.
|
||||
if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) {
|
||||
|
||||
@@ -991,6 +991,10 @@ fn structured_junk() {
|
||||
("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})),
|
||||
("addon.pathtools.commonTangents", json!({"tangents": "all", "centerline": true})),
|
||||
("addon.pathtools.commonTangents", json!({"tangents": "x", "centerline": "y", "ids": [u64::MAX, -1]})),
|
||||
("addon.pathtools.commonTangents", json!({"tangents": null, "ids": [1, 2, 3, 4], "centerline": null})),
|
||||
("addon.pathtools.commonTangents", json!({"tangents": ["external"], "ids": "all"})),
|
||||
("addon.pathtools.expandDashes", json!({})),
|
||||
("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})),
|
||||
("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})),
|
||||
|
||||
@@ -12598,3 +12598,199 @@ fn a_clipping_objects_text_wrap_is_left_out_without_room() {
|
||||
assert_eq!(carriers, if room >= 4 { vec![true] } else { vec![] }, "{room}\n{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clipping object written as art cut to it (one that isn't a path or compound path with points,
|
||||
/// or any clipping object in art already cut to one) keeps its name, its opacity mask and its
|
||||
/// visibility variable on one unpainted object, locked and hidden as it was: the reader reads the
|
||||
/// name once, on that object, with the mask, and binds the variable to it. The fills and strokes the
|
||||
/// clipping object paints keep its opacity mask, without its name.
|
||||
#[test]
|
||||
fn a_cut_clipping_object_keeps_its_name_mask_and_variables() {
|
||||
use vectorcraft_doc::{TextObject, Variable, VariableKind};
|
||||
// Each case, with the number of objects written for the clipping object's paint.
|
||||
let cases = [
|
||||
("group", 0),
|
||||
("hidden", 0),
|
||||
("locked", 0),
|
||||
("image", 0),
|
||||
("instance", 0),
|
||||
("blend", 0),
|
||||
("type", 1),
|
||||
("unpainted path", 0),
|
||||
("unpainted compound", 0),
|
||||
("fill", 1),
|
||||
("stroke", 1),
|
||||
("fill and stroke", 2),
|
||||
];
|
||||
for (case, parts) in cases {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
|
||||
let rect = Rect::new(20.0, 20.0, 80.0, 80.0);
|
||||
let mut cutter = match case {
|
||||
"image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None),
|
||||
"instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))),
|
||||
"blend" => {
|
||||
let keys = vec![
|
||||
Arc::new(square(&mut doc, Rect::new(20.0, 20.0, 30.0, 30.0), Color::gray(0.5))),
|
||||
Arc::new(square(&mut doc, Rect::new(60.0, 20.0, 70.0, 30.0), Color::gray(0.5))),
|
||||
];
|
||||
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() };
|
||||
Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) })
|
||||
}
|
||||
"type" => text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK))),
|
||||
"unpainted path" => clipping(&mut doc, shapes::rectangle(rect)),
|
||||
"unpainted compound" => {
|
||||
let outer = Node::path(doc.alloc_id(), shapes::rectangle(rect), Appearance::default());
|
||||
let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default());
|
||||
Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd })
|
||||
}
|
||||
"fill" | "stroke" | "fill and stroke" => {
|
||||
let mut c = clipping(&mut doc, shapes::rectangle(rect));
|
||||
let fill = if case == "stroke" { Paint::None } else { solid(Color::gray(0.5)) };
|
||||
let stroke = if case == "fill" { Paint::None } else { solid(Color::rgb(0.0, 0.0, 1.0)) };
|
||||
c.appearance = Appearance::basic(fill, stroke, if case == "fill" { 0.0 } else { 2.0 }).into();
|
||||
c
|
||||
}
|
||||
_ => {
|
||||
let members = vec![square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), square(&mut doc, rect, Color::gray(0.5))];
|
||||
group(&mut doc, members, false)
|
||||
}
|
||||
};
|
||||
cutter.name = Some("Cutter".into());
|
||||
cutter.visible = case != "hidden";
|
||||
cutter.locked = case == "locked";
|
||||
let veil = square(&mut doc, Rect::new(20.0, 20.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0));
|
||||
cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false)));
|
||||
let id = cutter.id;
|
||||
let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let mut top = group(&mut doc, vec![cutter, member], true);
|
||||
if matches!(case, "unpainted path" | "unpainted compound" | "fill" | "stroke" | "fill and stroke") {
|
||||
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
|
||||
let frame = group(&mut doc, vec![frame], false);
|
||||
top = group(&mut doc, vec![frame, top], true);
|
||||
}
|
||||
doc.insert(Some(layer), usize::MAX, top).unwrap();
|
||||
doc.variables.variables.push(Variable { name: "show".into(), kind: VariableKind::Visibility });
|
||||
doc.variables.bind(id, "show");
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().all(|w| w != writer::BINDINGS), "{case}: {:?}", out.warnings);
|
||||
let text = String::from_utf8(out.program).unwrap().replace("\r\n", "\n");
|
||||
assert_eq!(text.matches("%_/XMLUID : (Cutter) ; (AI10_ArtUID) ,").count(), 1, "{case}\n{text}");
|
||||
assert_eq!(text.matches("(AI9_Mask)").count(), 1 + parts, "{case}\n{text}");
|
||||
let back = read_back(&doc);
|
||||
let (mut cutters, mut masked) = (vec![], 0);
|
||||
back.layers[0].walk(&mut |n| {
|
||||
masked += usize::from(n.extras().mask.is_some());
|
||||
if n.name.as_deref() == Some("Cutter") {
|
||||
let unpainted = matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.is_empty();
|
||||
cutters.push((n.id, unpainted, n.extras().mask.is_some(), n.locked, n.visible));
|
||||
}
|
||||
});
|
||||
let [(carrier, unpainted, mask, locked, visible)] = cutters[..] else { panic!("{case}: {cutters:?}\n{text}") };
|
||||
assert!(unpainted && mask, "{case}");
|
||||
assert_eq!((locked, visible), (case == "locked", case != "hidden"), "{case}");
|
||||
assert_eq!(masked, 1 + parts, "{case}");
|
||||
assert_eq!(back.variables.objects_of("show"), vec![carrier], "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With too little room for the unpainted object that carries a cut clipping object's dictionary,
|
||||
/// the dictionary is left out, never written on another object; with room for the object but not
|
||||
/// for its opacity mask's art, only the mask is left out. The data stays readable.
|
||||
#[test]
|
||||
fn a_cut_clipping_objects_dictionary_is_left_out_without_room() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let before = named(square(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0), Color::gray(0.2)), "Before");
|
||||
doc.insert(Some(layer), usize::MAX, before).unwrap();
|
||||
let members = vec![
|
||||
square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)),
|
||||
square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)),
|
||||
];
|
||||
let mut cutter = wrapped(named(group(&mut doc, members, false), "Cutter"), 2.0, false);
|
||||
cutter.locked = true;
|
||||
let veil = vec![
|
||||
square(&mut doc, Rect::new(20.0, 20.0, 40.0, 40.0), Color::rgb(1.0, 1.0, 1.0)),
|
||||
square(&mut doc, Rect::new(40.0, 40.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)),
|
||||
];
|
||||
let veil = group(&mut doc, veil, false);
|
||||
cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false)));
|
||||
let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let top = group(&mut doc, vec![cutter, member], true);
|
||||
doc.insert(Some(layer), usize::MAX, top).unwrap();
|
||||
let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
|
||||
let mut kept = vec![];
|
||||
for room in 0..=all {
|
||||
let out = export_within(&doc, &opts(), room).unwrap();
|
||||
assert!(crate::import::objects_read(&out.program).unwrap() <= room);
|
||||
let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
|
||||
let (back, _) = crate::ai_alone(&out.program).unwrap();
|
||||
let mut found = vec![];
|
||||
back.layers[0].walk(&mut |n| {
|
||||
let x = n.extras();
|
||||
if !matches!(n.kind, NodeKind::Layer { .. }) && (n.name.is_some() || x.wrap.is_some() || x.mask.is_some()) {
|
||||
let carrier = matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty();
|
||||
found.push((n.name.clone(), carrier, x.wrap.is_some(), x.mask.is_some(), n.locked));
|
||||
}
|
||||
});
|
||||
let before = (Some("Before".to_string()), false, false, false, false);
|
||||
let rest = match found.split_first() {
|
||||
Some((b, rest)) if room > 0 => {
|
||||
assert_eq!(b, &before, "{room}\n{text}");
|
||||
rest
|
||||
}
|
||||
_ => &found[..],
|
||||
};
|
||||
match rest {
|
||||
[] => kept.push((false, false)),
|
||||
[(name, true, true, mask, true)] if name.as_deref() == Some("Cutter") => kept.push((true, *mask)),
|
||||
_ => panic!("{room}: {found:?}\n{text}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(kept.last(), Some(&(true, true)));
|
||||
// Once the carrier fits it stays, and once its mask fits it stays too.
|
||||
let carrier = kept.iter().position(|k| k.0).unwrap();
|
||||
let mask = kept.iter().position(|k| k.1).unwrap();
|
||||
assert!(carrier < mask, "{kept:?}");
|
||||
assert!(kept[carrier..].iter().all(|k| k.0) && kept[mask..].iter().all(|k| k.1), "{kept:?}");
|
||||
}
|
||||
|
||||
/// A cut clipping object with an opacity mask alone gets no unpainted object when its mask's art
|
||||
/// doesn't fit: an object without the dictionary it was written for would be extra art.
|
||||
#[test]
|
||||
fn a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let members = vec![
|
||||
square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)),
|
||||
square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)),
|
||||
];
|
||||
let mut cutter = group(&mut doc, members, false);
|
||||
let veil = vec![
|
||||
square(&mut doc, Rect::new(20.0, 20.0, 40.0, 40.0), Color::rgb(1.0, 1.0, 1.0)),
|
||||
square(&mut doc, Rect::new(40.0, 40.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)),
|
||||
];
|
||||
let veil = group(&mut doc, veil, false);
|
||||
cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false)));
|
||||
let top = group(&mut doc, vec![cutter], true);
|
||||
doc.insert(Some(layer), usize::MAX, top).unwrap();
|
||||
let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
|
||||
for room in 0..=all {
|
||||
let out = export_within(&doc, &opts(), room).unwrap();
|
||||
let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
|
||||
let (back, _) = crate::ai_alone(&out.program).unwrap();
|
||||
let mut carriers = vec![];
|
||||
back.layers[0].walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty() {
|
||||
carriers.push(n.extras().mask.is_some());
|
||||
}
|
||||
});
|
||||
assert!(carriers.is_empty() || carriers == [true], "{room}: {carriers:?}\n{text}");
|
||||
assert_eq!(carriers.is_empty(), !text.contains("(AI9_Mask)"), "{room}\n{text}");
|
||||
if room == all {
|
||||
assert_eq!(carriers, [true], "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1231,17 +1231,19 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
|
||||
/// A container's members, the first one's outline cutting the others: its fills painted
|
||||
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text
|
||||
/// wrap options are written once, under them all ([`Self::wrap_carrier`]), and not with its fills
|
||||
/// or strokes, which may be cut or left out.
|
||||
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its name,
|
||||
/// variables and text wrap options are written once, under them all, with its opacity mask
|
||||
/// ([`Self::object_carrier`]), and not with its fills or strokes, which may be cut or left out
|
||||
/// and keep only the opacity mask they are drawn through.
|
||||
fn clip_contents(&mut self, children: &[Arc<Node>]) {
|
||||
let Some((first, rest)) = children.split_first() else { return };
|
||||
self.wrap_carrier(first);
|
||||
self.object_carrier(first);
|
||||
// Nothing to clip by hides the clipped art.
|
||||
let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return };
|
||||
let mut paint = first.clip_paint();
|
||||
for part in [&mut paint.fill, &mut paint.stroke].into_iter().flatten() {
|
||||
part.extras_mut().wrap = None;
|
||||
part.name = None;
|
||||
}
|
||||
let outer = self.clip.clone();
|
||||
let region = self.cut(&PathData::from_bezpath(&outline), rule);
|
||||
@@ -1258,26 +1260,46 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The text wrap options of clipping object `first`, when it has them, on an unpainted path
|
||||
/// (a compound path for several subpaths) of the outline area type wraps around
|
||||
/// ([`vectorcraft_doc::text::wrap_outline`]), uncut, locked and hidden as `first` is. Nothing is
|
||||
/// written for an empty outline or without room for the path ([`Self::take_objects`]).
|
||||
fn wrap_carrier(&mut self, first: &Node) {
|
||||
let Some(wrap) = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return };
|
||||
let outline = vectorcraft_doc::text::wrap_outline(first);
|
||||
if outline.is_empty() {
|
||||
/// The dictionary of clipping object `first` ([`Self::dictionary`]: its name, visibility
|
||||
/// variables, text wrap options and opacity mask), when it has one, on an unpainted path (a
|
||||
/// compound path for several subpaths), uncut, locked and hidden as `first` is. The path is the
|
||||
/// outline area type wraps around when `first` has text wrap options
|
||||
/// ([`vectorcraft_doc::text::wrap_outline`]); else, and without the options when that outline is
|
||||
/// empty, `first`'s clipping outline, or the rectangle of its bounds when it has none. Nothing
|
||||
/// is written without such a path, or without room for the path ([`Self::take_objects`]), or
|
||||
/// when the dictionary would be empty (an opacity mask left out with nothing else in it).
|
||||
fn object_carrier(&mut self, first: &Node) {
|
||||
let points = |p: &PathData| p.subpaths.iter().any(|sp| !sp.anchors.is_empty());
|
||||
let wrap = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look);
|
||||
let wrap_outline = wrap.map(|_| vectorcraft_doc::text::wrap_outline(first)).filter(points);
|
||||
let named = first.name.as_deref().is_some_and(|s| !s.is_empty());
|
||||
let bound = !self.bound_variables(first, false, false).is_empty();
|
||||
if wrap_outline.is_none() && !named && !bound && first.extras().mask.is_none() {
|
||||
return;
|
||||
}
|
||||
let wrapped = wrap_outline.is_some();
|
||||
let outline = wrap_outline
|
||||
.or_else(|| vectorcraft_effects::clip_outline(first).map(|(o, _)| PathData::from_bezpath(&o)).filter(points))
|
||||
.or_else(|| finite_bounds(first).map(shapes::rectangle));
|
||||
let Some(outline) = outline else { return };
|
||||
let (start, state, gs, objects) = (self.body.len(), self.state, self.gs, self.objects);
|
||||
self.state(first.locked, !first.visible);
|
||||
let start = self.body.len();
|
||||
self.plain_object(&outline, FillRule::NonZero, None, None, Xy::of(first).object());
|
||||
if self.body.len() == start {
|
||||
if self.objects == objects {
|
||||
// Without the path, its lock and hidden lines are taken out too, and no dictionary follows.
|
||||
self.body.truncate(start);
|
||||
self.state = state;
|
||||
return;
|
||||
}
|
||||
self.block_end = usize::MAX;
|
||||
self.body.push_str("%_/ArtDictionary :\n");
|
||||
self.text_wrap(wrap);
|
||||
self.body.push_str("%_;\n%_\n");
|
||||
let path_end = self.body.len();
|
||||
// Text wrap options go only on the outline area type wraps around.
|
||||
self.wrap_moved = !wrapped;
|
||||
self.dictionary(first);
|
||||
if self.body.len() == path_end {
|
||||
self.body.truncate(start);
|
||||
(self.state, self.gs, self.objects) = (state, gs, objects);
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path.
|
||||
|
||||
@@ -233,7 +233,8 @@ fn tick(t: TickLength) -> u8 {
|
||||
}
|
||||
|
||||
/// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across
|
||||
/// the top, every series of the graph's type, one value axis on the left, lines not filled, no graph
|
||||
/// the top, every series of the graph's type, one value axis on the left, lines not filled and no
|
||||
/// Line Width of their own, no graph
|
||||
/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most
|
||||
/// [`MAX_TICK_MARKS`] tick marks a division.
|
||||
fn settings_kept(g: &GraphSpec) -> bool {
|
||||
@@ -244,6 +245,7 @@ fn settings_kept(g: &GraphSpec) -> bool {
|
||||
&& !g.separate_scales
|
||||
&& g.right_series.is_empty()
|
||||
&& !g.filled_lines
|
||||
&& g.line_width.is_none()
|
||||
&& g.series_markers.iter().all(Option::is_none)
|
||||
&& g.series_columns.iter().all(Option::is_none)
|
||||
&& g.label_styles == LabelStyles::default()
|
||||
@@ -514,6 +516,7 @@ pub(crate) mod sample {
|
||||
cases.extend([
|
||||
("no legend", with(&|g| g.legend = false)),
|
||||
("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))),
|
||||
("a filled line width", with(&|g| (g.kind, g.line_width) = (GraphKind::Line, Some(8.0)))),
|
||||
("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])),
|
||||
("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])),
|
||||
("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])),
|
||||
|
||||
@@ -1544,6 +1544,8 @@ fn headless_backend_methods() {
|
||||
let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap();
|
||||
assert_eq!(selected["tool"], tool.id);
|
||||
}
|
||||
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
|
||||
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
|
||||
assert!(h.call("ui.resize", json!({})).is_err());
|
||||
}
|
||||
|
||||
|
||||
@@ -854,7 +854,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.cropImage",
|
||||
"Crop Image",
|
||||
"",
|
||||
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error",
|
||||
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
|
||||
),
|
||||
("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"),
|
||||
(
|
||||
@@ -979,7 +979,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), li
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, v
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
@@ -1396,7 +1396,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.exportAs",
|
||||
"Export As…",
|
||||
"",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ, or a file that carries the native document, is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
|
||||
),
|
||||
(
|
||||
"ui.fileInfoDialog",
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places
|
||||
//! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along
|
||||
//! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes
|
||||
//! ([`divide_dashes`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch
|
||||
//! two or three shapes ([`tangent_circles`]).
|
||||
//! ([`divide_dashes`]), 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`]).
|
||||
|
||||
mod crossings;
|
||||
mod dashes;
|
||||
@@ -14,6 +15,7 @@ pub mod shapes;
|
||||
mod shared_edge;
|
||||
mod slide;
|
||||
mod tangent_circle;
|
||||
mod tangents;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod trim;
|
||||
@@ -31,6 +33,7 @@ pub use shared_edge::{
|
||||
};
|
||||
pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at};
|
||||
pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLES, TangentCircleError, tangent_circle_segments, tangent_circles};
|
||||
pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents};
|
||||
pub use trim::{Span, slice, span_at, spans, without_spans};
|
||||
|
||||
use crate::fit::{end_tangent, start_tangent};
|
||||
|
||||
@@ -0,0 +1,895 @@
|
||||
//! Common Tangents: the straight lines that touch two convex closed outlines (ellipses at any
|
||||
//! rotation and scale, and convex Bézier paths) without crossing into either. An external tangent
|
||||
//! has both outlines on the same side of it; an internal one runs between them.
|
||||
//!
|
||||
//! A line with unit normal `n` touches an outline from outside where `p · n` reaches the
|
||||
//! outline's support value `h(n)`, the largest `p · n` over its points. External tangents are the
|
||||
//! normals where both outlines have the same support value, internal ones where `h₁(n) = -h₂(-n)`.
|
||||
//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with
|
||||
//! sampled minima refined too so that a double root (outlines that touch) or two roots between
|
||||
//! neighboring samples are kept.
|
||||
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
use kurbo::{Affine, CubicBez, ParamCurve, Point, Vec2};
|
||||
use vectorcraft_geom::SubPath;
|
||||
|
||||
/// Most segments one outline may have.
|
||||
pub const MAX_TANGENT_SEGMENTS: usize = 10_000;
|
||||
/// Normal directions sampled around the circle before refining.
|
||||
const SAMPLES: usize = 720;
|
||||
/// Steps of bisection or golden-section search for each root.
|
||||
const STEPS: usize = 64;
|
||||
/// Straight pieces each segment is cut into to check that a path is convex and to find its center.
|
||||
const FLATTEN: usize = 32;
|
||||
|
||||
/// Which side of a tangent the two outlines lie on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TangentKind {
|
||||
/// Both on the same side.
|
||||
External,
|
||||
/// One on each side.
|
||||
Internal,
|
||||
}
|
||||
|
||||
/// One common tangent: the stretch of the line from where it touches the first outline to where
|
||||
/// it touches the second. Where the outlines touch each other at one point, the stretch is
|
||||
/// centered on that point and as long as the narrower outline is wide along the line, and `from`
|
||||
/// is the end with the lower position along the line.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Tangent {
|
||||
pub kind: TangentKind,
|
||||
pub from: Point,
|
||||
pub to: Point,
|
||||
}
|
||||
|
||||
/// Why [`Outline::convex`] or [`Outline::ellipse`] cannot take a shape.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OutlineError {
|
||||
/// The path is open.
|
||||
Open,
|
||||
/// The path bends inward somewhere, or winds around more than once.
|
||||
NotConvex,
|
||||
/// No area, or not finite.
|
||||
Empty,
|
||||
/// More than [`MAX_TANGENT_SEGMENTS`] segments.
|
||||
TooComplex,
|
||||
}
|
||||
|
||||
/// The two outlines are the same, so every line touching one touches the other.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Coincide;
|
||||
|
||||
/// A convex closed outline that [`common_tangents`] takes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Outline {
|
||||
/// The unit circle under an affine map: the center is the map's translation, `m` its linear
|
||||
/// part (`[a, b, c, d]`, as kurbo orders them).
|
||||
Ellipse { center: Point, m: [f64; 4] },
|
||||
/// A convex closed path's segments, its center of area and the diagonal of its bounds. `ccw`
|
||||
/// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then
|
||||
/// comes later in the list as the angle of `n` grows.
|
||||
Convex { segments: Vec<CubicBez>, center: Point, size: f64, ccw: bool },
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
/// The ellipse that `unit` maps the unit circle onto.
|
||||
pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> {
|
||||
let [a, b, c, d, e, f] = unit.as_coeffs();
|
||||
let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs());
|
||||
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] })
|
||||
}
|
||||
|
||||
/// A closed subpath that bends one way all around and winds around once.
|
||||
pub fn convex(sp: &SubPath) -> Result<Self, OutlineError> {
|
||||
if !sp.closed {
|
||||
return Err(OutlineError::Open);
|
||||
}
|
||||
let n = sp.segment_count();
|
||||
if n > MAX_TANGENT_SEGMENTS {
|
||||
return Err(OutlineError::TooComplex);
|
||||
}
|
||||
let segments: Vec<CubicBez> = (0..n).map(|k| sp.segment(k)).collect();
|
||||
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if segments.iter().any(|s| ![s.p0, s.p1, s.p2, s.p3].into_iter().all(finite)) {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
let mut pts: Vec<Point> = Vec::with_capacity(n * FLATTEN);
|
||||
for s in &segments {
|
||||
pts.extend((0..FLATTEN).map(|k| s.eval(k as f64 / FLATTEN as f64)));
|
||||
}
|
||||
let (lo, hi) = pts.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| {
|
||||
(Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))
|
||||
});
|
||||
let size = (hi - lo).hypot();
|
||||
if !size.is_finite() || size <= 0.0 {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
// Points closer than this to the one before are dropped: a retracted handle or a segment
|
||||
// of no length gives no direction.
|
||||
pts.dedup_by(|b, a| (*b - *a).hypot() <= 1e-9 * size);
|
||||
while pts.len() > 1 && pts.first().zip(pts.last()).is_some_and(|(f, l)| (*f - *l).hypot() <= 1e-9 * size) {
|
||||
pts.pop();
|
||||
}
|
||||
let m = pts.len();
|
||||
if m < 3 {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
// Area, center and turns are worked out on the points taken about the first one and
|
||||
// divided by the size.
|
||||
let origin = pts[0].to_vec2();
|
||||
let unit: Vec<Vec2> = pts.iter().map(|p| (p.to_vec2() - origin) / size).collect();
|
||||
let (mut area2, mut cx, mut cy) = (0.0, 0.0, 0.0);
|
||||
for i in 0..m {
|
||||
let (p, q) = (unit[i], unit[(i + 1) % m]);
|
||||
let cross = p.cross(q);
|
||||
area2 += cross;
|
||||
cx += (p.x + q.x) * cross;
|
||||
cy += (p.y + q.y) * cross;
|
||||
}
|
||||
if area2.abs() <= 1e-12 {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
let sign = area2.signum();
|
||||
// Every turn the same way (straight runs allowed), and one turn in all.
|
||||
let mut turning = 0.0;
|
||||
for i in 0..m {
|
||||
let (p, q, r) = (unit[(i + m - 1) % m], unit[i], unit[(i + 1) % m]);
|
||||
let (u, v) = (q - p, r - q);
|
||||
let cross = u.cross(v) * sign;
|
||||
if cross < -1e-12 {
|
||||
return Err(OutlineError::NotConvex);
|
||||
}
|
||||
turning += cross.atan2(u.dot(v));
|
||||
}
|
||||
if (turning - TAU).abs() > 1e-6 {
|
||||
return Err(OutlineError::NotConvex);
|
||||
}
|
||||
// A short bend the other way can lie between two of the points: each segment is checked
|
||||
// whole.
|
||||
if segments.iter().any(|s| bends_against(s, sign)) {
|
||||
return Err(OutlineError::NotConvex);
|
||||
}
|
||||
let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point();
|
||||
if !center.x.is_finite() || !center.y.is_finite() {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
Ok(Outline::Convex { segments, center, size, ccw: sign > 0.0 })
|
||||
}
|
||||
|
||||
/// The outline moved by `d`.
|
||||
fn shifted(&self, d: Vec2) -> Self {
|
||||
match self {
|
||||
Outline::Ellipse { center, m } => Outline::Ellipse { center: *center + d, m: *m },
|
||||
Outline::Convex { segments, center, size, ccw } => Outline::Convex {
|
||||
segments: segments.iter().map(|s| CubicBez::new(s.p0 + d, s.p1 + d, s.p2 + d, s.p3 + d)).collect(),
|
||||
center: *center + d,
|
||||
size: *size,
|
||||
ccw: *ccw,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` the normal angles where the point of largest `p · n` can pass from one
|
||||
/// segment to the next: square to each segment's direction at its ends, on both sides.
|
||||
fn breaks(&self, out: &mut Vec<f64>) {
|
||||
let Outline::Convex { segments, .. } = self else { return };
|
||||
let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot2() > 0.0);
|
||||
for s in segments {
|
||||
let ends = [nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]), nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])];
|
||||
for d in ends.into_iter().flatten() {
|
||||
let a = d.y.atan2(d.x);
|
||||
out.extend([a + TAU / 4.0, a - TAU / 4.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The support value at `n` and the segment it is reached on, from every segment.
|
||||
fn support_scan(&self, n: Vec2) -> (f64, usize) {
|
||||
match self {
|
||||
Outline::Ellipse { .. } => (self.support(n), 0),
|
||||
Outline::Convex { segments, .. } => {
|
||||
let mut best = (f64::MIN, 0);
|
||||
for (i, s) in segments.iter().enumerate() {
|
||||
each_extreme(s, n, |_, v| {
|
||||
if v > best.0 {
|
||||
best = (v, i);
|
||||
}
|
||||
});
|
||||
}
|
||||
best
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The support value at `n` and the segment it is reached on, walking on from segment `from`,
|
||||
/// where the support value was reached at a normal angle a little less than `n`'s.
|
||||
fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) {
|
||||
match self {
|
||||
Outline::Ellipse { .. } => (self.support(n), 0),
|
||||
Outline::Convex { segments, ccw, .. } => {
|
||||
let len = segments.len();
|
||||
if len == 0 {
|
||||
return (f64::MIN, 0);
|
||||
}
|
||||
let step = if *ccw { 1 } else { len - 1 };
|
||||
let value = |i: usize| {
|
||||
let mut best = f64::MIN;
|
||||
if let Some(s) = segments.get(i) {
|
||||
each_extreme(s, n, |_, v| best = best.max(v));
|
||||
}
|
||||
best
|
||||
};
|
||||
let mut i = from % len;
|
||||
let mut v = value(i);
|
||||
for _ in 0..len {
|
||||
let j = (i + step) % len;
|
||||
let w = value(j);
|
||||
if w < v {
|
||||
break;
|
||||
}
|
||||
(i, v) = (j, w);
|
||||
}
|
||||
(v, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The center: an ellipse's, or a path's center of area.
|
||||
pub fn center(&self) -> Point {
|
||||
match self {
|
||||
Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center,
|
||||
}
|
||||
}
|
||||
|
||||
/// The diagonal of the bounds (an ellipse's: of the box its axes span).
|
||||
fn size(&self) -> f64 {
|
||||
match self {
|
||||
Outline::Ellipse { m, .. } => {
|
||||
let [a, b, c, d] = *m;
|
||||
2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt()
|
||||
}
|
||||
Outline::Convex { size, .. } => *size,
|
||||
}
|
||||
}
|
||||
|
||||
/// The support value: the largest `p · n` over the outline's points.
|
||||
fn support(&self, n: Vec2) -> f64 {
|
||||
match self {
|
||||
Outline::Ellipse { center, m: [a, b, c, d] } => center.to_vec2().dot(n) + Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y).hypot(),
|
||||
Outline::Convex { segments, .. } => {
|
||||
let mut best = f64::MIN;
|
||||
for s in segments {
|
||||
each_extreme(s, n, |_, v| best = best.max(v));
|
||||
}
|
||||
best
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of the outline on the line `p · n = h`, its support value: the point where
|
||||
/// `p · n` is largest, and the ends of any straight side along the line. Another point counts
|
||||
/// when it lies within `tol` of the line plus `slope` times its distance from that largest
|
||||
/// point, where `slope` is how far off the normal's angle may be.
|
||||
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec<Point> {
|
||||
match self {
|
||||
Outline::Ellipse { center, m: [a, b, c, d] } => {
|
||||
let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y);
|
||||
let w = w / w.hypot();
|
||||
vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)]
|
||||
}
|
||||
Outline::Convex { segments, .. } => {
|
||||
let mut all = vec![];
|
||||
for s in segments {
|
||||
each_extreme(s, n, |p, v| all.push((p, v)));
|
||||
}
|
||||
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
|
||||
all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
|
||||
/// the curve runs square to `n`) and the value there.
|
||||
/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product
|
||||
/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared
|
||||
/// with the segment's control polygon length squared.
|
||||
fn bends_against(s: &CubicBez, sign: f64) -> bool {
|
||||
let (a, b, c) = (s.p1 - s.p0, s.p2 - s.p1, s.p3 - s.p2);
|
||||
let q = |t: f64| {
|
||||
let u = 1.0 - t;
|
||||
let d1 = a * (u * u) + b * (2.0 * u * t) + c * (t * t);
|
||||
let d2 = (b - a) * u + (c - b) * t;
|
||||
d1.cross(d2) * sign
|
||||
};
|
||||
let (q0, half, q1) = (q(0.0), q(0.5), q(1.0));
|
||||
// q(t) = q0 + k1 t + k2 t².
|
||||
let k2 = 2.0 * (q0 + q1 - 2.0 * half);
|
||||
let k1 = q1 - q0 - k2;
|
||||
let mut low = q0.min(q1);
|
||||
if k2 > 0.0 {
|
||||
let t = -k1 / (2.0 * k2);
|
||||
if t > 0.0 && t < 1.0 {
|
||||
low = low.min(q(t));
|
||||
}
|
||||
}
|
||||
let scale = (a.hypot() + b.hypot() + c.hypot()).powi(2);
|
||||
low < -1e-9 * scale
|
||||
}
|
||||
|
||||
fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) {
|
||||
let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n));
|
||||
f(s.p0, v0);
|
||||
f(s.p3, v3);
|
||||
// The derivative of p(t) · n, divided by 3: a quadratic in t.
|
||||
let (d0, d1, d2) = (v1 - v0, v2 - v1, v3 - v2);
|
||||
let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);
|
||||
let mut root = |t: f64| {
|
||||
if t > 0.0 && t < 1.0 {
|
||||
let p = s.eval(t);
|
||||
f(p, p.to_vec2().dot(n));
|
||||
}
|
||||
};
|
||||
let scale = qa.abs().max(qb.abs()).max(qc.abs());
|
||||
if !scale.is_finite() || scale <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if qa.abs() <= 1e-12 * scale {
|
||||
if qb != 0.0 {
|
||||
root(-qc / qb);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let disc = qb * qb - 4.0 * qa * qc;
|
||||
if disc < 0.0 {
|
||||
return;
|
||||
}
|
||||
// The stable form of the two roots; with `qb` zero the sign is taken as positive, so `q` is
|
||||
// not zero.
|
||||
let sign = if qb < 0.0 { -1.0 } else { 1.0 };
|
||||
let q = -0.5 * (qb + sign * disc.sqrt());
|
||||
root(q / qa);
|
||||
if q != 0.0 {
|
||||
root(qc / q);
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit vector at `angle` radians.
|
||||
fn dir(angle: f64) -> Vec2 {
|
||||
Vec2::new(angle.cos(), angle.sin())
|
||||
}
|
||||
|
||||
/// The common tangents of `a` and `b`: the external ones, then the internal ones, each in order of
|
||||
/// the angle of its normal. Separate outlines have two of each; overlapping ones only external
|
||||
/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the
|
||||
/// other none; outlines that touch share one tangent where they touch.
|
||||
pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincide> {
|
||||
// Worked out about the point between the two centers.
|
||||
let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0;
|
||||
let (a, b) = (&a.shifted(-origin), &b.shifted(-origin));
|
||||
let size = a.size().max(b.size()).max((a.center() - b.center()).hypot());
|
||||
let tol = 1e-9 * size;
|
||||
// The normal angles sampled: evenly spaced ones, and every angle where the support value of
|
||||
// either outline passes to another segment. Between two neighboring samples each outline is
|
||||
// then touched on one segment.
|
||||
let mut at: Vec<f64> = (0..SAMPLES).map(|k| k as f64 * TAU / SAMPLES as f64).collect();
|
||||
a.breaks(&mut at);
|
||||
b.breaks(&mut at);
|
||||
let mut at: Vec<f64> = at.into_iter().map(|t| t.rem_euclid(TAU)).map(|t| if t < TAU { t } else { 0.0 }).collect();
|
||||
at.sort_by(f64::total_cmp);
|
||||
at.dedup_by(|y, x| *y - *x <= 1e-12);
|
||||
// The segment each outline is touched on at each sample, found by walking around once.
|
||||
let hints = |o: &Outline, sign: f64| -> Vec<usize> {
|
||||
let mut out = Vec::with_capacity(at.len());
|
||||
let mut i = at.first().map_or(0, |t| o.support_scan(dir(*t) * sign).1);
|
||||
for t in &at {
|
||||
i = o.support_from(dir(*t) * sign, i).1;
|
||||
out.push(i);
|
||||
}
|
||||
out
|
||||
};
|
||||
let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0));
|
||||
let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0);
|
||||
let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?;
|
||||
let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?;
|
||||
let mut out = Vec::with_capacity(external.len() + internal.len());
|
||||
for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] {
|
||||
for root in list {
|
||||
let t = tangent_at(a, b, kind, dir(root.angle), root.double, size);
|
||||
out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t });
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A zero of a support-value difference: the normal's angle, and whether the difference only
|
||||
/// touches zero there (outlines that touch) rather than crossing it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Root {
|
||||
angle: f64,
|
||||
double: bool,
|
||||
}
|
||||
|
||||
/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value,
|
||||
/// and `b` on the same side (external) or the other side (internal). `double` when the outlines
|
||||
/// touch there.
|
||||
fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent {
|
||||
// The rounding allowed in `p · n` grows with each outline's own size and its distance from the
|
||||
// origin.
|
||||
let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size());
|
||||
let (tol_a, tol_b) = (rounding(a), rounding(b));
|
||||
// Bisection finds a simple root's angle to about the rounding of the support values; the
|
||||
// golden-section search finds a double root's to about 1e-8 radians.
|
||||
let slope = if double { 1e-7 } else { 1e-10 };
|
||||
let ha = a.support(n);
|
||||
let (on_a, on_b) = match kind {
|
||||
TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)),
|
||||
TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)),
|
||||
};
|
||||
// Positions along the line, which runs square to `n` through `n * ha`.
|
||||
let t = Vec2::new(-n.y, n.x);
|
||||
let along = |p: &Point| p.to_vec2().dot(t);
|
||||
let mean = |v: &[Point]| v.iter().map(along).sum::<f64>() / v.len().max(1) as f64;
|
||||
let all = on_a.iter().chain(&on_b).map(along);
|
||||
let (lo, hi) = all.fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(s), hi.max(s)));
|
||||
let at = |s: f64| (n * ha + t * s).to_point();
|
||||
// A double root's angle is found less exactly than a simple one's, so touching points may
|
||||
// stand a little apart.
|
||||
let (from, to) = if double && hi - lo <= 1e-6 * size {
|
||||
// Touching at one point: the narrower outline's width along the line, centered there.
|
||||
let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min);
|
||||
let mid = (lo + hi) / 2.0;
|
||||
(mid - width / 2.0, mid + width / 2.0)
|
||||
} else if mean(&on_a) <= mean(&on_b) {
|
||||
(lo, hi)
|
||||
} else {
|
||||
(hi, lo)
|
||||
};
|
||||
Tangent { kind, from: at(from), to: at(to) }
|
||||
}
|
||||
|
||||
/// The angles in `[0, 2π)` where `f` (periodic) is zero, within `tol`. An interval where it stays
|
||||
/// zero (outlines that meet at a corner or along a shared stretch) gives the angle at its middle,
|
||||
/// as a double root.
|
||||
///
|
||||
/// `at` holds the sampled angles in increasing order, in `[0, 2π)`; `f(t, k)` is `f` at an angle
|
||||
/// `t` at or after sample `k` and before the sample two on.
|
||||
fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result<Vec<Root>, Coincide> {
|
||||
let n = at.len();
|
||||
if n < 3 {
|
||||
return Err(Coincide);
|
||||
}
|
||||
// The angle of sample `k + j`, counted on from sample `k` past 2π.
|
||||
let ang = |k: usize, j: usize| at.get((k + j) % n).copied().unwrap_or(0.0) + TAU * ((k + j) / n) as f64;
|
||||
let v: Vec<f64> = (0..n).map(|k| f(ang(k, 0), k)).collect();
|
||||
let val = |k: usize| v.get(k % n).copied().unwrap_or(0.0);
|
||||
let zero = |x: f64| x.abs() <= tol;
|
||||
let Some(start) = v.iter().position(|x| !zero(*x)) else { return Err(Coincide) };
|
||||
let simple = |angle: f64| Root { angle, double: false };
|
||||
let mut out = vec![];
|
||||
// Between `lo` (sample `k`) and `hi`, where `s * f` is positive at both ends: the least of
|
||||
// `s * f`, a double root where it reaches zero, two roots where it goes past it, none where it
|
||||
// stays above.
|
||||
let dip = |out: &mut Vec<Root>, s: f64, k: usize, lo: f64, hi: f64| {
|
||||
let g = |t: f64| f(t, k);
|
||||
let (t, least) = golden(&|t| s * g(t), lo, hi);
|
||||
if least < -tol {
|
||||
out.push(simple(bisect(&g, lo, t)));
|
||||
out.push(simple(bisect(&g, t, hi)));
|
||||
} else if least <= tol {
|
||||
out.push(Root { angle: t, double: true });
|
||||
}
|
||||
};
|
||||
for i in 0..n {
|
||||
let k = (start + i) % n;
|
||||
let (prev, next) = ((k + n - 1) % n, k + 1);
|
||||
let theta = ang(k, 0);
|
||||
if zero(val(k)) {
|
||||
continue;
|
||||
}
|
||||
if zero(val(next)) {
|
||||
let len = (1..n).take_while(|j| zero(val(k + j))).count();
|
||||
if len == 1 {
|
||||
// One sample on zero: a crossing when the samples beside it differ in sign, else a
|
||||
// dip between them.
|
||||
let (lo, hi) = (theta, ang(k, 2));
|
||||
let s = val(k).signum();
|
||||
if val(k + 2).signum() == s {
|
||||
dip(&mut out, s, k, lo, hi);
|
||||
} else {
|
||||
out.push(simple(bisect(&|t| f(t, k), lo, hi)));
|
||||
}
|
||||
} else {
|
||||
out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if val(k).signum() != val(next).signum() {
|
||||
out.push(simple(bisect(&|t| f(t, k), theta, ang(k, 1))));
|
||||
continue;
|
||||
}
|
||||
// A sampled minimum of |f|: the curve may dip to zero (a double root), or across it and
|
||||
// back (two roots), between the neighboring samples.
|
||||
let (vp, vk, vn) = (val(prev), val(k), val(next));
|
||||
if !zero(vp) && vp.signum() == vk.signum() && vk.abs() < vp.abs() && vk.abs() <= vn.abs() {
|
||||
let lo = if k == 0 { ang(prev, 0) - TAU } else { ang(prev, 0) };
|
||||
dip(&mut out, vk.signum(), prev, lo, ang(k, 1));
|
||||
}
|
||||
}
|
||||
let mut out: Vec<Root> = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect();
|
||||
out.sort_by(|a, b| a.angle.total_cmp(&b.angle));
|
||||
out.dedup_by(|b, a| {
|
||||
let same = (b.angle - a.angle).abs() < 1e-7;
|
||||
a.double |= same && b.double;
|
||||
same
|
||||
});
|
||||
if out.len() > 1
|
||||
&& out.first().zip(out.last()).is_some_and(|(f, l)| f.angle + TAU - l.angle < 1e-7)
|
||||
&& let Some(last) = out.pop()
|
||||
&& let Some(first) = out.first_mut()
|
||||
{
|
||||
first.double |= last.double;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A root of `f` between `lo` and `hi`, where it has opposite signs.
|
||||
fn bisect(f: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> f64 {
|
||||
let s = f(lo).signum();
|
||||
for _ in 0..STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if f(mid).signum() == s {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
}
|
||||
|
||||
/// Where `g` is least between `lo` and `hi` (taken as having one minimum there), and its value.
|
||||
fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) {
|
||||
let r = (5f64.sqrt() - 1.0) / 2.0;
|
||||
let (mut x1, mut x2) = (hi - r * (hi - lo), lo + r * (hi - lo));
|
||||
let (mut g1, mut g2) = (g(x1), g(x2));
|
||||
for _ in 0..STEPS {
|
||||
if g1 < g2 {
|
||||
hi = x2;
|
||||
(x2, g2) = (x1, g1);
|
||||
x1 = hi - r * (hi - lo);
|
||||
g1 = g(x1);
|
||||
} else {
|
||||
lo = x1;
|
||||
(x1, g1) = (x2, g2);
|
||||
x2 = lo + r * (hi - lo);
|
||||
g2 = g(x2);
|
||||
}
|
||||
}
|
||||
let t = (lo + hi) / 2.0;
|
||||
(t, g(t))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use kurbo::Rect;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn circle(cx: f64, cy: f64, r: f64) -> Outline {
|
||||
Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap()
|
||||
}
|
||||
|
||||
/// An ellipse with semi-axes `rx`, `ry`, turned `deg` degrees, centered at (`cx`, `cy`).
|
||||
fn ellipse_map(cx: f64, cy: f64, rx: f64, ry: f64, deg: f64) -> Affine {
|
||||
Affine::translate((cx, cy)) * Affine::rotate(deg.to_radians()) * Affine::scale_non_uniform(rx, ry)
|
||||
}
|
||||
|
||||
/// Whether `t` has its two ends at `p` and `q`, in either order.
|
||||
fn ends_at(t: &Tangent, p: Point, q: Point) -> bool {
|
||||
ends_within(t, p, q, 1e-7)
|
||||
}
|
||||
|
||||
/// [`ends_at`] within `eps`: the angle of a tangent where outlines touch (a double root) is
|
||||
/// found to about 1e-8 radians.
|
||||
fn ends_within(t: &Tangent, p: Point, q: Point, eps: f64) -> bool {
|
||||
let near = |a: Point, b: Point| (a - b).hypot() < eps;
|
||||
(near(t.from, p) && near(t.to, q)) || (near(t.from, q) && near(t.to, p))
|
||||
}
|
||||
|
||||
/// Checks `t` against dense samples of the two outlines, without support values: each lies on
|
||||
/// one side of the line (the same side for an external tangent, opposite ones for an internal
|
||||
/// one) and comes within `eps` of it.
|
||||
fn check_against_samples(t: &Tangent, a: &[Point], b: &[Point], eps: f64) {
|
||||
let d = t.to - t.from;
|
||||
let n = Vec2::new(-d.y, d.x) / d.hypot();
|
||||
let side = |pts: &[Point]| {
|
||||
let dist: Vec<f64> = pts.iter().map(|p| (*p - t.from).dot(n)).collect();
|
||||
let (lo, hi) = dist.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s)));
|
||||
assert!(lo > -eps || hi < eps, "the line crosses the outline: {lo} .. {hi} ({t:?})");
|
||||
assert!(lo.abs() < eps || hi.abs() < eps, "the line misses the outline: {lo} .. {hi} ({t:?})");
|
||||
if hi < eps { -1.0 } else { 1.0 }
|
||||
};
|
||||
let (sa, sb) = (side(a), side(b));
|
||||
match t.kind {
|
||||
TangentKind::External => assert_eq!(sa, sb, "{t:?}"),
|
||||
TangentKind::Internal => assert_ne!(sa, sb, "{t:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_ellipse(m: Affine, count: usize) -> Vec<Point> {
|
||||
(0..count).map(|k| m * Point::new((TAU * k as f64 / count as f64).cos(), (TAU * k as f64 / count as f64).sin())).collect()
|
||||
}
|
||||
|
||||
fn sample_path(sp: &SubPath, per_segment: usize) -> Vec<Point> {
|
||||
(0..sp.segment_count()).flat_map(|k| (0..per_segment).map(move |j| sp.segment(k).eval(j as f64 / per_segment as f64))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_have_four_tangents_at_the_closed_form_points() {
|
||||
let (c1, r1, c2, r2) = (Point::new(0.0, 0.0), 10.0, Point::new(100.0, 0.0), 20.0);
|
||||
let all = common_tangents(&circle(c1.x, c1.y, r1), &circle(c2.x, c2.y, r2)).unwrap();
|
||||
assert_eq!(all.len(), 4, "{all:?}");
|
||||
// External: (c1 - c2) · n = r2 - r1, so n.x = -0.1; the points are c + r n on each.
|
||||
// Internal: (c1 - c2) · n = -(r1 + r2), so n.x = 0.3; c1 + r1 n and c2 - r2 n.
|
||||
for (kind, nx) in [(TangentKind::External, -0.1f64), (TangentKind::Internal, 0.3)] {
|
||||
for sy in [1.0, -1.0] {
|
||||
let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt());
|
||||
let far = if kind == TangentKind::External { c2 + n * r2 } else { c2 - n * r2 };
|
||||
let found = all.iter().filter(|t| t.kind == kind && ends_at(t, c1 + n * r1, far)).count();
|
||||
assert_eq!(found, 1, "{kind:?} {n:?} in {all:?}");
|
||||
}
|
||||
}
|
||||
// Each runs from the first outline to the second.
|
||||
assert!(all.iter().all(|t| (t.from - c1).hypot() < (t.to - c1).hypot()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_ellipses_match_an_independent_numeric_solution() {
|
||||
let (ma, mb) = (ellipse_map(0.0, 0.0, 40.0, 15.0, 30.0), ellipse_map(150.0, 60.0, 25.0, 60.0, -70.0));
|
||||
let all = common_tangents(&Outline::ellipse(ma).unwrap(), &Outline::ellipse(mb).unwrap()).unwrap();
|
||||
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}");
|
||||
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}");
|
||||
let (sa, sb) = (sample_ellipse(ma, 5_000), sample_ellipse(mb, 5_000));
|
||||
for t in &all {
|
||||
check_against_samples(t, &sa, &sb, 1e-3);
|
||||
}
|
||||
// A brute-force scan of the normal's angle with support values read off the samples finds
|
||||
// the same normals.
|
||||
let support = |pts: &[Point], n: Vec2| pts.iter().map(|p| p.to_vec2().dot(n)).fold(f64::MIN, f64::max);
|
||||
let scan = |f: &dyn Fn(Vec2) -> f64| {
|
||||
let steps = 7_200;
|
||||
let g = |k: usize| f(dir(TAU * k as f64 / steps as f64));
|
||||
(0..steps).filter(|&k| g(k).signum() != g((k + 1) % steps).signum()).map(|k| TAU * (k as f64 + 0.5) / steps as f64).collect::<Vec<_>>()
|
||||
};
|
||||
let ext = scan(&|n| support(&sa, n) - support(&sb, n));
|
||||
let int = scan(&|n| support(&sa, n) + support(&sb, -n));
|
||||
for (kind, expected) in [(TangentKind::External, ext), (TangentKind::Internal, int)] {
|
||||
assert_eq!(expected.len(), 2);
|
||||
for angle in expected {
|
||||
let n = dir(angle);
|
||||
let hit = all.iter().filter(|t| t.kind == kind).any(|t| {
|
||||
let d = t.to - t.from;
|
||||
let m = Vec2::new(d.y, -d.x) / d.hypot();
|
||||
m.dot(n).abs() > 1.0 - 1e-6
|
||||
});
|
||||
assert!(hit, "{kind:?} normal at {angle} in {all:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_overlapping_and_touching_circles() {
|
||||
// One inside the other: none.
|
||||
assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(5.0, 0.0, 10.0)).unwrap().is_empty());
|
||||
// Overlapping: the two external ones only.
|
||||
let over = common_tangents(&circle(0.0, 0.0, 30.0), &circle(40.0, 0.0, 30.0)).unwrap();
|
||||
assert_eq!(over.len(), 2);
|
||||
assert!(over.iter().all(|t| t.kind == TangentKind::External));
|
||||
assert!(over.iter().any(|t| ends_at(t, Point::new(0.0, 30.0), Point::new(40.0, 30.0))));
|
||||
// Touching from outside at (10, 0): two external ones and one shared internal one, square to
|
||||
// the line of centers, as long as the smaller circle is wide.
|
||||
let touch = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0, 0.0, 20.0)).unwrap();
|
||||
assert_eq!(touch.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{touch:?}");
|
||||
let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect();
|
||||
assert_eq!(shared.len(), 1, "{touch:?}");
|
||||
assert!(ends_within(shared[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{shared:?}");
|
||||
// Touching along a direction between two sampled normals: the sampled minimum is refined
|
||||
// down to the double root.
|
||||
let along = dir(0.1234);
|
||||
let off = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0 * along.x, 30.0 * along.y, 20.0)).unwrap();
|
||||
assert_eq!(off.iter().filter(|t| t.kind == TangentKind::Internal).count(), 1, "{off:?}");
|
||||
// A hair apart: two internal tangents less than a sample apart, both kept.
|
||||
let d = 30.000_01;
|
||||
let near_miss = common_tangents(&circle(0.0, 0.0, 10.0), &circle(d * along.x, d * along.y, 20.0)).unwrap();
|
||||
assert_eq!(near_miss.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{near_miss:?}");
|
||||
// Inside with a clearance of 1e-6: no tangent.
|
||||
assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0 - 1e-6, 0.0, 10.0)).unwrap().is_empty());
|
||||
// Equal circles a hair apart: the two external tangents run between their real contact
|
||||
// points, that hair apart, not as a touching tangent.
|
||||
let hair = common_tangents(&circle(0.0, 0.0, 30.0), &circle(1e-5, 0.0, 30.0)).unwrap();
|
||||
assert_eq!(hair.len(), 2, "{hair:?}");
|
||||
assert!(hair.iter().all(|t| ((t.to - t.from).hypot() - 1e-5).abs() < 1e-9), "{hair:?}");
|
||||
// Touching from inside at (50, 0): the one shared external tangent.
|
||||
let inside = common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0, 0.0, 10.0)).unwrap();
|
||||
assert_eq!(inside.len(), 1, "{inside:?}");
|
||||
assert!(ends_within(&inside[0], Point::new(50.0, -10.0), Point::new(50.0, 10.0), 1e-5), "{inside:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_convex_bezier_blob_and_an_ellipse_path() {
|
||||
// A lopsided convex blob of four curves.
|
||||
let a = |x: f64, y: f64, ix: f64, iy: f64, ox: f64, oy: f64| {
|
||||
vectorcraft_geom::Anchor::with_handles(Point::new(x, y), Point::new(ix, iy), Point::new(ox, oy))
|
||||
};
|
||||
let blob = SubPath::new(
|
||||
vec![
|
||||
a(0.0, 40.0, 0.0, 70.0, 0.0, 10.0),
|
||||
a(50.0, 0.0, 20.0, 0.0, 90.0, 0.0),
|
||||
a(110.0, 50.0, 110.0, 20.0, 110.0, 90.0),
|
||||
a(40.0, 100.0, 80.0, 100.0, 10.0, 100.0),
|
||||
],
|
||||
true,
|
||||
);
|
||||
let round = shapes::ellipse(Rect::new(200.0, 150.0, 260.0, 230.0)).subpaths[0].clone();
|
||||
let (oa, ob) = (Outline::convex(&blob).unwrap(), Outline::convex(&round).unwrap());
|
||||
let all = common_tangents(&oa, &ob).unwrap();
|
||||
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}");
|
||||
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}");
|
||||
let (sa, sb) = (sample_path(&blob, 4000), sample_path(&round, 4000));
|
||||
for t in &all {
|
||||
check_against_samples(t, &sa, &sb, 1e-3);
|
||||
}
|
||||
// The path's center is its center of area: the ellipse path's is its box's center.
|
||||
assert!((ob.center() - Point::new(230.0, 190.0)).hypot() < 1e-6, "{:?}", ob.center());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_sides_give_the_whole_stretch_they_touch() {
|
||||
let square =
|
||||
|x: f64| SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)], true);
|
||||
let all = common_tangents(&Outline::convex(&square(0.0)).unwrap(), &Outline::convex(&square(30.0)).unwrap()).unwrap();
|
||||
let ext: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::External).collect();
|
||||
assert_eq!(ext.len(), 2, "{all:?}");
|
||||
assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 0.0), Point::new(40.0, 0.0))), "{ext:?}");
|
||||
assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 10.0), Point::new(40.0, 10.0))), "{ext:?}");
|
||||
// Far apart, each diamond is still touched only at its top corner.
|
||||
let diamond =
|
||||
|x: f64| SubPath::polyline(&[Point::new(x - 5.0, 0.0), Point::new(x, -5.0), Point::new(x + 5.0, 0.0), Point::new(x, 5.0)], true);
|
||||
let far = common_tangents(&Outline::convex(&diamond(0.0)).unwrap(), &Outline::convex(&diamond(1e9)).unwrap()).unwrap();
|
||||
let top = far.iter().find(|t| t.kind == TangentKind::External && t.from.y > 0.0).unwrap();
|
||||
assert!(ends_within(top, Point::new(0.0, 5.0), Point::new(1e9, 5.0), 1e-3), "{far:?}");
|
||||
// Far from the origin the center of area and the tangents come out as near it.
|
||||
let o = 1e9;
|
||||
let away = |x: f64| SubPath::polyline(&[(x, o), (x + 10.0, o), (x + 10.0, o + 10.0), (x, o + 10.0)].map(Point::from), true);
|
||||
let (sa, sb) = (Outline::convex(&away(o)).unwrap(), Outline::convex(&away(o + 30.0)).unwrap());
|
||||
assert!((sa.center() - Point::new(o + 5.0, o + 5.0)).hypot() < 1e-6, "{:?}", sa.center());
|
||||
let shifted = common_tangents(&sa, &sb).unwrap();
|
||||
assert!(shifted.iter().any(|t| ends_within(t, Point::new(o, o), Point::new(o + 40.0, o), 1e-6)), "{shifted:?}");
|
||||
// The internal ones are the diagonals between the near corners.
|
||||
let int: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::Internal).collect();
|
||||
assert_eq!(int.len(), 2, "{all:?}");
|
||||
assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 0.0), Point::new(30.0, 10.0))), "{int:?}");
|
||||
assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 10.0), Point::new(30.0, 0.0))), "{int:?}");
|
||||
// Squares meeting at the corner (10, 10): every line through the corner between their
|
||||
// sides touches both, and the one internal line drawn is the one at the middle of those
|
||||
// directions, as long as a square is wide along it.
|
||||
let box_at = |x: f64, y: f64| {
|
||||
SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y), Point::new(x + 10.0, y + 10.0), Point::new(x, y + 10.0)], true)
|
||||
};
|
||||
let corner = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(10.0, 10.0)).unwrap()).unwrap();
|
||||
let shared: Vec<_> = corner.iter().filter(|t| t.kind == TangentKind::Internal).collect();
|
||||
assert_eq!(shared.len(), 1, "{corner:?}");
|
||||
assert!(ends_within(shared[0], Point::new(5.0, 15.0), Point::new(15.0, 5.0), 1e-6), "{shared:?}");
|
||||
// Sides 1e-6 off parallel: each line ends at the corners it touches, not at the corners
|
||||
// of the sides it nearly lies along.
|
||||
let tilted = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(30.0, -1e-6)).unwrap()).unwrap();
|
||||
let ext: Vec<_> = tilted.iter().filter(|t| t.kind == TangentKind::External).collect();
|
||||
assert_eq!(ext.len(), 2, "{tilted:?}");
|
||||
assert!(ext.iter().any(|t| ends_within(t, Point::new(10.0, 10.0), Point::new(40.0, 10.0 - 1e-6), 1e-6)), "{ext:?}");
|
||||
assert!(ext.iter().any(|t| ends_within(t, Point::new(0.0, 0.0), Point::new(30.0, -1e-6), 1e-6)), "{ext:?}");
|
||||
}
|
||||
|
||||
/// A circle path of four curves, radius 100 about the origin, with an anchor at (100, 0).
|
||||
fn circle_path() -> SubPath {
|
||||
shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).subpaths[0].clone()
|
||||
}
|
||||
|
||||
/// The point of `sp` where `p · n` is largest.
|
||||
fn peak(sp: &SubPath, n: Vec2) -> Point {
|
||||
let mut best = (Point::ORIGIN, f64::MIN);
|
||||
for k in 0..sp.segment_count() {
|
||||
each_extreme(&sp.segment(k), n, |p, v| {
|
||||
if v > best.1 {
|
||||
best = (p, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
best.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_is_touched_only_at_its_peak_beside_an_anchor() {
|
||||
// The line touches the circle path 5e-4 radians from its anchor at (100, 0), where the
|
||||
// anchor lies about 1.25e-5 inside the line: the line still ends at the peak, not at the
|
||||
// anchor 0.05 along it.
|
||||
let path = circle_path();
|
||||
let n = dir(5e-4);
|
||||
let away = Vec2::new(n.y, -n.x) * 300.0;
|
||||
let a = Outline::convex(&path).unwrap();
|
||||
let all = common_tangents(&a, &a.shifted(away)).unwrap();
|
||||
let top = all.iter().find(|t| t.kind == TangentKind::External && (t.from.to_vec2().dot(n) - 100.0).abs() < 1e-3).unwrap();
|
||||
let p = peak(&path, n);
|
||||
assert!(ends_within(top, p, p + away, 1e-6), "{top:?} {p:?}");
|
||||
// An exact circle touching the path there from outside: one shared internal line, as long
|
||||
// as that circle is wide, not a stub running to the anchor.
|
||||
let b = circle(p.x + 20.0 * n.x, p.y + 20.0 * n.y, 20.0);
|
||||
let touch = common_tangents(&a, &b).unwrap();
|
||||
let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect();
|
||||
assert_eq!(shared.len(), 1, "{touch:?}");
|
||||
assert!(((shared[0].to - shared[0].from).hypot() - 40.0).abs() < 1e-3, "{shared:?}");
|
||||
assert!(((shared[0].from.midpoint(shared[0].to)) - p).hypot() < 1e-3, "{shared:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlines_crossing_more_often_than_the_even_samples_keep_every_tangent() {
|
||||
// Two regular 400-gons about one center, one turned half a step: their outlines cross 800
|
||||
// times, and an external tangent runs across each crossing.
|
||||
let gon = |turn: f64| {
|
||||
let pts: Vec<Point> = (0..400).map(|k| (dir(turn + TAU * k as f64 / 400.0) * 100.0).to_point()).collect();
|
||||
SubPath::polyline(&pts, true)
|
||||
};
|
||||
let all = common_tangents(&Outline::convex(&gon(0.0)).unwrap(), &Outline::convex(&gon(TAU / 800.0)).unwrap()).unwrap();
|
||||
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 800);
|
||||
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 0);
|
||||
// Each runs between a corner of one and the next corner of the other, about 0.785 apart.
|
||||
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() {
|
||||
// p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is
|
||||
// zero, and the peak, 0.25 at t = 0.5, lies inside the segment.
|
||||
let s = CubicBez::new((0.0, 0.0), (1.0, 0.25), (2.0, 0.5), (3.0, -0.25));
|
||||
let mut best = f64::MIN;
|
||||
each_extreme(&s, Vec2::new(0.0, 1.0), |_, v| best = best.max(v));
|
||||
assert!((best - 0.25).abs() < 1e-12, "{best}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_concave_empty_and_identical_outlines_are_refused() {
|
||||
let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false);
|
||||
assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open));
|
||||
let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone();
|
||||
assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex));
|
||||
// A half disk whose straight side is a cubic with crossed handles: it bends the other way
|
||||
// for a short stretch between two of the points the outline is checked at.
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
let k = 0.5523 * 50.0;
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.curve_to((62.4, 43.4), (60.3, 44.2), (100.0, 0.0));
|
||||
bp.curve_to((100.0, -k), (50.0 + k, -50.0), (50.0, -50.0));
|
||||
bp.curve_to((50.0 - k, -50.0), (0.0, -k), (0.0, 0.0));
|
||||
bp.close_path();
|
||||
let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
|
||||
assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex));
|
||||
// A square traced twice around winds around twice.
|
||||
let twice: Vec<Point> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect();
|
||||
assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex));
|
||||
let flat = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(20.0, 0.0)], true);
|
||||
assert_eq!(Outline::convex(&flat).err(), Some(OutlineError::Empty));
|
||||
assert_eq!(Outline::ellipse(Affine::scale_non_uniform(10.0, 0.0)).err(), Some(OutlineError::Empty));
|
||||
assert_eq!(Outline::ellipse(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])).err(), Some(OutlineError::Empty));
|
||||
let many: Vec<Point> = (0..=MAX_TANGENT_SEGMENTS).map(|k| dir(TAU * k as f64 / (MAX_TANGENT_SEGMENTS + 1) as f64).to_point()).collect();
|
||||
assert_eq!(Outline::convex(&SubPath::polyline(&many, true)).err(), Some(OutlineError::TooComplex));
|
||||
// A square 1e110 wide has a finite center.
|
||||
let huge = SubPath::polyline(&[(0.0, 0.0), (1e110, 0.0), (1e110, 1e110), (0.0, 1e110)].map(Point::from), true);
|
||||
let center = Outline::convex(&huge).unwrap().center();
|
||||
assert!((center - Point::new(5e109, 5e109)).hypot() < 1e98, "{center:?}");
|
||||
assert_eq!(common_tangents(&circle(1.0, 2.0, 3.0), &circle(1.0, 2.0, 3.0)), Err(Coincide));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
//! PSD export: a layered bitmap at 8 bits per channel, written from the format's public
|
||||
//! specification. The file holds the header, the resolution and colour profile resources, the
|
||||
//! layer records and their channels (PackBits row by row; groups as section dividers), then the
|
||||
//! specification. The file holds the header, the resolution, colour profile and slices resources,
|
||||
//! the layer records and their channels (PackBits row by row; groups as section dividers), then the
|
||||
//! merged image, which readers that skip layers show. RGB, CMYK (stored as 255 − ink, as the
|
||||
//! format keeps inks) or grayscale.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, cms};
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind};
|
||||
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use super::jpeg::{self, ColorModel};
|
||||
@@ -302,6 +303,8 @@ struct File {
|
||||
records: Vec<Record>,
|
||||
ppi: f64,
|
||||
icc: Option<Arc<[u8]>>,
|
||||
/// Image resource 1050's data, when the file has slices.
|
||||
slices: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Refuse a size the format can't store.
|
||||
@@ -332,7 +335,8 @@ impl File {
|
||||
out.extend(mode(self.model).to_be_bytes());
|
||||
// No colour mode data.
|
||||
out.extend(0u32.to_be_bytes());
|
||||
// Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the profile.
|
||||
// Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the
|
||||
// profile, the slices.
|
||||
let ppi = if self.ppi.is_finite() && self.ppi > 0.0 { self.ppi } else { 72.0 };
|
||||
let fixed = (ppi.min(30_000.0) * 65536.0).round() as u32;
|
||||
let res = [fixed.to_be_bytes(), [0, 1, 0, 1], fixed.to_be_bytes(), [0, 1, 0, 1]].concat();
|
||||
@@ -341,6 +345,9 @@ impl File {
|
||||
if let Some(icc) = &self.icc {
|
||||
resource(&mut resources, 1039, icc)?;
|
||||
}
|
||||
if let Some(slices) = &self.slices {
|
||||
resource(&mut resources, SLICES, slices)?;
|
||||
}
|
||||
out.extend(len32(resources.len())?.to_be_bytes());
|
||||
out.extend(resources);
|
||||
self.write_layers(&mut out)?;
|
||||
@@ -390,17 +397,20 @@ fn icc(o: &PsdOptions) -> Result<Option<Arc<[u8]>>, String> {
|
||||
pub fn encode(img: &Rendered, ppi: f64, o: &PsdOptions) -> Result<Vec<u8>, String> {
|
||||
let inks = (o.color_model == ColorModel::Cmyk).then(|| jpeg::separated(img));
|
||||
let merged = planes(o.color_model, &img.to_straight(), inks.as_deref(), true, false);
|
||||
File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)? }.write()
|
||||
File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)?, slices: None }
|
||||
.write()
|
||||
}
|
||||
|
||||
/// `region` of `doc` as a PSD with `opts` (see [`PsdOptions`]). The merged image is the export's
|
||||
/// render; with Write Layers each part is also drawn alone as its own layer, cropped to what it
|
||||
/// paints, its opacity and blend mode in the layer's record.
|
||||
/// paints, its opacity and blend mode in the layer's record. The user and object slices that reach
|
||||
/// into `region` are written with or without layers ([`slices`]).
|
||||
pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &RasterExportOptions) -> Result<Vec<u8>, String> {
|
||||
let o = &opts.psd;
|
||||
let scale = opts.scale();
|
||||
let (width, height) = crate::region_pixels(region, scale);
|
||||
check_size(width, height)?;
|
||||
let slices = slices(doc, region, scale, (width, height))?;
|
||||
let ro = opts.render_options(RasterFormat::Psd);
|
||||
let (mut merged, mut alpha) = {
|
||||
let px = r.render_region_with(doc, region, scale, &ro).to_straight();
|
||||
@@ -426,7 +436,156 @@ pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &Rast
|
||||
merged.pop();
|
||||
alpha = false;
|
||||
}
|
||||
File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)? }.write()
|
||||
File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)?, slices }.write()
|
||||
}
|
||||
|
||||
/// The image resource that holds the slices.
|
||||
const SLICES: u16 = 1050;
|
||||
|
||||
/// The most slices one file holds (as many as `document.open` reads).
|
||||
pub(crate) const MAX_SLICES: usize = 10_000;
|
||||
|
||||
/// The longest text of a slice, in UTF-16 units (as long as `document.open` reads).
|
||||
pub(crate) const MAX_SLICE_TEXT: usize = 65_536;
|
||||
|
||||
/// Resource 1050's data for the user and object slices of `doc` that reach into `region`, in the
|
||||
/// "Slices resource format" of the Photoshop File Formats Specification
|
||||
/// (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>), version 6: the bounds of all
|
||||
/// the slices, the group's name, the count, then one record per slice. `None` when no slice
|
||||
/// reaches into `region`. Each rectangle is the slice as laid out ([`Document::slice_layout`]),
|
||||
/// clipped to `region` and given in the `size` canvas's pixels at `scale`, at least one pixel
|
||||
/// each way. Every slice is written as one the user made (origin 2): an object slice keeps its
|
||||
/// rectangle and options. Auto slices aren't written; a reader lays them out again. An HTML Text
|
||||
/// slice is written as No Image with its type's text as HTML. Text alignment is written as the
|
||||
/// default. An error when a slice's bounds aren't finite, or there are more than [`MAX_SLICES`]
|
||||
/// slices, a text longer than [`MAX_SLICE_TEXT`], or more than 4 GB of slices ([`room`]).
|
||||
fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Result<Option<Vec<u8>>, String> {
|
||||
let users: HashMap<NodeId, &SliceOptions> = doc.slices.iter().map(|s| (s.id, &s.options)).collect();
|
||||
let mut found = vec![];
|
||||
for area in doc.slice_layout().iter().filter(|a| a.source != SliceSource::Auto) {
|
||||
let Some(id) = area.id else { continue };
|
||||
let r = area.rect;
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
let number = area.number;
|
||||
return Err(format!("slice {number} has no finite bounds and can't be written to PSD"));
|
||||
}
|
||||
let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue };
|
||||
// The part inside `region`, found before the region is rounded to whole pixels.
|
||||
let (x0, y0, x1, y1) = (r.x0.max(region.x0), r.y0.max(region.y0), r.x1.min(region.x1), r.y1.min(region.y1));
|
||||
if !(x0 < x1 && y0 < y1) {
|
||||
continue;
|
||||
}
|
||||
let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max));
|
||||
let (l, t, r, b) = (edge(x0, region.x0, w), edge(y0, region.y0, h), edge(x1, region.x0, w), edge(y1, region.y0, h));
|
||||
// Whole pixels, at least one each way.
|
||||
let span = |a: f64, b: f64, max: u32| {
|
||||
let max = i64::from(max);
|
||||
let (mut a, mut b) = ((a.round() as i64).clamp(0, max), (b.round() as i64).clamp(0, max));
|
||||
if b <= a {
|
||||
a = a.min(max - 1);
|
||||
b = a + 1;
|
||||
}
|
||||
(a as i32, b as i32)
|
||||
};
|
||||
let ((l, r), (t, b)) = (span(l, r, w), span(t, b, h));
|
||||
let text = match options.kind {
|
||||
SliceKind::HtmlText => doc.node(id).map(html_text).unwrap_or_default(),
|
||||
_ => options.text.clone(),
|
||||
};
|
||||
found.push(([l, t, r, b], options, text));
|
||||
}
|
||||
if found.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if found.len() > MAX_SLICES {
|
||||
let count = found.len();
|
||||
return Err(format!("the document has {count} slices, more than the {MAX_SLICES} a PSD file holds"));
|
||||
}
|
||||
let (mut top, mut left, mut bottom, mut right) = (i32::MAX, i32::MAX, 0, 0);
|
||||
for ([l, t, r, b], _, _) in &found {
|
||||
(left, top, right, bottom) = (left.min(*l), top.min(*t), right.max(*r), bottom.max(*b));
|
||||
}
|
||||
let mut out = 6u32.to_be_bytes().to_vec();
|
||||
for v in [top, left, bottom, right] {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
let stem = doc.title.rsplit_once('.').map_or(doc.title.as_str(), |(s, _)| s);
|
||||
unicode(&mut out, stem)?;
|
||||
out.extend((found.len() as u32).to_be_bytes());
|
||||
// IDs from 1.
|
||||
for ((rect, o, text), id) in found.into_iter().zip(1u32..) {
|
||||
out.extend(id.to_be_bytes());
|
||||
// Group 0; made by the user.
|
||||
out.extend(0u32.to_be_bytes());
|
||||
out.extend(2u32.to_be_bytes());
|
||||
unicode(&mut out, &o.name)?;
|
||||
out.extend(u32::from(o.kind == SliceKind::Image).to_be_bytes());
|
||||
for v in rect {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
for s in [&o.url, &o.target, &o.message, &o.alt] {
|
||||
unicode(&mut out, s)?;
|
||||
}
|
||||
// The cell text is HTML, as a No Image slice shows it.
|
||||
out.push(1);
|
||||
unicode(&mut out, &text)?;
|
||||
// The default horizontal and vertical alignment.
|
||||
out.extend([0; 8]);
|
||||
out.extend(background(o));
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// A slice's background as alpha, red, green and blue: none (all 0), the matte (alpha 0 over a
|
||||
/// colour) or an opaque `#rrggbb`.
|
||||
fn background(o: &SliceOptions) -> [u8; 4] {
|
||||
let bg = o.background.trim();
|
||||
if bg.eq_ignore_ascii_case("matte") {
|
||||
return [0, 255, 255, 255];
|
||||
}
|
||||
let hex = bg.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()));
|
||||
match hex.and_then(|h| u32::from_str_radix(h, 16).ok()) {
|
||||
Some(c) => {
|
||||
let [_, r, g, b] = c.to_be_bytes();
|
||||
[255, r, g, b]
|
||||
}
|
||||
None => [0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a
|
||||
/// line break as `<br>` (CR LF is one break). Empty for anything but type.
|
||||
fn html_text(n: &Node) -> String {
|
||||
let NodeKind::Text(t) = &n.kind else { return String::new() };
|
||||
t.plain_text()
|
||||
.replace("\r\n", "\n")
|
||||
.split(['\n', '\r', '\u{2029}'])
|
||||
.map(|l| l.replace('&', "&").replace('<', "<").replace('>', ">"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("<br>")
|
||||
}
|
||||
|
||||
/// `s` as a Unicode string: a count of UTF-16 units, then the units. An error past
|
||||
/// [`MAX_SLICE_TEXT`] units, or when the string would take `out` past [`room`].
|
||||
fn unicode(out: &mut Vec<u8>, s: &str) -> Result<(), String> {
|
||||
let units = s.encode_utf16().count();
|
||||
if units > MAX_SLICE_TEXT {
|
||||
return Err(format!("a slice's text has more than the {MAX_SLICE_TEXT} characters a PSD file holds"));
|
||||
}
|
||||
room(out.len(), units)?;
|
||||
out.extend((units as u32).to_be_bytes());
|
||||
out.extend(s.encode_utf16().flat_map(|u| u.to_be_bytes()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An error when `units` UTF-16 units and their count, added to a slices resource of `len` bytes,
|
||||
/// make it longer than the 4 GB a PSD resource holds.
|
||||
pub(crate) fn room(len: usize, units: usize) -> Result<(), String> {
|
||||
let end = units.checked_mul(2).and_then(|n| n.checked_add(4)).and_then(|n| n.checked_add(len));
|
||||
match end.map(u32::try_from) {
|
||||
Some(Ok(_)) => Ok(()),
|
||||
_ => Err("the slices are too large for PSD (at most 4 GB)".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the parts of a document as layer records, bottom first.
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
//! PSD export: the header, the layer records (names, bounds, opacity, blend modes, groups,
|
||||
//! hidden layers), the merged image, the colour models, and a reader's view of the file.
|
||||
//! hidden layers), the merged image, the colour models, the slices, and a reader's view of the
|
||||
//! file.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color};
|
||||
use vectorcraft_doc::{Document, LayerColor, Node};
|
||||
use vectorcraft_doc::{Document, LayerColor, Node, NodeId, Slice, SliceKind, SliceOptions};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
use super::jpeg::ColorModel;
|
||||
use super::psd::{MAX_SIDE, PsdOptions};
|
||||
use super::psd::{MAX_SIDE, MAX_SLICE_TEXT, MAX_SLICES, PsdOptions, room};
|
||||
use super::*;
|
||||
|
||||
/// A 100 × 60 pt document: a red square on Layer 1, and on "Top" a half-opaque blue multiply
|
||||
@@ -735,3 +736,145 @@ fn long_unicode_name_is_cut_on_a_character_boundary() {
|
||||
let file = export(&b.build(), &opts(PsdOptions::default()));
|
||||
assert_eq!(parse(&file).records.last().unwrap().name, "a".repeat(254));
|
||||
}
|
||||
|
||||
/// `doc()` with a user slice over (20, 5)–(50, 15) and the red square made an object slice.
|
||||
fn sliced() -> Document {
|
||||
let mut d = doc();
|
||||
let red = d.layers[0].children().unwrap()[0].id;
|
||||
let user = SliceOptions {
|
||||
name: "banner".into(),
|
||||
url: "https://example.com/".into(),
|
||||
target: "_blank".into(),
|
||||
message: "Go".into(),
|
||||
alt: "Banner".into(),
|
||||
background: "#123456".into(),
|
||||
..SliceOptions::default()
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
d.slices.push(Slice { id, rect: Rect::new(20.0, 5.0, 50.0, 15.0), options: user });
|
||||
let cell = SliceOptions { kind: SliceKind::NoImage, text: "<b>Hi</b>".into(), background: "matte".into(), ..SliceOptions::default() };
|
||||
d.node_mut(red).unwrap().extras_mut().slice = Some(Box::new(cell));
|
||||
d
|
||||
}
|
||||
|
||||
/// The slices resource of `file` as an independent reader reads it.
|
||||
fn slices_of(file: &[u8]) -> Option<craft_psd::slices::SlicesResource> {
|
||||
let psd = craft_psd::PsdFile::from_bytes(file).expect("a PSD a reader takes");
|
||||
psd.resource(1050).map(|r| craft_psd::slices::SlicesResource::from_bytes(&r.data).expect("a slices resource a reader takes"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_are_written_with_or_without_layers() {
|
||||
let d = sliced();
|
||||
for layers in [true, false] {
|
||||
let file = export(&d, &opts(PsdOptions { layers, ..PsdOptions::default() }));
|
||||
let res = slices_of(&file).expect("the slices resource");
|
||||
assert_eq!((res.version, res.bounds, res.group_name.as_str()), (6, [5, 10, 40, 50], "Untitled-1"));
|
||||
let s = &res.slices;
|
||||
assert_eq!(s.len(), 2, "{s:?}");
|
||||
// Laid out top to bottom: the user slice, then the object slice, both written as made by
|
||||
// the user.
|
||||
let user = &s[0];
|
||||
assert_eq!((user.id, user.origin, user.layer_id, user.kind, user.rect), (1, 2, None, 1, [20, 5, 50, 15]));
|
||||
assert_eq!(
|
||||
(user.name.as_str(), user.url.as_str(), user.target.as_str(), user.message.as_str(), user.alt.as_str()),
|
||||
("banner", "https://example.com/", "_blank", "Go", "Banner")
|
||||
);
|
||||
assert_eq!(user.color, [255, 0x12, 0x34, 0x56]);
|
||||
let cell = &s[1];
|
||||
assert_eq!((cell.id, cell.origin, cell.kind, cell.rect), (2, 2, 0, [10, 10, 40, 40]));
|
||||
assert_eq!((cell.name.as_str(), cell.cell_text.as_str(), cell.cell_text_is_html), ("", "<b>Hi</b>", true));
|
||||
assert_eq!((cell.color[0], cell.color[1..].iter().any(|c| *c != 0)), (0, true), "the matte");
|
||||
assert_eq!((cell.horizontal_align, cell.vertical_align), (0, 0));
|
||||
}
|
||||
// A document without slices has no slices resource.
|
||||
assert!(slices_of(&export(&doc(), &opts(PsdOptions::default()))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_are_cut_to_the_exported_region_in_its_pixels() {
|
||||
let doc = sliced();
|
||||
// The right part at 2 px a point: the user slice is cut at the region's left edge, and the red
|
||||
// square's slice ends at that edge.
|
||||
let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) };
|
||||
let file = Renderer::new().export_region(&doc, Rect::new(40.0, 0.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
let res = slices_of(&file).unwrap();
|
||||
assert_eq!(res.slices.iter().map(|s| s.rect).collect::<Vec<_>>(), [[0, 10, 20, 30]]);
|
||||
assert_eq!(res.bounds, [10, 0, 30, 20]);
|
||||
// A region no slice reaches has none.
|
||||
let file = Renderer::new().export_region(&doc, Rect::new(60.0, 30.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
assert!(slices_of(&file).is_none());
|
||||
// A slice thinner than a pixel keeps one pixel.
|
||||
let mut thin = doc.clone();
|
||||
thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0);
|
||||
let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap();
|
||||
assert_eq!(res.slices[0].rect, [20, 5, 21, 15]);
|
||||
// The overlap is found before the region is rounded to whole pixels: a slice inside a region
|
||||
// that ends at 10.4 keeps its last pixel, and one past a region that ends at 10.6 isn't written.
|
||||
let o = opts(PsdOptions::default());
|
||||
let mut edge = doc.clone();
|
||||
edge.slices[0].rect = Rect::new(10.1, 5.0, 10.3, 15.0);
|
||||
edge.node_mut(edge.layers[0].children().unwrap()[0].id).unwrap().extras_mut().slice = None;
|
||||
let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.4, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
assert_eq!(slices_of(&file).unwrap().slices.iter().map(|s| s.rect).collect::<Vec<_>>(), [[9, 5, 10, 15]]);
|
||||
edge.slices[0].rect = Rect::new(10.7, 5.0, 10.9, 15.0);
|
||||
let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.6, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
assert!(slices_of(&file).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_html_text_slice_writes_one_break_for_each_line_ending() {
|
||||
use vectorcraft_doc::{CharStyle, NodeKind, TextObject};
|
||||
use vectorcraft_geom::Point;
|
||||
let mut d = DocBuilder::new(100.0, 60.0).build();
|
||||
let t = TextObject::point(Point::new(10.0, 30.0), "A\r\nB\rC\nD\u{2029}E", CharStyle { size: 12.0, ..CharStyle::default() });
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.extras_mut().slice = Some(Box::new(SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() }));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let res = slices_of(&export(&d, &opts(PsdOptions::default()))).unwrap();
|
||||
assert_eq!(res.slices[0].cell_text, "A<br>B<br>C<br>D<br>E");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slice_ids_count_from_1_and_the_limits_are_errors() {
|
||||
let mut doc = doc();
|
||||
for i in 0..20 {
|
||||
let id = doc.alloc_id();
|
||||
let x = f64::from(i) * 5.0;
|
||||
doc.slices.push(Slice { id, rect: Rect::new(x, 0.0, x + 5.0, 5.0), options: SliceOptions::default() });
|
||||
}
|
||||
let res = slices_of(&export(&doc, &opts(PsdOptions::default()))).unwrap();
|
||||
let ids: Vec<u32> = res.slices.iter().map(|s| s.id).collect();
|
||||
assert_eq!(ids, (1..=20).collect::<Vec<_>>());
|
||||
let export_err = |d: &Document| {
|
||||
Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::Psd, &opts(PsdOptions::default())).err().unwrap_or_default()
|
||||
};
|
||||
let mut long = doc.clone();
|
||||
long.slices[0].options.alt = "a".repeat(MAX_SLICE_TEXT + 1);
|
||||
let e = export_err(&long);
|
||||
assert!(e.contains("characters"), "{e}");
|
||||
let mut many = doc.clone();
|
||||
many.slices = (0..=MAX_SLICES as u64)
|
||||
.map(|i| Slice { id: NodeId(1_000_000 + i), rect: Rect::new(0.0, 0.0, 5.0, 5.0), options: SliceOptions::default() })
|
||||
.collect();
|
||||
let e = export_err(&many);
|
||||
assert!(e.contains("slices"), "{e}");
|
||||
// Not clipped to the artboard, a slice keeps bounds that aren't finite.
|
||||
let mut bad = doc;
|
||||
bad.slices_clip_to_artboard = false;
|
||||
bad.slices[0].rect = Rect::new(f64::NAN, 0.0, 5.0, 5.0);
|
||||
let e = export_err(&bad);
|
||||
assert!(e.contains("finite"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_past_4_gb_are_an_error_before_they_are_written() {
|
||||
let max = u32::MAX as usize;
|
||||
assert_eq!(room(0, MAX_SLICE_TEXT), Ok(()));
|
||||
assert_eq!(room(max - 4 - 2 * 10, 10), Ok(()));
|
||||
let e = room(max - 4 - 2 * 10, 11).err().unwrap_or_default();
|
||||
assert!(e.contains("4 GB"), "{e}");
|
||||
assert!(room(max, 0).is_err());
|
||||
assert!(room(0, usize::MAX).is_err());
|
||||
}
|
||||
@@ -96,8 +96,9 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
return art.visual_bounds_with(symbols).map(|r| with_raster_reach(symbols, n, r));
|
||||
}
|
||||
// Copies that each carry the raster effects listed before their Transform effect reach as far
|
||||
// as each copy's raster effects paint, and the raster effects after it spread them all.
|
||||
if effects::outer_effects(n).len() < n.appearance.effects.len()
|
||||
// as each copy's raster effects paint, and the raster effects after it spread them all,
|
||||
// as do copies whose fills and strokes each carry their own raster effects.
|
||||
if (effects::outer_effects(n).len() < n.appearance.effects.len() || effects::has_copied_row_raster(n))
|
||||
&& let Some(art) = effects::reshape(Some(symbols.document()), n, None)
|
||||
{
|
||||
return cull_bounds(symbols, &art);
|
||||
|
||||
@@ -1243,6 +1243,45 @@ fn each_copy_of_a_transform_effect_draws_its_own_shadow() {
|
||||
assert!(b.x1 >= 80.0 - 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
/// Each copy of a fill's own Transform effect, and each copy of its object's Transform effect,
|
||||
/// draws the fill's drop shadow under itself, scaled with it: as for the object's own shadow
|
||||
/// above, the copy's green shadow is 40 pt to its right. A 4 pt stroke's own Transform effect
|
||||
/// gives each copy the shadow of its stroke: the copy's right edge (38..42 across) casts it at
|
||||
/// 78..82. The bounds reach as far as the copy's shadow.
|
||||
#[test]
|
||||
fn each_copy_of_a_fills_or_strokes_transform_draws_its_own_shadow() {
|
||||
let shadow = || fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}));
|
||||
let copies = || fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}));
|
||||
let square = |item: AppearanceItem| {
|
||||
Node::path(NodeId(0), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance { items: vec![item], ..Default::default() })
|
||||
};
|
||||
let mut red = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
red.effects = vec![shadow(), copies()];
|
||||
let own = square(AppearanceItem::Fill(red.clone()));
|
||||
red.effects = vec![shadow()];
|
||||
let mut owner = square(AppearanceItem::Fill(red));
|
||||
owner.appearance.effects = vec![copies()];
|
||||
for (what, n) in [("own", own), ("object's", owner)] {
|
||||
let d = doc_with(Document::new(100.0, 100.0), n);
|
||||
let img = render(&d);
|
||||
assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "{what}: the square");
|
||||
assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "{what}: the square's shadow");
|
||||
assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "{what}: the copy");
|
||||
assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "{what}: the copy's shadow, 40 pt to its right");
|
||||
assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "{what}: past the copy's shadow");
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap();
|
||||
assert!(b.x1 >= 80.0 - 1e-9, "{what}: {b:?}");
|
||||
}
|
||||
let mut blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
|
||||
blue.effects = vec![shadow(), copies()];
|
||||
let d = doc_with(Document::new(100.0, 100.0), square(AppearanceItem::Stroke(blue)));
|
||||
let img = render(&d);
|
||||
assert_eq!(img.pixel(50, 20), [0, 255, 0, 255], "the square's stroke shadow");
|
||||
assert_eq!(img.pixel(80, 80), [0, 255, 0, 255], "the copy's stroke shadow, 40 pt to the right of its edge");
|
||||
assert_eq!(img.pixel(60, 80), [255, 255, 255, 255], "inside the copy's stroke shadow");
|
||||
}
|
||||
|
||||
/// Each copy of an image's Transform effect draws the drop shadow listed before the effect under
|
||||
/// itself, scaled with it: the red image (20..50) has its green shadow 10 pt to its right, and its
|
||||
/// copy scaled 50 % and moved 40 pt down (27.5..42.5 across, 67.5..82.5 down) has its own 5 pt to
|
||||
|
||||
@@ -70,7 +70,7 @@ pub use stylistic_sets::StylisticSet;
|
||||
use traits::Alias;
|
||||
#[cfg(test)]
|
||||
use traits::{FaceKeys, face_names};
|
||||
pub use traits::{FontClass, FontMatch, FontTraits};
|
||||
pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits};
|
||||
#[cfg(test)]
|
||||
pub(crate) use traits::{alias_lists, face_styles, on_faces_published};
|
||||
pub use wanted::{WantedFont, WantedFonts};
|
||||
|
||||
@@ -8,7 +8,10 @@ pub(super) struct CatalogFamily {
|
||||
/// Non-English family name from the name table, when the scan found one.
|
||||
pub(super) native: Option<String>,
|
||||
pub(super) faces: Vec<CatalogFace>,
|
||||
/// The family's kind (from its first face found); variable when any face found is.
|
||||
/// The family's kind (from its first face found); variable when any face found is. Its
|
||||
/// likeness is the one of the face found nearest an upright Regular ([`regular_rank`]).
|
||||
///
|
||||
/// [`regular_rank`]: super::traits::regular_rank
|
||||
pub(super) traits: Option<FontTraits>,
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ use super::scan::{file_face_names, is_font_file};
|
||||
#[cfg(test)]
|
||||
use super::traits::faces_published;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::traits::{Alias, FaceStyle};
|
||||
use super::traits::{Alias, FaceStyle, regular_rank};
|
||||
use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{ScanStamp, modified};
|
||||
@@ -430,6 +430,9 @@ impl FontDb {
|
||||
let entry = catalog.entry(family.to_ascii_lowercase()).or_default();
|
||||
let kind = entry.traits.get_or_insert(traits);
|
||||
kind.variable |= traits.variable;
|
||||
if regular_rank(&traits.likeness) < regular_rank(&kind.likeness) {
|
||||
kind.likeness = traits.likeness;
|
||||
}
|
||||
if entry.name.is_empty() {
|
||||
entry.name = family;
|
||||
}
|
||||
|
||||
@@ -356,6 +356,11 @@ impl FontFace {
|
||||
pub fn x_height(&self) -> f64 {
|
||||
self.x_height
|
||||
}
|
||||
/// The height of the capital letters in font units, positive (estimated from the ascent when
|
||||
/// the font has no OS/2 value).
|
||||
pub fn cap_height(&self) -> f64 {
|
||||
self.cap_height
|
||||
}
|
||||
/// The line gap the font asks for between lines, in font units (from the same table as
|
||||
/// [`vertical_metrics`](Self::vertical_metrics); 0 when it has none).
|
||||
pub fn line_gap(&self) -> f64 {
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::names::SYSTEM_FALLBACKS;
|
||||
use super::names::{norm, norm_chars, script_families};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::scan::{enumerate_faces, font_files};
|
||||
use super::traits::{Alias, FontMatch, FontTraits};
|
||||
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
|
||||
use super::{
|
||||
Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX,
|
||||
Ordering, Size,
|
||||
@@ -18,6 +18,45 @@ use super::{
|
||||
/// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads.
|
||||
const MAX_POSTSCRIPT_FACES: usize = 16;
|
||||
|
||||
/// Keeps `other`'s variable flag in `traits`, and its likeness when it is nearer an upright
|
||||
/// Regular.
|
||||
fn merge_traits(traits: &mut FontTraits, other: &FontTraits) {
|
||||
traits.variable |= other.variable;
|
||||
if regular_rank(&other.likeness) < regular_rank(&traits.likeness) {
|
||||
traits.likeness = other.likeness;
|
||||
}
|
||||
}
|
||||
|
||||
/// The traits of the loaded faces of each family, or of `only` that family, keyed by the family's
|
||||
/// name in ASCII lowercase: the first face's, with the other faces merged in ([`merge_traits`]).
|
||||
fn loaded_traits(faces: &[Arc<FontFace>], only: Option<&str>) -> std::collections::HashMap<String, FontTraits> {
|
||||
let mut found = std::collections::HashMap::<String, FontTraits>::new();
|
||||
for f in faces.iter().filter(|f| only.is_none_or(|o| f.family.eq_ignore_ascii_case(o))) {
|
||||
match found.entry(f.family.to_ascii_lowercase()) {
|
||||
std::collections::hash_map::Entry::Vacant(e) => {
|
||||
e.insert(f.traits);
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(mut e) => merge_traits(e.get_mut(), &f.traits),
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// A family's traits from its `loaded` faces with what the scan in `catalog` found for `key` (its
|
||||
/// name in ASCII lowercase) merged in, or the scan's alone when none is loaded.
|
||||
fn scanned_traits(loaded: Option<FontTraits>, catalog: &Catalog, key: &str) -> FontTraits {
|
||||
let scanned = catalog.get(key).and_then(|c| c.traits);
|
||||
match loaded {
|
||||
None => scanned.unwrap_or_default(),
|
||||
Some(mut traits) => {
|
||||
if let Some(found) = scanned {
|
||||
merge_traits(&mut traits, &found);
|
||||
}
|
||||
traits
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FontDb {
|
||||
/// The family's own name and the style for a name given in a document: any of a family's
|
||||
/// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its
|
||||
@@ -86,26 +125,73 @@ impl FontDb {
|
||||
/// loaded face, else from the system font scan. Variable when any of its faces, loaded or
|
||||
/// scanned, is: a family may install static files beside a variable one. Cheap: no font file
|
||||
/// is read, and a loaded family doesn't start the scan. A composite font takes its base font's.
|
||||
/// Its likeness is the one of its face nearest an upright Regular, loaded or scanned.
|
||||
pub fn family_traits(&self, family: &str) -> FontTraits {
|
||||
if let Some((base, _)) = self.composite_base(family) {
|
||||
return self.family_traits(&base);
|
||||
}
|
||||
let loaded = {
|
||||
let faces = self.read_faces();
|
||||
let mut of_family = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family));
|
||||
of_family.next().map(|first| FontTraits { variable: first.traits.variable || of_family.any(|f| f.traits.variable), ..first.traits })
|
||||
};
|
||||
let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits);
|
||||
let key = family.to_ascii_lowercase();
|
||||
let loaded = loaded_traits(&self.read_faces(), Some(family)).remove(&key);
|
||||
match loaded {
|
||||
None => scanned(&self.read_catalog()).unwrap_or_default(),
|
||||
Some(traits) if traits.variable => traits,
|
||||
Some(traits) => {
|
||||
let variable = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)).is_some_and(|t| t.variable);
|
||||
FontTraits { variable, ..traits }
|
||||
}
|
||||
None => scanned_traits(None, &self.read_catalog(), &key),
|
||||
// What the scan found so far, without starting it.
|
||||
Some(_) => scanned_traits(loaded, &self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner), &key),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name [`family_traits`](Self::family_traits) takes `family`'s traits by, in ASCII
|
||||
/// lowercase: a composite font's base font's.
|
||||
fn traits_key(&self, family: &str) -> String {
|
||||
match self.composite_base(family) {
|
||||
Some((base, _)) => self.traits_key(&base),
|
||||
None => family.to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `families` ordered by how alike they look to `family` (Show Similar Fonts): `family` itself
|
||||
/// first when listed, then the families that set the same script as it (Japanese, Thai or
|
||||
/// neither, as [`FontTraits`] tells), then the others, each group nearest first by
|
||||
/// [`FontLikeness::distance`](super::FontLikeness::distance) of their
|
||||
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
|
||||
/// counting 2 further. Families equally far keep their order in `families`. Reads no font
|
||||
/// file, as `family_traits` does not.
|
||||
pub fn similar_families(&self, family: &str, families: &[String]) -> Vec<String> {
|
||||
let base = self.family_traits(family);
|
||||
let script = |t: &FontTraits| {
|
||||
if t.japanese {
|
||||
0
|
||||
} else if t.thai {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
};
|
||||
// Every family's traits from one pass over the loaded faces and one look at the scan, as
|
||||
// `family_traits` finds them; composite fonts are resolved before any lock is held.
|
||||
let keys: Vec<String> = families.iter().map(|f| self.traits_key(f)).collect();
|
||||
let loaded = loaded_traits(&self.read_faces(), None);
|
||||
let catalog = if keys.iter().all(|k| loaded.contains_key(k)) {
|
||||
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
} else {
|
||||
self.read_catalog()
|
||||
};
|
||||
let mut keyed: Vec<(bool, f32, &String)> = families
|
||||
.iter()
|
||||
.zip(&keys)
|
||||
.map(|(f, key)| {
|
||||
let traits = scanned_traits(loaded.get(key).copied(), &catalog, key);
|
||||
let d = if f.eq_ignore_ascii_case(family) {
|
||||
-1.0
|
||||
} else {
|
||||
base.likeness.distance(&traits.likeness) + if traits.class == base.class { 0.0 } else { 2.0 }
|
||||
};
|
||||
(script(&traits) != script(&base), d, f)
|
||||
})
|
||||
.collect();
|
||||
keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
|
||||
keyed.into_iter().map(|(_, _, f)| f.clone()).collect()
|
||||
}
|
||||
|
||||
/// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how
|
||||
/// it matched. A composite font matches as its base font does ([`Self::composite_base`]).
|
||||
pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc<FontFace>, FontMatch)> {
|
||||
|
||||
@@ -160,6 +160,8 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
|
||||
use std::io::SeekFrom;
|
||||
/// The largest table read from a (possibly damaged) file.
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
/// The `post` table's header: version, italic angle, underline and fixed-pitch fields.
|
||||
const POST_HEADER: u32 = 32;
|
||||
let mut read = 0u64;
|
||||
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
|
||||
read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?;
|
||||
@@ -186,26 +188,34 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
|
||||
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
|
||||
return None;
|
||||
}
|
||||
let mut table = |tag: &[u8; 4]| -> Option<Vec<u8>> {
|
||||
// A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing.
|
||||
let mut table_within = |tag: &[u8; 4], most: u32| -> Option<Vec<u8>> {
|
||||
let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?;
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most));
|
||||
if len > MAX_NAME_TABLE {
|
||||
return None;
|
||||
}
|
||||
read_at(offset.into(), len as usize)
|
||||
};
|
||||
let name = table(b"name")?;
|
||||
let name = table_within(b"name", u32::MAX)?;
|
||||
// A variable font's named instances are styles too.
|
||||
let fvar = table(b"fvar");
|
||||
let fvar = table_within(b"fvar", u32::MAX);
|
||||
// Its OS/2 table (the font's classification, for the menus' filters), when it has one.
|
||||
let os2 = table(b"OS/2");
|
||||
let os2 = table_within(b"OS/2", u32::MAX);
|
||||
// Its units per em and italic angle, for Show Similar Fonts ([`super::FontLikeness`]):
|
||||
// the `head` table and the `post` table's 32-byte header, as a version 3 table (one
|
||||
// without glyph names).
|
||||
let head = table_within(b"head", u32::MAX);
|
||||
let post = table_within(b"post", POST_HEADER).filter(|p| p.len() == POST_HEADER as usize).map(|mut p| {
|
||||
p[..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes());
|
||||
p
|
||||
});
|
||||
// A font holding just these tables, to read them as the font itself would.
|
||||
let mut tables: Vec<(&[u8; 4], &[u8])> = vec![(b"name", &name)];
|
||||
if let Some(fvar) = &fvar {
|
||||
tables.push((b"fvar", fvar));
|
||||
}
|
||||
if let Some(os2) = &os2 {
|
||||
tables.push((b"OS/2", os2));
|
||||
for (tag, data) in [(b"fvar", &fvar), (b"OS/2", &os2), (b"head", &head), (b"post", &post)] {
|
||||
if let Some(data) = data {
|
||||
tables.push((tag, data.as_slice()));
|
||||
}
|
||||
}
|
||||
let font = sfnt_of(&tables)?;
|
||||
Some(face_styles(&skrifa::FontRef::new(&font).ok()?))
|
||||
|
||||
@@ -101,6 +101,111 @@ pub struct FontTraits {
|
||||
/// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of
|
||||
/// its faces has.
|
||||
pub variable: bool,
|
||||
/// What Show Similar Fonts compares; for a family, its face nearest an upright Regular.
|
||||
pub likeness: FontLikeness,
|
||||
}
|
||||
|
||||
/// The numbers a font menu's Show Similar Fonts compares faces by ([`FontLikeness::distance`]),
|
||||
/// read from the face's OS/2, `head` and `post` tables only, so that the system font scan reads
|
||||
/// the same numbers without loading the font ([`super::scan::file_face_names`]). Each is 0 (the
|
||||
/// italic angle `None`) when the face does not say (no such table, or an OS/2 table too old to
|
||||
/// hold the value).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct FontLikeness {
|
||||
/// The OS/2 PANOSE digits (0 is "any" and 1 "no fit" in each digit).
|
||||
pub panose: [u8; 10],
|
||||
/// The OS/2 weight class, at most 1000; a named instance's `wght` setting.
|
||||
pub weight: u16,
|
||||
/// The OS/2 width class, 1 to 9.
|
||||
pub width: u8,
|
||||
/// The OS/2 x-height and cap height in thousandths of the em.
|
||||
pub x_height: u16,
|
||||
pub cap_height: u16,
|
||||
/// The OS/2 average character width in thousandths of the em.
|
||||
pub avg_width: u16,
|
||||
/// The `post` table's italic angle in tenths of a degree (negative: leaning right); a named
|
||||
/// instance's `slnt` setting.
|
||||
pub italic_angle: Option<i16>,
|
||||
/// The face is italic or oblique: by its OS/2 selection flags or a nonzero italic angle; a
|
||||
/// named instance by its `ital` or `slnt` setting or its name. Not compared; it picks a
|
||||
/// family's face nearest an upright Regular.
|
||||
pub italic: bool,
|
||||
}
|
||||
|
||||
impl FontLikeness {
|
||||
/// From a face's tables, with a named instance's `variations` (its axis settings in user
|
||||
/// units; empty for the face itself): its `weight` (`wght` setting) in place of the OS/2
|
||||
/// weight class, its `slnt` setting in place of the italic angle, and whether it is
|
||||
/// `italic`. The heights and the average width need the `head` table's units per em (16 to
|
||||
/// 16384).
|
||||
fn of(font: &skrifa::FontRef<'_>, variations: &[Variation], weight: Option<f32>, italic: Option<bool>) -> Self {
|
||||
use skrifa::raw::TableProvider;
|
||||
let em = font.head().ok().map(|h| h.units_per_em()).filter(|u| (16..=16384).contains(u)).map(f32::from);
|
||||
// Thousandths of the em, 0 for nothing (and for a value at or below 0).
|
||||
let per_mille = |v: i16| match em {
|
||||
Some(em) if v > 0 => (f32::from(v) / em * 1000.0).round().min(4000.0) as u16,
|
||||
_ => 0,
|
||||
};
|
||||
let mut likeness = Self::default();
|
||||
if let Ok(o) = font.os2() {
|
||||
for (digit, value) in likeness.panose.iter_mut().zip(o.panose_10()) {
|
||||
*digit = *value;
|
||||
}
|
||||
likeness.weight = o.us_weight_class().min(1000);
|
||||
likeness.width = u8::try_from(o.us_width_class()).ok().filter(|w| (1..=9).contains(w)).unwrap_or(0);
|
||||
likeness.x_height = o.sx_height().map_or(0, per_mille);
|
||||
likeness.cap_height = o.s_cap_height().map_or(0, per_mille);
|
||||
likeness.avg_width = per_mille(o.x_avg_char_width());
|
||||
// fsSelection's ITALIC (bit 0) and OBLIQUE (bit 9) flags.
|
||||
likeness.italic = o.fs_selection().bits() & 0x0201 != 0;
|
||||
}
|
||||
if let Some(w) = weight.filter(|w| w.is_finite()) {
|
||||
likeness.weight = w.round().clamp(1.0, 1000.0) as u16;
|
||||
}
|
||||
let angle = |a: f32| (a.is_finite() && a.abs() <= 90.0).then(|| (a * 10.0).round() as i16);
|
||||
likeness.italic_angle = match variations.iter().find(|(tag, _)| tag == b"slnt") {
|
||||
Some((_, slant)) => angle(*slant),
|
||||
None => font.post().ok().and_then(|p| angle(p.italic_angle().to_f32())),
|
||||
};
|
||||
likeness.italic = italic.unwrap_or(likeness.italic || likeness.italic_angle.is_some_and(|a| a != 0));
|
||||
likeness
|
||||
}
|
||||
|
||||
/// How unlike two faces look: 0 for faces whose numbers are all the same, more the further
|
||||
/// apart they are. A number one of the faces does not give is left out. PANOSE digits are
|
||||
/// compared only between faces of the same PANOSE family kind; faces of different kinds count
|
||||
/// 3 apart. The weights and scales are VectorCraft's own.
|
||||
pub fn distance(&self, other: &Self) -> f32 {
|
||||
let mut d = 0.0;
|
||||
let (kind, other_kind) = (self.panose[0], other.panose[0]);
|
||||
if kind > 1 && other_kind > 1 {
|
||||
if kind == other_kind {
|
||||
for (a, b) in self.panose.iter().zip(&other.panose).skip(1) {
|
||||
if *a > 1 && *b > 1 {
|
||||
d += f32::from(a.abs_diff(*b)) * 0.15;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
d += 3.0;
|
||||
}
|
||||
}
|
||||
if self.weight != 0 && other.weight != 0 {
|
||||
d += f32::from(self.weight.abs_diff(other.weight)) / 200.0;
|
||||
}
|
||||
if self.width != 0 && other.width != 0 {
|
||||
d += f32::from(self.width.abs_diff(other.width)) * 0.5;
|
||||
}
|
||||
for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)]
|
||||
{
|
||||
if a != 0 && b != 0 {
|
||||
d += f32::from(a.abs_diff(b)) / 1000.0 * scale;
|
||||
}
|
||||
}
|
||||
if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) {
|
||||
d += f32::from(a.abs_diff(b)) / 50.0;
|
||||
}
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
impl FontTraits {
|
||||
@@ -216,10 +321,20 @@ impl FontTraits {
|
||||
FontClass::Other
|
||||
};
|
||||
let variable = (1..=MAX_AXES).contains(&font.axes().len());
|
||||
FontTraits { japanese, thai, class, variable }
|
||||
FontTraits { japanese, thai, class, variable, likeness: FontLikeness::of(font, &[], None, None) }
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a face is from an upright Regular by its `likeness`: an italic or oblique face
|
||||
/// ([`FontLikeness::italic`]) after every upright one, then by how far its weight is from 400 (a
|
||||
/// face that gives no weight last), then by the numbers themselves, so that the same faces give
|
||||
/// the same answer whichever is found or loaded first. The lower, the nearer. A family's likeness
|
||||
/// ([`FontTraits::likeness`]) is its lowest-ranked face's, whether the faces are scanned or loaded.
|
||||
pub(super) fn regular_rank(likeness: &FontLikeness) -> (bool, u16, FontLikeness) {
|
||||
let off = if likeness.weight == 0 { u16::MAX } else { likeness.weight.abs_diff(400) };
|
||||
(likeness.italic, off, *likeness)
|
||||
}
|
||||
|
||||
/// What a name other than a family's own one stands for ([`FontDb::canonical`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Alias {
|
||||
@@ -342,11 +457,7 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec<FaceStyle> {
|
||||
let Some((family, style)) = face_names(f) else { return vec![] };
|
||||
let native_family = native_family_name(f, &family);
|
||||
let mut keys = FaceKeys::of(f, &family, &style);
|
||||
let traits = FontTraits::of(f, &keys);
|
||||
let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone());
|
||||
for i in &mut instances {
|
||||
i.traits = traits;
|
||||
}
|
||||
let mut traits = FontTraits::of(f, &keys);
|
||||
// A variable font's default face renders at its `wght` default, whatever its name table and
|
||||
// OS/2 table say (Noto Sans Hebrew: named `Light`, weight class 300, default instance Regular
|
||||
// at 400): weigh it so, and name it by its default instance when that is another weight.
|
||||
@@ -357,6 +468,19 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec<FaceStyle> {
|
||||
.map(|a| a.default_value())
|
||||
.filter(|w| w.is_finite())
|
||||
.map(|w| w.clamp(1.0, 1000.0));
|
||||
// Its likeness is likewise taken at its axes' defaults (`wght` and `slnt`).
|
||||
if f.axes().len() <= MAX_AXES {
|
||||
let defaults: Vec<Variation> = f.axes().iter().map(|a| (a.tag().to_be_bytes(), a.default_value())).collect();
|
||||
traits.likeness = FontLikeness::of(f, &defaults, weight, None);
|
||||
}
|
||||
let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone());
|
||||
// Each named instance shares the face's kind; its likeness is measured at its own axis settings.
|
||||
// Without an `ital` or `slnt` axis, an instance of an italic face is italic too.
|
||||
for i in &mut instances {
|
||||
let slant_axis = i.variations.iter().any(|(tag, _)| tag == b"ital" || tag == b"slnt");
|
||||
let italic = i.italic || (!slant_axis && traits.likeness.italic);
|
||||
i.traits = FontTraits { likeness: FontLikeness::of(f, &i.variations, i.weight, Some(italic)), ..traits };
|
||||
}
|
||||
let style = renamed.unwrap_or(style);
|
||||
let face = FaceStyle { family, native_family, style, keys, variations: vec![], weight, italic: false, traits };
|
||||
std::iter::once(face).chain(instances).collect()
|
||||
|
||||
@@ -41,10 +41,10 @@ pub use features::{
|
||||
EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by,
|
||||
};
|
||||
pub use fontdb::{
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, GlyphCategoryKind,
|
||||
GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont,
|
||||
WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined,
|
||||
style_weight, system_font_dirs, user_font_dirs,
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory,
|
||||
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind,
|
||||
WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs,
|
||||
set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
|
||||
};
|
||||
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
|
||||
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
|
||||
|
||||
@@ -28,6 +28,7 @@ mod path_joins;
|
||||
mod ruby;
|
||||
mod scripts;
|
||||
mod shape_plans;
|
||||
mod similar;
|
||||
mod snap;
|
||||
mod svg_glyphs;
|
||||
mod sysfonts;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Show Similar Fonts: the numbers a face is compared by ([`FontLikeness`]), a family's likeness
|
||||
//! from its face nearest an upright Regular, and families ordered by likeness.
|
||||
|
||||
use skrifa::raw::TableProvider;
|
||||
|
||||
use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font};
|
||||
use crate::*;
|
||||
|
||||
/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without
|
||||
/// heights in their OS/2 tables.
|
||||
fn db() -> FontDb {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
for heights in [true, false] {
|
||||
assert_eq!(db.add_font(height_font(heights).expect("the test font builds")), 1);
|
||||
}
|
||||
db
|
||||
}
|
||||
|
||||
fn names(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_face_is_compared_by_its_tables() {
|
||||
let db = db();
|
||||
let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness;
|
||||
assert_eq!(regular.weight, 400);
|
||||
assert_eq!(regular.italic_angle, Some(0));
|
||||
assert!(regular.panose[0] > 1, "a PANOSE family kind: {regular:?}");
|
||||
assert!(regular.x_height > 300 && regular.cap_height > regular.x_height, "{regular:?}");
|
||||
// The OS/2 average character width, in thousandths of the em.
|
||||
let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSans3-Regular.ttf")).expect("bundled");
|
||||
let font = skrifa::FontRef::new(&bytes).expect("it parses");
|
||||
let (avg, em) = (font.os2().expect("an OS/2 table").x_avg_char_width(), font.head().expect("a head table").units_per_em());
|
||||
assert_eq!(f32::from(regular.avg_width), (f32::from(avg) / f32::from(em) * 1000.0).round());
|
||||
let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness;
|
||||
assert!(italic.italic_angle.is_some_and(|a| a < 0), "leans right: {italic:?}");
|
||||
assert!(italic.italic && !regular.italic);
|
||||
let bold = db.face("Source Sans 3", "Bold").expect("bundled").traits.likeness;
|
||||
assert_eq!(bold.weight, 700);
|
||||
// The OS/2 heights, in thousandths of its 1,000-unit em.
|
||||
let heights = db.family_traits(HEIGHT_FAMILY).likeness;
|
||||
assert_eq!((heights.x_height, heights.cap_height), (HEIGHT_X as u16, HEIGHT_CAP as u16));
|
||||
// Without them (a version 1 OS/2 table), the heights are left out.
|
||||
let heightless = db.family_traits(HEIGHTLESS_FAMILY).likeness;
|
||||
assert_eq!((heightless.x_height, heightless.cap_height), (0, 0), "{heightless:?}");
|
||||
assert_eq!(heightless.avg_width, regular.avg_width);
|
||||
}
|
||||
|
||||
/// A variable font's named instance takes its `wght` setting as its weight; the default face its
|
||||
/// default weight.
|
||||
#[test]
|
||||
fn a_named_instance_is_weighed_by_its_axis_setting() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(variable_font().expect("the test font builds")), 3);
|
||||
let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the default face").traits.likeness;
|
||||
let semibold = db.face(VARIABLE_FAMILY, "SemiBold").expect("a named instance").traits.likeness;
|
||||
let bold = db.face(VARIABLE_FAMILY, "Bold").expect("a named instance").traits.likeness;
|
||||
assert_eq!((regular.weight, semibold.weight, bold.weight), (400, 550, 700));
|
||||
// The family is compared by its Regular face.
|
||||
assert_eq!(db.family_traits(VARIABLE_FAMILY).likeness, regular);
|
||||
}
|
||||
|
||||
/// A face without an italic angle is compared by the other numbers only.
|
||||
#[test]
|
||||
fn a_missing_italic_angle_is_left_out() {
|
||||
let db = db();
|
||||
let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness;
|
||||
assert_eq!(italic.distance(&FontLikeness { italic_angle: None, ..italic }), 0.0);
|
||||
assert!(italic.distance(&FontLikeness { italic_angle: Some(0), ..italic }) > 0.0);
|
||||
}
|
||||
|
||||
/// A family is compared by its face nearest an upright Regular, not by the first one loaded.
|
||||
#[test]
|
||||
fn a_family_is_compared_by_its_regular_face() {
|
||||
let db = db();
|
||||
let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness;
|
||||
assert_eq!(db.family_traits("Source Sans 3").likeness, regular);
|
||||
assert_eq!(db.family_traits("source sans 3").likeness, regular, "by any case");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn likeness_is_a_distance() {
|
||||
let db = db();
|
||||
let (sans, serif, mono) =
|
||||
(db.family_traits("Source Sans 3").likeness, db.family_traits("Source Serif 4").likeness, db.family_traits("JetBrains Mono").likeness);
|
||||
assert_eq!(sans.distance(&sans), 0.0);
|
||||
assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric");
|
||||
assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0);
|
||||
// A number a face does not give is left out, not counted as 0.
|
||||
let unknown = FontLikeness::default();
|
||||
assert_eq!(sans.distance(&unknown), 0.0);
|
||||
let lighter = FontLikeness { weight: 300, ..sans };
|
||||
assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart");
|
||||
}
|
||||
|
||||
/// The family itself first, then nearest first: a copy of Source Sans 3 Regular comes before every
|
||||
/// other family, and the order never moves away from the family and back.
|
||||
#[test]
|
||||
fn families_are_ordered_by_likeness() {
|
||||
let db = db();
|
||||
let families = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]);
|
||||
let order = db.similar_families("Source Sans 3", &families);
|
||||
assert_eq!(order.len(), families.len());
|
||||
assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}");
|
||||
let base = db.family_traits("Source Sans 3");
|
||||
let far = |f: &str| {
|
||||
let t = db.family_traits(f);
|
||||
base.likeness.distance(&t.likeness) + if t.class == base.class { 0.0 } else { 2.0 }
|
||||
};
|
||||
for pair in order[1..].windows(2) {
|
||||
assert!(far(&pair[0]) <= far(&pair[1]), "{order:?}");
|
||||
}
|
||||
// Asked by another case, or for a family not in the list.
|
||||
assert_eq!(db.similar_families("SOURCE SANS 3", &families)[0], "Source Sans 3");
|
||||
let without = db.similar_families("Source Sans 3", &families[..4]);
|
||||
assert_eq!(without[0], HEIGHTLESS_FAMILY);
|
||||
assert!(db.similar_families("Source Sans 3", &[]).is_empty());
|
||||
}
|
||||
@@ -428,6 +428,29 @@ fn a_family_with_a_variable_file_beside_static_ones_is_variable() {
|
||||
assert!(db.family_traits(FAMILY).variable);
|
||||
}
|
||||
|
||||
/// Show Similar Fonts: the scan reads the numbers a face is compared by as loading the face does,
|
||||
/// and a family's are its Regular face's whichever file is found first.
|
||||
#[test]
|
||||
fn the_scan_reads_a_familys_likeness_without_loading_it() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-likeness", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Sysfont-Italic.ttf"), renamed("SourceSans3-It.ttf")).unwrap();
|
||||
std::fs::write(dir.join("Sysfont-Regular.ttf"), renamed("SourceSans3-Regular.ttf")).unwrap();
|
||||
let scanned = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let likeness = scanned.family_traits(FAMILY).likeness;
|
||||
assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded");
|
||||
let loaded = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(loaded.add_font(renamed("SourceSans3-Regular.ttf")), 1);
|
||||
assert_eq!(likeness, loaded.face(FAMILY, "Regular").unwrap().traits.likeness);
|
||||
assert!(likeness.avg_width > 0 && likeness.x_height > 0 && likeness.italic_angle == Some(0), "{likeness:?}");
|
||||
// With only the italic loaded, the scanned Regular face still gives the family's numbers.
|
||||
assert_eq!(scanned.add_font(renamed("SourceSans3-It.ttf")), 1);
|
||||
assert!(scanned.is_loaded(FAMILY));
|
||||
assert_eq!(scanned.family_traits(FAMILY).likeness, likeness);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_fonts_outside_the_font_folders_are_their_full_paths() {
|
||||
let dir = std::env::temp_dir().join("Fonts");
|
||||
@@ -697,8 +720,8 @@ fn a_search_reads_at_most_its_share_of_a_font_file() {
|
||||
let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap();
|
||||
u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap()))
|
||||
};
|
||||
// What one face costs: its table directory and its name and OS/2 tables.
|
||||
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2");
|
||||
// What one face costs: its table directory, its name, OS/2 and head tables and the post table's header.
|
||||
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2") + len(b"head") + 32;
|
||||
let n = 300;
|
||||
let base = 12 + 4 * n;
|
||||
let mut ttc = b"ttcf".to_vec();
|
||||
|
||||
+263
-5
@@ -1,7 +1,7 @@
|
||||
//! Portable 3D effect geometry: Revolve, Extrude & Bevel, Inflate and Rotate. No windowing, GPU or
|
||||
//! document dependencies.
|
||||
//!
|
||||
//! Open profiles optionally close their circular ends with caps. Faces are projected and sorted back to front,
|
||||
//! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front,
|
||||
//! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer:
|
||||
//! intersecting profiles can have ambiguous visibility and are not solid modelling inputs.
|
||||
#![forbid(unsafe_code)]
|
||||
@@ -102,9 +102,14 @@ pub struct Revolve {
|
||||
pub shade: bool,
|
||||
/// Interpolate profile normals using vector gradients. Enabled by default.
|
||||
pub smooth_shading: bool,
|
||||
/// Close circular endpoint rings of open profiles. Partial sweeps get sectors;
|
||||
/// the angular cut sides are left open. Enabled by default.
|
||||
/// Close circular endpoint rings of open profiles (sectors on a partial sweep), and the two
|
||||
/// angular cut sides of a partial sweep: each is one flat face of the region between an open
|
||||
/// profile and the axis, and of a closed profile's own area with its holes left open. Off, the
|
||||
/// surface is hollow. Enabled by default.
|
||||
pub cap_ends: bool,
|
||||
/// The profile's fill rule, which decides the holes the cut sides leave open in [`revolve`] and
|
||||
/// [`revolve_shadowed`]. Nonzero by default.
|
||||
pub fill_rule: FillRule,
|
||||
/// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of
|
||||
/// one object. `None` plans them from the profile alone.
|
||||
pub curve_samples: Option<usize>,
|
||||
@@ -140,6 +145,7 @@ impl Default for Revolve {
|
||||
shade: true,
|
||||
smooth_shading: true,
|
||||
cap_ends: true,
|
||||
fill_rule: FillRule::NonZero,
|
||||
curve_samples: None,
|
||||
map_surface: false,
|
||||
}
|
||||
@@ -729,7 +735,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi
|
||||
/// Evaluate a profile in document space. All subpaths share one axis from `bounds`.
|
||||
/// Invalid or excessively complex inputs return an error, never a partial surface.
|
||||
pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result<Vec<Face>, String> {
|
||||
revolve_faces(path, FillRule::NonZero, bounds, options, None)
|
||||
revolve_faces(path, options.fill_rule, bounds, options, None)
|
||||
}
|
||||
|
||||
/// [`revolve`]'s faces as facets, back to front, for the classic surfaces: each keeps its
|
||||
@@ -772,7 +778,10 @@ pub fn revolve_curve_samples<'a>(paths: impl IntoIterator<Item = &'a PathData>,
|
||||
if lines.saturating_add(curves.saturating_mul(MIN_CURVE_SAMPLES)) > points {
|
||||
return Err(TOO_COMPLEX_PROFILE.into());
|
||||
}
|
||||
let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)) / per_edge).min(points);
|
||||
// A partial sweep with caps closes each of its two cut sides with a face for each outline,
|
||||
// planned here as one for each contour.
|
||||
let cut_sides = if o.cap_ends && o.angle > 0.0 && o.angle < 360.0 { contours.saturating_mul(2) } else { 0 };
|
||||
let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)).saturating_sub(cut_sides) / per_edge).min(points);
|
||||
if curves == 0 {
|
||||
return if lines > edges { Err(TOO_COMPLEX_SURFACE.into()) } else { Ok(CURVE_SAMPLES) };
|
||||
}
|
||||
@@ -1055,6 +1064,249 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Twice the signed area of the polygon `ring`.
|
||||
fn ring_area(ring: &[Point]) -> f64 {
|
||||
ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum()
|
||||
}
|
||||
|
||||
/// The region a cut side of a partial sweep closes for one contour's profile `points`, in the
|
||||
/// profile's plane and in the order the profile runs: a closed contour's own area, or an open one
|
||||
/// closed along the axis at `axis` from its last end back to its first. An open contour whose ends
|
||||
/// meet is taken as closed. The region is given as the loops the nonzero rule fills, so one that
|
||||
/// crosses itself, such as a bow tie, gives a loop for each part it encloses. None when the contour
|
||||
/// encloses no area.
|
||||
fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec<Vec<Point>> {
|
||||
let ring = cut_ring(points, closed, axis);
|
||||
if ring.len() < 3 {
|
||||
return vec![];
|
||||
}
|
||||
let crossed = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ring, true)]);
|
||||
// A loop thinner than 0.000001 pt is left out, as the solids' rings leave out such debris.
|
||||
match vectorcraft_pathops::try_unite_all_with(&[(&crossed, FillRule::NonZero)], 1e-6) {
|
||||
Ok(loops) => loops
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|s| s.anchors.iter().map(|a| a.p).collect::<Vec<_>>())
|
||||
.filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10)
|
||||
.collect(),
|
||||
// Past the boolean's limits the region is kept as the profile draws it, as the solids'
|
||||
// rings keep theirs.
|
||||
Err(_) if ring_area(&ring).abs() > 1e-10 => vec![ring],
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// The ring around the region of one contour's profile `points` ([`cut_region`]), without repeated
|
||||
/// points or a last point that repeats the first.
|
||||
fn cut_ring(points: &[Point], closed: bool, axis: f64) -> Vec<Point> {
|
||||
let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return vec![] };
|
||||
let mut ring = points.to_vec();
|
||||
if !closed && first.distance(last) > 1e-10 {
|
||||
ring.extend([Point::new(axis, last.y), Point::new(axis, first.y)]);
|
||||
}
|
||||
ring.dedup_by(|a, b| a.distance(*b) <= 1e-10);
|
||||
while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-10) {
|
||||
ring.pop();
|
||||
}
|
||||
ring
|
||||
}
|
||||
|
||||
/// The steps at whose ends the two cut sides of a partial sweep lie, each with its outward normal
|
||||
/// before the view's rotation: the start faces back against the sweep, the end on along it.
|
||||
fn cut_sides(at: &Sweeping) -> [(usize, V3); 2] {
|
||||
// The profile lies on one side of the axis: the sweep turns it forward on the left and back on
|
||||
// the right.
|
||||
let side = if at.o.edge == Edge::Left { 1.0 } else { -1.0 };
|
||||
let (s, c) = at.sweep.sin_cos();
|
||||
[(0, V3(0.0, 0.0, -side)), (at.steps, V3(-s * side, 0.0, c * side))]
|
||||
}
|
||||
|
||||
/// Whether `p` lies inside the polygon `ring`.
|
||||
fn ring_contains(ring: &[Point], p: Point) -> bool {
|
||||
let mut inside = false;
|
||||
for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()) {
|
||||
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
/// The regions `regions` (turned as [`oriented`] gives them) grouped into the faces of one cut
|
||||
/// side: each outline, counterclockwise, first, with the holes, clockwise, that the smallest outline
|
||||
/// around them holds.
|
||||
fn cut_groups(regions: &[Vec<Point>]) -> Vec<Vec<&Vec<Point>>> {
|
||||
let bounds = |r: &[Point]| r.iter().fold(Rect::new(f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |b, p| b.union_pt(*p));
|
||||
// Each outline with its bounds and area, and the holes it holds.
|
||||
let mut groups: Vec<(Rect, f64, Vec<&Vec<Point>>)> =
|
||||
regions.iter().filter(|r| ring_area(r) > 0.0).map(|r| (bounds(r), ring_area(r), vec![r])).collect();
|
||||
for hole in regions.iter().filter(|r| ring_area(r) < 0.0) {
|
||||
let Some(&p) = hole.first() else { continue };
|
||||
let owner =
|
||||
groups.iter_mut().filter(|(b, _, g)| b.contains(p) && g.first().is_some_and(|o| ring_contains(o, p))).min_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((_, _, g)) = owner {
|
||||
g.push(hole);
|
||||
}
|
||||
}
|
||||
groups.into_iter().map(|(_, _, g)| g).collect()
|
||||
}
|
||||
|
||||
/// One face of the cut side of a partial sweep at the end of step `step`: an outline among the
|
||||
/// regions ([`cut_groups`]) and its holes, turned there and drawn as one flat, evenly shaded face,
|
||||
/// filled with the nonzero rule, so its holes stay open. The outline gives the face's shading,
|
||||
/// depth and polygon. `None` when it is seen edge on.
|
||||
fn cut_face(at: &Sweeping, regions: &[&Vec<Point>], step: usize, eye: Option<f64>, light: V3) -> Result<Option<Face>, String> {
|
||||
let origin = Point::new(at.axis, at.center_y);
|
||||
let turned: Vec<Vec<V3>> = regions.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect();
|
||||
let Some(vertices) = turned.first() else { return Ok(None) };
|
||||
let Some(mut face) = project_face(vertices, None, at.o, origin, eye, light)? else { return Ok(None) };
|
||||
let project = |v: &V3| {
|
||||
let factor = perspective_scale(eye, v.2);
|
||||
Point::new(origin.x + v.0 * factor, origin.y + v.1 * factor)
|
||||
};
|
||||
let drawn: Vec<Vec<Point>> = turned.iter().map(|c| c.iter().map(project).collect()).collect();
|
||||
if drawn.iter().flatten().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
return Err("Revolve projection is not finite".into());
|
||||
}
|
||||
face.outline = Some(PathData::new(drawn.iter().map(|c| vectorcraft_geom::SubPath::polyline(c, true)).collect()));
|
||||
Ok(Some(face))
|
||||
}
|
||||
|
||||
/// Both cut sides of a partial sweep drawn, a face for each outline among `regions` with its holes
|
||||
/// ([`cut_face`]), those seen edge on left out; none for no regions.
|
||||
fn cut_faces(at: &Sweeping, regions: &[Vec<Point>], eye: Option<f64>, light: V3) -> Result<Vec<Face>, String> {
|
||||
let groups = cut_groups(regions);
|
||||
let mut out = vec![];
|
||||
for (step, _) in cut_sides(at) {
|
||||
for group in &groups {
|
||||
out.extend(cut_face(at, group, step, eye, light)?);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The profiles whose regions the cut sides of a partial sweep close, contour by contour, each with
|
||||
/// whether its contour is closed: those of the profile drawn, and those of the profile kept for a
|
||||
/// mesh. Each profile is added as its faces are swept, with any anchor [`ring_cut`] adds, so the
|
||||
/// cut sides have a corner at every corner of the edges they share with the side.
|
||||
struct CutRegions {
|
||||
/// A partial sweep with caps: there are cut sides to close.
|
||||
on: bool,
|
||||
drawn: Vec<(Vec<Point>, bool)>,
|
||||
kept: Vec<(Vec<Point>, bool)>,
|
||||
}
|
||||
|
||||
/// The loops of one contour's region turned so the region runs counterclockwise in the profile's
|
||||
/// plane: filled with the nonzero rule, it fills. Its largest loop decides, and loops inside it that
|
||||
/// run the other way stay holes of it.
|
||||
fn outlined(mut loops: Vec<Vec<Point>>) -> Vec<Vec<Point>> {
|
||||
let largest = loops.iter().map(|l| ring_area(l)).max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or_default();
|
||||
if largest < 0.0 {
|
||||
loops.iter_mut().for_each(|l| l.reverse());
|
||||
}
|
||||
loops
|
||||
}
|
||||
|
||||
/// The regions the cut sides of a partial sweep close for the profiles `contours`, as loops that
|
||||
/// the nonzero rule fills: outlines run counterclockwise in the profile's plane and holes clockwise.
|
||||
/// Each open contour closes its own region ([`cut_region`]). The closed contours together close
|
||||
/// what `rule` fills of them, so a contour that walls a hole leaves it open, and the parts where
|
||||
/// contours overlap are filled or left open as `rule` fills them; a closed contour alone closes its
|
||||
/// own region. Every corner of the closed contours' profiles on the region's edge stays a corner
|
||||
/// of it. An error when the closed contours pass the limits of combining them.
|
||||
fn cut_loops(contours: &[(Vec<Point>, bool)], rule: FillRule, axis: f64) -> Result<Vec<Vec<Point>>, String> {
|
||||
let mut out = vec![];
|
||||
let mut rings = vec![];
|
||||
for (points, closed) in contours {
|
||||
if *closed {
|
||||
rings.push(points);
|
||||
} else {
|
||||
out.extend(outlined(cut_region(points, false, axis)));
|
||||
}
|
||||
}
|
||||
match rings.as_slice() {
|
||||
[] => {}
|
||||
[one] => out.extend(outlined(cut_region(one, true, axis))),
|
||||
_ => {
|
||||
let subpaths =
|
||||
rings.iter().map(|r| cut_ring(r, true, axis)).filter(|r| r.len() >= 3).map(|r| vectorcraft_geom::SubPath::polyline(&r, true));
|
||||
let path = PathData::new(subpaths.collect());
|
||||
let filled = vectorcraft_pathops::try_unite_all_with(&[(&path, rule)], 1e-6).map_err(|_| TOO_COMPLEX_PROFILE.to_string())?;
|
||||
// The union gives outlines counterclockwise and holes clockwise. A loop thinner than
|
||||
// 0.000001 pt is left out, as in [`cut_region`].
|
||||
out.extend(
|
||||
filled
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|s| s.anchors.iter().map(|a| a.p).collect::<Vec<_>>())
|
||||
.filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl CutRegions {
|
||||
/// The regions of a sweep with sanitized options `o`, none yet.
|
||||
fn new(o: Revolve) -> Self {
|
||||
Self { on: o.cap_ends && o.angle > 0.0 && o.angle < 360.0, drawn: vec![], kept: vec![] }
|
||||
}
|
||||
|
||||
/// Add a contour's profile `s`, drawn or kept for a mesh as `kept` says.
|
||||
fn add(&mut self, s: &Swept, closed: bool, kept: bool) {
|
||||
if self.on {
|
||||
let to = if kept { &mut self.kept } else { &mut self.drawn };
|
||||
to.push((s.points.clone(), closed));
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the cut sides of sweep `at` about `axis`, the holes `rule` leaves left open: keep them
|
||||
/// for the mesh, if any, of `kept` (whether faces are drawn, the mesh, and the error that
|
||||
/// stopped it, as [`lose_mesh`] takes them) within `face_limit` faces, and give them drawn
|
||||
/// ([`cut_faces`]).
|
||||
fn close(
|
||||
&self,
|
||||
at: &Sweeping,
|
||||
(rule, axis): (FillRule, f64),
|
||||
kept: (bool, &mut Option<&mut Vec<solid::Face3>>, &mut Option<String>),
|
||||
face_limit: usize,
|
||||
eye: Option<f64>,
|
||||
light: V3,
|
||||
) -> Result<Vec<Face>, String> {
|
||||
let (draw, mesh, lost) = kept;
|
||||
let result = match mesh.as_deref_mut() {
|
||||
Some(m) => cut_loops(&self.kept, rule, axis).and_then(|loops| {
|
||||
keep_cuts(at, &loops, |contours, normal| {
|
||||
m.push((contours, normal));
|
||||
if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) }
|
||||
})
|
||||
}),
|
||||
None => Ok(()),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
lose_mesh(draw, mesh, lost, e)?;
|
||||
}
|
||||
if !draw {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
cut_faces(at, &cut_loops(&self.drawn, rule, axis)?, eye, light)
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep for a mesh the two cut sides of a partial sweep: the loops `loops` of their regions
|
||||
/// ([`cut_loops`]) turned to each side. Outlines run one way round and holes the other, so the mesh
|
||||
/// leaves the holes open. `keep` keeps one face with its outward normal.
|
||||
fn keep_cuts(at: &Sweeping, loops: &[Vec<Point>], mut keep: impl FnMut(Vec<Vec<V3>>, V3) -> Result<(), String>) -> Result<(), String> {
|
||||
if loops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for (step, normal) in cut_sides(at) {
|
||||
let contours = loops.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect();
|
||||
keep(contours, at.o.rotate(normal))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn.
|
||||
fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec<solid::Face3>>, lost: &mut Option<String>, e: String) -> Result<(), String> {
|
||||
if !draw {
|
||||
@@ -1152,6 +1404,9 @@ fn revolve_sweep(
|
||||
// its edges are cut into.
|
||||
let (mut count, mut kept_count) = (0, 0);
|
||||
let mut curve_budget = 0;
|
||||
// With caps, a partial sweep closes its two cut sides: the regions of every contour drawn, and
|
||||
// those kept for the mesh with whether each walls a hole.
|
||||
let mut cuts = CutRegions::new(o);
|
||||
for (contour, sp) in path.subpaths.iter().enumerate() {
|
||||
let (mut drawn, mut kept) = (Swept::default(), Swept::default());
|
||||
if let Some(first) = sp.anchors.first() {
|
||||
@@ -1274,6 +1529,7 @@ fn revolve_sweep(
|
||||
};
|
||||
if let Some(m) = mesh.as_deref_mut() {
|
||||
let turn = prepare(&mut kept);
|
||||
cuts.add(&kept, sp.closed, true);
|
||||
let caps: Vec<usize> = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect();
|
||||
let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal));
|
||||
if let Err(e) = kept {
|
||||
@@ -1284,6 +1540,7 @@ fn revolve_sweep(
|
||||
continue;
|
||||
}
|
||||
let turn = prepare(&mut drawn);
|
||||
cuts.add(&drawn, sp.closed, false);
|
||||
let profile = &drawn.points;
|
||||
let along = along_profile(profile, axis, sp.closed);
|
||||
for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() {
|
||||
@@ -1344,6 +1601,7 @@ fn revolve_sweep(
|
||||
}
|
||||
}
|
||||
}
|
||||
cuts.close(&at, (rule, axis), (draw, &mut mesh, &mut lost), face_limit, eye, light)?.into_iter().try_for_each(|face| emit(Some(face), 1))?;
|
||||
faces.sort_by(|a, b| a.depth.total_cmp(&b.depth));
|
||||
Ok((faces, lost))
|
||||
}
|
||||
|
||||
@@ -118,8 +118,9 @@ pub fn inflate_meshed(
|
||||
}
|
||||
|
||||
/// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than
|
||||
/// 360° caps its ends with sectors and leaves its two cut sides open ([`Revolve::cap_ends`]). The
|
||||
/// walls of holes under `rule`, such as the counter of an O, face into the hole.
|
||||
/// 360° caps its ends with sectors and closes its two cut sides with flat faces ([`Revolve::cap_ends`]).
|
||||
/// The walls of holes under `rule`, such as the counter of an O, face into the hole, and the cut
|
||||
/// sides leave those holes open.
|
||||
pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result<Mesh, String> {
|
||||
let mut faces = vec![];
|
||||
crate::revolve_faces(path, rule, bounds, options, Some(&mut faces))?;
|
||||
@@ -127,7 +128,7 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo
|
||||
}
|
||||
|
||||
/// The area-weighted normal of `contours` (Newell's method).
|
||||
fn newell(contours: &[Vec<V3>]) -> V3 {
|
||||
pub(crate) fn newell(contours: &[Vec<V3>]) -> V3 {
|
||||
let mut n = V3::default();
|
||||
for c in contours {
|
||||
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
|
||||
@@ -210,7 +211,7 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> {
|
||||
|
||||
/// The triangles covering one face: `contours` (outlines one way round, holes the other) on the
|
||||
/// plane across `normal` (its Newell normal).
|
||||
fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) -> Result<Vec<[V3; 3]>, String> {
|
||||
pub(crate) fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) -> Result<Vec<[V3; 3]>, String> {
|
||||
// Cut the face on the coordinate plane it is least slanted to, turned so outlines run
|
||||
// counterclockwise.
|
||||
let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs());
|
||||
|
||||
@@ -239,7 +239,7 @@ fn a_revolved_profile_is_a_closed_cylinder() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_revolve_caps_its_ends_with_sectors() {
|
||||
fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((20.0, 0.0));
|
||||
b.line_to((20.0, 100.0));
|
||||
@@ -247,8 +247,12 @@ fn a_partial_revolve_caps_its_ends_with_sectors() {
|
||||
let r = p.bounds().unwrap();
|
||||
let o = Revolve { angle: 90.0, offset: 10.0, segments: 64, ..Revolve::default() };
|
||||
let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap();
|
||||
let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0);
|
||||
// The side and the two end sectors, and the two cut sides, each 10 pt from the axis by 100 pt.
|
||||
let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0) + 2.0 * 10.0 * 100.0;
|
||||
assert!((area(&m) - exact).abs() / exact < 0.01, "{} vs {exact}", area(&m));
|
||||
assert!(closed(&m), "the quarter of a cylinder is a closed solid");
|
||||
let hollow = revolve_mesh(&p, FillRule::NonZero, r, Revolve { cap_ends: false, ..o }).unwrap();
|
||||
assert!(!closed(&hollow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The shadow a 3D effect's solid casts: its faces projected along the first light onto a plane
|
||||
//! behind the object (square to the view) or below it (under the object's own vertical axis, turned
|
||||
//! with it), as one hard-edged vector shape.
|
||||
//! with it), as one vector shape. The light's Softness gives the shape a blur radius
|
||||
//! ([`ShadowPlane::blur`]); at 0 the shape stays hard-edged.
|
||||
//!
|
||||
//! Every face is projected whole, so the shape is the union of the projected faces: each contour is
|
||||
//! turned so that its face winds the same way, and the shape is filled with the nonzero rule. The
|
||||
@@ -48,20 +49,36 @@ pub struct Shadow {
|
||||
/// How far the plane reaches, as a share (0.1..4): at 1 the plane is a square four times the
|
||||
/// object's largest size across.
|
||||
pub bounds: f64,
|
||||
/// The casting light's Softness (0..1): at 0 the shadow is hard-edged, above it blurred
|
||||
/// ([`ShadowPlane::blur`]).
|
||||
pub softness: f64,
|
||||
}
|
||||
|
||||
impl Default for Shadow {
|
||||
fn default() -> Self {
|
||||
Self { position: ShadowPosition::Behind, distance: 0.0, bounds: 1.0 }
|
||||
Self { position: ShadowPosition::Behind, distance: 0.0, bounds: 1.0, softness: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Shadow {
|
||||
fn sanitized(self) -> Self {
|
||||
Self { distance: finite(self.distance, 0.0, 0.0, 1.0), bounds: finite(self.bounds, 1.0, 0.1, 4.0), ..self }
|
||||
Self {
|
||||
distance: finite(self.distance, 0.0, 0.0, 1.0),
|
||||
bounds: finite(self.bounds, 1.0, 0.1, 4.0),
|
||||
softness: finite(self.softness, 0.0, 0.0, 1.0),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The blur radius at full Softness on a plane that touches the object, as a share of the object's
|
||||
/// largest size, and what each share of Distance from Object adds to it. VectorCraft's own values.
|
||||
const BLUR_NEAR: f64 = 0.05;
|
||||
const BLUR_PER_DISTANCE: f64 = 0.2;
|
||||
|
||||
/// Most blur radius a shadow takes, in points (the Gaussian Blur effect's own limit).
|
||||
pub const MAX_SHADOW_BLUR: f64 = 1000.0;
|
||||
|
||||
/// The rotation and projection a solid is drawn with.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Projection {
|
||||
@@ -119,6 +136,17 @@ pub struct ShadowPlane {
|
||||
foot: V3,
|
||||
/// Half the side of the square the plane ends at.
|
||||
half: f64,
|
||||
/// The blur radius of the shadow on the plane, in points ([`ShadowPlane::blur`]).
|
||||
blur: f64,
|
||||
}
|
||||
|
||||
impl ShadowPlane {
|
||||
/// The radius, in points, of the blur that softens the edges of the shadow on this plane: 0 at
|
||||
/// Softness 0, and with Softness a share of the object's largest size that grows with the
|
||||
/// plane's distance from the object (VectorCraft's own mapping), at most [`MAX_SHADOW_BLUR`].
|
||||
pub fn blur(&self) -> f64 {
|
||||
self.blur
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces of one object's solids, gathered to cast one shadow. The solids of one object share
|
||||
@@ -254,13 +282,15 @@ impl ShadowCaster {
|
||||
let level = corners().map(|v| n.dot(*v)).fold(f64::INFINITY, f64::min) - s.distance * size;
|
||||
let centre = V3((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0, (lo.2 + hi.2) / 2.0);
|
||||
let foot = add(centre, scale(n, level - n.dot(centre)));
|
||||
Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size })
|
||||
let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR);
|
||||
let blur = if blur.is_finite() { blur } else { 0.0 };
|
||||
Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size, blur })
|
||||
}
|
||||
|
||||
/// The shadow the faces in the ranges `faces` cast on `plane`, on the page, filled with the
|
||||
/// nonzero rule; `None` when nothing of it falls within the plane.
|
||||
pub fn path_on(&self, plane: &ShadowPlane, faces: &[Range<usize>]) -> Option<PathData> {
|
||||
let &ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half } = plane;
|
||||
let &ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half, .. } = plane;
|
||||
// A corner's shadow, in the plane's axes about the foot.
|
||||
let cast = |v: V3| {
|
||||
let q = add(v, scale(light, -(n.dot(v) - level) / reach));
|
||||
@@ -335,11 +365,11 @@ pub fn inflate_shadowed(
|
||||
}
|
||||
|
||||
/// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces
|
||||
/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where
|
||||
/// [`ShadowCaster::revolve`] adds for it with the fill rule of `options`. An error where
|
||||
/// [`crate::revolve`] gives one.
|
||||
pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec<Face>, SolidFaces), String> {
|
||||
let mut kept = vec![];
|
||||
let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?;
|
||||
let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?;
|
||||
let projection = Some(crate::revolve_projection(bounds, options.sanitized()));
|
||||
Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection }))
|
||||
}
|
||||
|
||||
@@ -127,10 +127,41 @@ fn bad_settings_are_sanitized_and_an_empty_caster_casts_nothing() {
|
||||
let wild = Shadow { distance: f64::NAN, bounds: f64::INFINITY, ..Shadow::default() };
|
||||
assert_eq!(wild.sanitized(), Shadow { bounds: 1.0, ..Shadow::default() });
|
||||
assert_eq!(Shadow { distance: -3.0, bounds: 99.0, ..Shadow::default() }.sanitized(), Shadow { bounds: 4.0, ..Shadow::default() });
|
||||
assert_eq!(Shadow { softness: f64::NAN, ..Shadow::default() }.sanitized(), Shadow::default());
|
||||
assert_eq!(Shadow { softness: 7.0, ..Shadow::default() }.sanitized(), Shadow { softness: 1.0, ..Shadow::default() });
|
||||
assert_eq!(ShadowPosition::parse("below"), Some(ShadowPosition::Below));
|
||||
assert_eq!(ShadowPosition::parse("under"), None);
|
||||
}
|
||||
|
||||
/// Softness blurs the shadow by a radius that grows with Softness and with the plane's distance
|
||||
/// from the object, and scales with the object; at 0 the shadow keeps its hard edge. The outline
|
||||
/// itself does not change.
|
||||
#[test]
|
||||
fn softness_blurs_the_shadow_more_the_farther_the_plane_is() {
|
||||
let blur = |s: f64, shadow: Shadow| {
|
||||
let path = square(100.0, 100.0, s);
|
||||
let mut caster = ShadowCaster::new();
|
||||
caster.extrude(&path, FillRule::NonZero, Rect::new(100.0, 100.0, 100.0 + s, 100.0 + s), Extrude::default(), front()).unwrap();
|
||||
let all = 0..caster.len();
|
||||
let all = std::slice::from_ref(&all);
|
||||
let plane = caster.shadow_plane(shadow, all).unwrap();
|
||||
(plane.blur(), caster.path_on(&plane, all).unwrap())
|
||||
};
|
||||
let (hard, hard_path) = blur(100.0, Shadow::default());
|
||||
assert_eq!(hard, 0.0);
|
||||
let (half, half_path) = blur(100.0, Shadow { softness: 0.5, ..Shadow::default() });
|
||||
let (full, _) = blur(100.0, Shadow { softness: 1.0, ..Shadow::default() });
|
||||
let (far, _) = blur(100.0, Shadow { softness: 1.0, distance: 1.0, ..Shadow::default() });
|
||||
assert!(half > 0.0 && full > half && far > full, "{half} {full} {far}");
|
||||
assert_eq!(half_path, hard_path, "the outline stays");
|
||||
// Twice the object, twice the blur.
|
||||
let (twice, _) = blur(200.0, Shadow { softness: 1.0, ..Shadow::default() });
|
||||
assert!((twice - 2.0 * full).abs() < 1e-9, "{twice} {full}");
|
||||
// A huge object's blur stops at the Gaussian Blur effect's limit.
|
||||
let (huge, _) = blur(1.0e7, Shadow { softness: 1.0, distance: 1.0, ..Shadow::default() });
|
||||
assert_eq!(huge, MAX_SHADOW_BLUR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_faces_one_shadow_is_cast_from_are_bounded() {
|
||||
// An open profile of 500 points revolves into about 64,000 faces at 128 segments: five fit,
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
|
||||
mod caps;
|
||||
mod classic;
|
||||
mod cut_sides;
|
||||
mod lighting;
|
||||
mod multiple_lights;
|
||||
mod profile_limits;
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
use crate::*;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
/// Swept with Cap on, unshaded and seen from the front.
|
||||
fn options() -> Revolve {
|
||||
Revolve { cap_ends: true, shade: false, ..Default::default() }
|
||||
}
|
||||
|
||||
fn profile(data: &str) -> PathData {
|
||||
PathData::from_bezpath(&BezPath::from_svg(data).unwrap())
|
||||
}
|
||||
|
||||
fn area(face: &Face) -> f64 {
|
||||
face.path().to_bezpath().area().abs()
|
||||
}
|
||||
|
||||
/// The faces of the cut sides among `faces`: the flat faces in a plane through the axis, which these
|
||||
/// tests keep upright. The strips of the swept side lie off the axis, and the endpoint caps across it.
|
||||
fn cut_sides(faces: &[Face]) -> Vec<&Face> {
|
||||
faces.iter().filter(|f| !f.cap && f.plane.is_some_and(|p| p.offset.abs() < 1e-6 && p.normal[1].abs() < 1e-9)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_turn_closes_both_cut_sides_with_the_region_between_the_profile_and_the_axis() {
|
||||
let path = profile("M40 10 L40 90");
|
||||
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
|
||||
// Seen from the front, a half turn's two cut sides both face the viewer: the profile's plane
|
||||
// to the right of the axis and to its left.
|
||||
let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
assert_eq!(cuts.len(), 2);
|
||||
for cut in &cuts {
|
||||
assert!((area(cut) - 40.0 * 80.0).abs() < 1e-6, "{}", area(cut));
|
||||
assert!(cut.points.iter().all(|p| (10.0 - 1e-9..=90.0 + 1e-9).contains(&p.y)));
|
||||
}
|
||||
assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x >= -1e-9)));
|
||||
assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x <= 1e-9)));
|
||||
assert!(faces.windows(2).all(|pair| pair[0].depth <= pair[1].depth));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_off_full_turns_and_no_turn_leave_the_cut_sides_open() {
|
||||
let path = profile("M40 10 L40 90");
|
||||
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
|
||||
for (o, what) in [
|
||||
(Revolve { angle: 180.0, cap_ends: false, ..options() }, "hollow"),
|
||||
(Revolve { angle: 360.0, rotation_x: 90.0, ..options() }, "a full turn"),
|
||||
(Revolve { angle: 0.0, ..options() }, "no turn"),
|
||||
] {
|
||||
let faces = revolve(&path, bounds, o).unwrap();
|
||||
assert!(cut_sides(&faces).is_empty(), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_profile_closes_its_cut_sides_with_its_area_and_leaves_its_hole_open() {
|
||||
// A square ring away from the axis, its hole wound the other way.
|
||||
let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L30 40 L50 40 L50 20 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() };
|
||||
let faces = revolve(&path, bounds, o).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
assert_eq!(cuts.len(), 2);
|
||||
for cut in &cuts {
|
||||
let outline = cut.outline.as_ref().unwrap();
|
||||
assert_eq!(outline.subpaths.len(), 2, "the outline and its hole");
|
||||
// Turned 20° about the vertical axis, each side is foreshortened by cos 20°.
|
||||
let expected = (40.0 * 40.0 - 20.0 * 20.0) * 20f64.to_radians().cos();
|
||||
assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut));
|
||||
}
|
||||
// Visibility measures the face with its hole open.
|
||||
assert!(!visible_faces(&faces).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_even_odd_hole_wound_with_its_outline_stays_open_in_the_drawn_cut_sides() {
|
||||
// The hole runs the same way round as the outline, so only the even-odd rule leaves it open.
|
||||
let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L50 20 L50 40 L30 40 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 180.0, offset: 10.0, ..options() };
|
||||
let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::EvenOdd, ..o }).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
assert_eq!(cuts.len(), 2);
|
||||
for cut in cuts {
|
||||
// The drawn path is filled with the nonzero rule; the hole is in the middle of the side.
|
||||
let filled = cut.path().to_bezpath();
|
||||
assert!(!filled.contains(filled.bounding_box().center()));
|
||||
assert!((area(cut) - (40.0 * 40.0 - 20.0 * 20.0)).abs() < 1e-6, "{}", area(cut));
|
||||
}
|
||||
// Under the nonzero rule the inner contour fills too: each side is the whole outer square.
|
||||
let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::NonZero, ..o }).unwrap();
|
||||
let areas: Vec<f64> = cut_sides(&faces).iter().map(|f| area(f)).collect();
|
||||
assert_eq!(areas.len(), 2);
|
||||
assert!(areas.iter().all(|a| (a - 1600.0).abs() < 1e-6), "{areas:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bow_tie_whose_loops_cancel_out_closes_its_cut_sides_with_both_loops() {
|
||||
// Two triangles of 400 pt² that meet at (40, 30), wound opposite ways.
|
||||
let path = profile("M20 10 L60 50 L60 10 L20 50 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() };
|
||||
let faces = revolve(&path, bounds, o).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
// Each side draws each loop as a face.
|
||||
assert_eq!(cuts.len(), 4);
|
||||
let expected = 400.0 * 20f64.to_radians().cos();
|
||||
for cut in cuts {
|
||||
assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut));
|
||||
}
|
||||
let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, rotation_y: 0.0, ..o }).unwrap();
|
||||
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
|
||||
assert!((start - 800.0).abs() < 1e-6, "{start}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_closes_a_cut_side_that_crosses_itself_with_both_of_its_loops() {
|
||||
// Loops of 900 pt² and 100 pt² that meet at (50, 40): the mesh covers both, and nothing
|
||||
// between them.
|
||||
let path = profile("M20 10 L60 50 L60 30 L20 70 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, offset: 10.0, ..options() }).unwrap();
|
||||
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
|
||||
assert!((start - 1000.0).abs() < 1e-6, "{start}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_thinner_than_a_millionth_of_a_point_is_debris_and_closes_no_cut_side() {
|
||||
// 0.0000005 pt wide and 80 pt tall, beside a square 40 pt across.
|
||||
let path = profile("M40 10 L40.0000005 10 L40.0000005 90 L40 90 Z M50 10 L90 10 L90 50 L50 50 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 90.0, offset: 10.0, ..options() };
|
||||
let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, o).unwrap();
|
||||
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
|
||||
assert!((start - 40.0 * 40.0).abs() < 1e-6, "{start}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_sides_whose_holes_cannot_be_found_within_the_limit_are_refused() {
|
||||
// 2,100 squares on top of each other: each test of a point meets every square.
|
||||
let square = "M20 10 L60 10 L60 50 L20 50 Z ";
|
||||
let path = profile(&square.repeat(2100));
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 90.0, offset: 10.0, ..options() };
|
||||
assert_eq!(revolve(&path, bounds, o).err().as_deref(), Some(TOO_COMPLEX_PROFILE));
|
||||
// Hollow, the sweep has no cut sides to close.
|
||||
assert!(revolve(&path, bounds, Revolve { cap_ends: false, ..o }).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_keeps_both_of_two_separate_regions_wound_opposite_ways() {
|
||||
let path = profile("M20 10 L30 10 L30 50 L20 50 Z M40 10 L40 50 L50 50 L50 10 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
// Seen from behind, the half turn's walls are behind both cut sides, which nothing covers. Seen
|
||||
// from the front, the walls the outer square sweeps cover both sides completely.
|
||||
for (rotation_y, all) in [(180.0, 4.0 * 10.0 * 40.0), (0.0, 0.0)] {
|
||||
let faces = revolve(&path, bounds, Revolve { angle: 180.0, offset: 10.0, rotation_y, ..options() }).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
assert_eq!(cuts.len(), 4, "a face for each region on each side");
|
||||
let mut depths: Vec<f64> = cuts.iter().map(|f| f.depth).collect();
|
||||
depths.dedup();
|
||||
let visible = visible_faces(&faces).unwrap();
|
||||
let shown: f64 = visible
|
||||
.iter()
|
||||
.filter(|v| depths.contains(&v.depth))
|
||||
.flat_map(|v| v.path.subpaths.iter().map(|s| PathData::new(vec![s.clone()]).to_bezpath().area().abs()))
|
||||
.sum();
|
||||
assert!((shown - all).abs() < 1e-6, "turned {rotation_y}°, the cut sides show {shown}, not {all}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_open_contour_of_a_compound_profile_closes_its_own_region_on_each_side() {
|
||||
let path = profile("M40 10 L40 40 M20 60 L50 90");
|
||||
let bounds = Rect::new(0.0, 10.0, 50.0, 90.0);
|
||||
let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap();
|
||||
let mut areas: Vec<f64> = cut_sides(&faces).iter().map(|f| area(f)).collect();
|
||||
areas.sort_by(f64::total_cmp);
|
||||
// The trapezoid between the slanted line and the axis, (20 + 50) / 2 × 30, and 40 × 30.
|
||||
let expected = [35.0 * 30.0, 35.0 * 30.0, 40.0 * 30.0, 40.0 * 30.0];
|
||||
assert_eq!(areas.len(), 4);
|
||||
assert!(areas.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-6), "{areas:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_side_seen_edge_on_is_not_drawn() {
|
||||
let path = profile("M40 10 L40 90");
|
||||
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
|
||||
// A quarter turn ends in the plane through the axis toward the viewer.
|
||||
let faces = revolve(&path, bounds, Revolve { angle: 90.0, ..options() }).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
assert_eq!(cuts.len(), 1);
|
||||
assert!((area(cuts[0]) - 40.0 * 80.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_sides_are_shaded_evenly_by_their_plane() {
|
||||
let path = profile("M40 10 L40 90");
|
||||
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
|
||||
let o = Revolve { angle: 180.0, shade: true, rotation_y: 30.0, ..options() };
|
||||
let faces = revolve(&path, bounds, o).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
assert_eq!(cuts.len(), 2);
|
||||
for cut in cuts {
|
||||
assert!(cut.gradient.is_none(), "a flat face is shaded evenly");
|
||||
assert!(cut.plane.is_some());
|
||||
assert!((0.0..=1.0).contains(&cut.brightness));
|
||||
// Both sides lie in the plane through the axis turned 30°, whose normal faces the viewer.
|
||||
let n = cut.normal;
|
||||
assert!((n[0].abs() - 30f64.to_radians().sin()).abs() < 1e-9 && n[2] > 0.0, "{n:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The area of the triangles of `mesh` whose normal is `normal`.
|
||||
fn area_facing(mesh: &Mesh, normal: [f64; 3]) -> f64 {
|
||||
mesh.triangles
|
||||
.iter()
|
||||
.filter(|t| t.iter().all(|&i| mesh.normals[i as usize].iter().zip(normal).all(|(a, b)| (a - b).abs() < 1e-9)))
|
||||
.map(|t| {
|
||||
let [a, b, c] = t.map(|i| mesh.positions[i as usize]);
|
||||
let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
|
||||
let x = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
||||
(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]).sqrt() / 2.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_closes_both_cut_sides_and_leaves_holes_open_under_either_fill_rule() {
|
||||
let ring = "M20 10 L60 10 L60 50 L20 50 Z";
|
||||
let o = Revolve { angle: 90.0, offset: 10.0, ..options() };
|
||||
let expected = 40.0 * 40.0 - 20.0 * 20.0;
|
||||
// The hole wound against the outline, and wound with it under even-odd.
|
||||
for (hole, rule) in [("M30 20 L30 40 L50 40 L50 20 Z", FillRule::NonZero), ("M30 20 L50 20 L50 40 L30 40 Z", FillRule::EvenOdd)] {
|
||||
let path = profile(&format!("{ring} {hole}"));
|
||||
let mesh = revolve_mesh(&path, rule, path.bounds().unwrap(), o).unwrap();
|
||||
// The start faces back, against the sweep; a quarter turn ends facing left, along it.
|
||||
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
|
||||
let end = area_facing(&mesh, [-1.0, 0.0, 0.0]);
|
||||
assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}");
|
||||
assert!((end - expected).abs() < 1e-6, "{rule:?}: {end}");
|
||||
}
|
||||
let path = profile(ring);
|
||||
let hollow = revolve_mesh(&path, FillRule::NonZero, path.bounds().unwrap(), Revolve { cap_ends: false, ..o }).unwrap();
|
||||
assert_eq!(area_facing(&hollow, [0.0, 0.0, -1.0]), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_contours_close_the_cut_sides_with_what_the_fill_rule_fills() {
|
||||
// Two squares of 1,600 pt² that overlap in 300 pt², and only one corner of each lies inside
|
||||
// the other. The even-odd rule leaves the overlap open; the nonzero rule fills it once.
|
||||
let path = profile("M20 10 L60 10 L60 50 L20 50 Z M50 20 L90 20 L90 60 L50 60 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 180.0, offset: 10.0, ..options() };
|
||||
for (rule, expected) in [(FillRule::EvenOdd, 2.0 * (1600.0 - 300.0)), (FillRule::NonZero, 2.0 * 1600.0 - 300.0)] {
|
||||
let faces = revolve(&path, bounds, Revolve { fill_rule: rule, ..o }).unwrap();
|
||||
let cuts = cut_sides(&faces);
|
||||
let total: f64 = cuts.iter().map(|f| area(f)).sum();
|
||||
assert!((total - 2.0 * expected).abs() < 1e-6, "{rule:?}: both sides cover {total}, not twice {expected}");
|
||||
let mesh = revolve_mesh(&path, rule, bounds, Revolve { angle: 90.0, ..o }).unwrap();
|
||||
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
|
||||
assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cut_sides_kept_for_a_mesh_have_a_corner_at_every_corner_of_the_side() {
|
||||
// With graphics mapped, the square's side is cut half way round from its outer side, at
|
||||
// (20, 30), which is not an anchor: the cut side takes that corner too.
|
||||
let path = profile("M20 10 L60 10 L60 50 L20 50 Z");
|
||||
let bounds = path.bounds().unwrap();
|
||||
let o = Revolve { angle: 90.0, offset: 10.0, map_surface: true, ..options() };
|
||||
let mut faces = vec![];
|
||||
revolve_faces(&path, FillRule::NonZero, bounds, o, Some(&mut faces)).unwrap();
|
||||
// The corners in the plane where the sweep starts, of every face kept for the mesh and of the
|
||||
// cut side's alone, which faces back against the sweep.
|
||||
let in_plane = |all: bool| {
|
||||
let start = |n: &V3| (n.0.abs() + n.1.abs() + (n.2 + 1.0).abs()) < 1e-9;
|
||||
let kept = faces.iter().filter(|(_, n)| all || start(n));
|
||||
kept.flat_map(|(contours, _)| contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::<Vec<V3>>()
|
||||
};
|
||||
let cut = in_plane(false);
|
||||
assert!(!cut.is_empty());
|
||||
for p in in_plane(true) {
|
||||
assert!(cut.iter().any(|q| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9), "{p:?} is not a corner of the cut side");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_cut_sides_face_out_of_a_sweep_on_the_left_of_its_axis() {
|
||||
// The axis is 40 pt to the right of the line, which sweeps from the left of the axis to its back.
|
||||
let path = profile("M40 10 L40 90");
|
||||
let o = Revolve { angle: 90.0, edge: Edge::Right, offset: 40.0, ..options() };
|
||||
let mesh = revolve_mesh(&path, FillRule::NonZero, Rect::new(40.0, 10.0, 40.0, 90.0), o).unwrap();
|
||||
assert!((area_facing(&mesh, [0.0, 0.0, 1.0]) - 40.0 * 80.0).abs() < 1e-6);
|
||||
assert!((area_facing(&mesh, [1.0, 0.0, 0.0]) - 40.0 * 80.0).abs() < 1e-6);
|
||||
}
|
||||
@@ -199,7 +199,8 @@ pub fn visible_faces(faces: &[Face]) -> Result<Vec<VisibleFace>, String> {
|
||||
}) {
|
||||
return Err("Revolve visibility requires finite projected faces".into());
|
||||
}
|
||||
let all = faces.iter().flat_map(|f| &f.points).copied().collect::<Vec<_>>();
|
||||
let outlines = faces.iter().filter_map(|f| f.outline.as_ref()).flat_map(|o| o.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)));
|
||||
let all = faces.iter().flat_map(|f| f.points.iter().copied()).chain(outlines).collect::<Vec<_>>();
|
||||
let total = bounds(&all);
|
||||
if total.width() <= 0.0 || total.height() <= 0.0 {
|
||||
return Ok(vec![]);
|
||||
@@ -222,7 +223,9 @@ pub fn visible_faces(faces: &[Face]) -> Result<Vec<VisibleFace>, String> {
|
||||
if pieces.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let source_bounds = bounds(&face.points);
|
||||
// A face drawn as several contours, such as a cut side of a partial sweep, reaches past its
|
||||
// own polygon: look for covers over all of its pieces.
|
||||
let source_bounds = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)).unwrap_or_else(|| bounds(&face.points));
|
||||
let mut fragments: Vec<_> = pieces.iter().map(|p| p.points.clone()).collect();
|
||||
let mut clipped = false;
|
||||
'covers: for tile in index.tiles(source_bounds) {
|
||||
|
||||
@@ -91,6 +91,22 @@ fn triangulate(mut points: Vec<Point>, epsilon: f64, work: &mut usize, depth: us
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Triangles covering a flat face drawn as several straight-edged contours, such as a cut side of a
|
||||
/// partial Revolve whose profile has holes: outlines one way round and holes the other, the holes
|
||||
/// left uncovered. The work is checked before the face is cut, at four times its corners squared.
|
||||
fn with_holes(outline: &vectorcraft_geom::PathData, epsilon: f64, work: &mut usize) -> Result<Vec<Vec<Point>>, String> {
|
||||
const LIMIT: &str = "Revolve visibility exceeds its geometry work limit";
|
||||
let rings: Vec<Vec<crate::V3>> = outline.subpaths.iter().map(|s| s.anchors.iter().map(|a| crate::V3(a.p.x, a.p.y, 0.0)).collect()).collect();
|
||||
let corners: usize = rings.iter().map(Vec::len).sum();
|
||||
*work = work.saturating_add(corners.saturating_mul(corners).saturating_mul(4));
|
||||
if *work > MAX_WORK {
|
||||
return Err(LIMIT.into());
|
||||
}
|
||||
let mut spent = 0;
|
||||
let triangles = crate::mesh::triangulate(&rings, crate::mesh::newell(&rings), &mut spent)?;
|
||||
Ok(triangles.into_iter().map(|t| clean(t.iter().map(|v| Point::new(v.0, v.1)).collect(), epsilon)).filter(|t| !t.is_empty()).collect())
|
||||
}
|
||||
|
||||
pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result<Vec<Vec<Point>>, String> {
|
||||
if let Some(strips) = &face.visibility_pieces {
|
||||
let mut out = vec![];
|
||||
@@ -99,6 +115,9 @@ pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result<Vec<
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
if let Some(outline) = face.outline.as_ref().filter(|o| !face.cap && o.subpaths.len() > 1) {
|
||||
return with_holes(outline, epsilon, work);
|
||||
}
|
||||
if !face.cap {
|
||||
return triangulate(clean(face.points.clone(), epsilon), epsilon, work, 0);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod enclosing_lasso;
|
||||
pub mod extend_path;
|
||||
pub mod measure_inspect;
|
||||
pub mod parametric_shape;
|
||||
pub mod polygonal_lasso;
|
||||
pub mod shared_edge;
|
||||
pub mod slide_anchor;
|
||||
pub mod smart_pen;
|
||||
@@ -38,13 +39,21 @@ pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, l
|
||||
|
||||
pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }];
|
||||
|
||||
pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }];
|
||||
|
||||
/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the
|
||||
/// heading the All Tools drawer lists it under (its add-on's name).
|
||||
const HEADED: &[(&[ToolInfo], &str)] =
|
||||
&[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour"), (BOX_3D, "3D Box")];
|
||||
const HEADED: &[(&[ToolInfo], &str)] = &[
|
||||
(PATH_TOOLS, "Path Precision Tools"),
|
||||
(SMART_PEN, "Smart Pen"),
|
||||
(ENCLOSING_LASSO, "Enclosing Lasso"),
|
||||
(CONTOUR, "Contour"),
|
||||
(BOX_3D, "3D Box"),
|
||||
(POLYGONAL_LASSO, "Polygonal Lasso"),
|
||||
];
|
||||
|
||||
/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]).
|
||||
pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D];
|
||||
pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO];
|
||||
|
||||
/// The heading the All Tools drawer lists tool `id` under: its add-on's name.
|
||||
pub fn heading(id: &str) -> Option<&'static str> {
|
||||
@@ -66,6 +75,7 @@ pub fn create(id: &str) -> Option<Box<dyn Tool>> {
|
||||
enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()),
|
||||
contour::ID => Box::new(contour::ContourTool::default()),
|
||||
box3d::ID => Box::new(box3d::Box3dTool::default()),
|
||||
polygonal_lasso::ID => Box::new(polygonal_lasso::PolygonalLassoTool::default()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -88,6 +98,7 @@ mod tests {
|
||||
assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso"));
|
||||
assert_eq!(heading(contour::ID), Some("Contour"));
|
||||
assert_eq!(heading(box3d::ID), Some("3D Box"));
|
||||
assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso"));
|
||||
assert_eq!(GROUPS.len(), HEADED.len());
|
||||
assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID));
|
||||
assert!(create("pen").is_none() && heading("pen").is_none());
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Polygonal Lasso selects anchor points inside a straight-edged loop, as the Lasso does inside a
|
||||
//! freehand one. Each click sets a vertex, and a segment from the last vertex follows the pointer.
|
||||
//! A double-click, Enter or a click on the first vertex closes the loop; Backspace or Delete removes
|
||||
//! the last vertex and Escape drops the loop. Shift keeps the next segment to 45° steps (from the Constrain
|
||||
//! Angle). Shift held at the first click adds to the selection and Alt subtracts from it.
|
||||
|
||||
use vectorcraft_geom::{Point, constrain_angle_from};
|
||||
|
||||
use crate::meshedit::MeshEdit;
|
||||
use crate::xform::lasso_select;
|
||||
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
|
||||
pub const ID: &str = "polygonalLasso";
|
||||
/// The most vertices a loop keeps; clicks past it are ignored.
|
||||
pub(crate) const MAX_VERTICES: usize = 65_536;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PolygonalLassoTool {
|
||||
vertices: Vec<Point>,
|
||||
/// Where the segment from the last vertex ends: the pointer, constrained while Shift is held.
|
||||
hover: Option<Point>,
|
||||
/// Shift held at the first click: the loop adds to the selection.
|
||||
add: bool,
|
||||
/// Alt held at the first click: the loop subtracts from the selection.
|
||||
sub: bool,
|
||||
/// Whether the press in progress set a vertex (a dropped press takes it back).
|
||||
pressed_vertex: bool,
|
||||
/// The picked gradient mesh points (the tool's `meshPoints` option), as with the Lasso.
|
||||
mesh: MeshEdit,
|
||||
}
|
||||
|
||||
impl PolygonalLassoTool {
|
||||
/// The next vertex for a pointer at `p`: with Shift and a vertex already set, at a 45° step
|
||||
/// from the last vertex.
|
||||
fn target(&self, cx: &ToolContext, p: Point, mods: Mods) -> Point {
|
||||
match self.vertices.last() {
|
||||
Some(&last) if mods.shift => last + constrain_angle_from(p - last, 45.0, cx.constrain_angle),
|
||||
_ => p,
|
||||
}
|
||||
}
|
||||
|
||||
/// How near a vertex a click counts as a click on it.
|
||||
fn reach(cx: &ToolContext) -> f64 {
|
||||
cx.tol(5.0).max(cx.point_tol())
|
||||
}
|
||||
|
||||
/// Removes the last vertex and hides the segment that followed the pointer until the pointer
|
||||
/// moves again. A press in progress no longer owns a vertex, so dropping it removes nothing more.
|
||||
fn take_back_vertex(&mut self) {
|
||||
self.vertices.pop();
|
||||
self.hover = None;
|
||||
self.pressed_vertex = false;
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.vertices.clear();
|
||||
self.hover = None;
|
||||
self.pressed_vertex = false;
|
||||
}
|
||||
|
||||
/// Closes the loop and selects inside it. A loop of fewer than three vertices selects nothing.
|
||||
fn close(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
let vertices = std::mem::take(&mut self.vertices);
|
||||
self.clear();
|
||||
if vertices.len() < 3 {
|
||||
return vec![];
|
||||
}
|
||||
vec![lasso_select(cx, &mut self.mesh, &vertices, self.add, self.sub)]
|
||||
}
|
||||
}
|
||||
|
||||
impl Tool for PolygonalLassoTool {
|
||||
fn id(&self) -> &'static str {
|
||||
ID
|
||||
}
|
||||
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
if !ev.pos.is_finite() {
|
||||
return vec![];
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Move | PointerKind::Drag => {
|
||||
self.hover = (!self.vertices.is_empty()).then(|| self.target(cx, ev.pos, ev.mods));
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
self.pressed_vertex = false;
|
||||
let reach = Self::reach(cx);
|
||||
let Some(&first) = self.vertices.first() else {
|
||||
self.add = ev.mods.shift;
|
||||
self.sub = ev.mods.alt;
|
||||
self.vertices.push(ev.pos);
|
||||
self.pressed_vertex = true;
|
||||
return vec![];
|
||||
};
|
||||
if first.distance(ev.pos) <= reach {
|
||||
// With fewer than three vertices, a click on the first one adds nothing.
|
||||
return if self.vertices.len() >= 3 { self.close(cx) } else { vec![] };
|
||||
}
|
||||
let p = self.target(cx, ev.pos, ev.mods);
|
||||
// The second click of a double-click lands on the vertex the first one set.
|
||||
if self.vertices.last().is_some_and(|last| last.distance(p) > reach) && self.vertices.len() < MAX_VERTICES {
|
||||
self.vertices.push(p);
|
||||
self.pressed_vertex = true;
|
||||
}
|
||||
self.hover = Some(p);
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Up => {
|
||||
self.pressed_vertex = false;
|
||||
vec![]
|
||||
}
|
||||
PointerKind::DoubleClick => self.close(cx),
|
||||
// The third click of a triple-click starts no loop of its own.
|
||||
PointerKind::TripleClick => {
|
||||
if self.vertices.len() == 1 {
|
||||
self.clear();
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
match key {
|
||||
ToolKey::Enter => self.close(cx),
|
||||
ToolKey::Escape => {
|
||||
self.clear();
|
||||
vec![]
|
||||
}
|
||||
ToolKey::Backspace | ToolKey::Delete => {
|
||||
self.take_back_vertex();
|
||||
vec![]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// A dropped press (a second finger, a canceled touch) takes back only the vertex it set.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
if std::mem::take(&mut self.pressed_vertex) {
|
||||
self.take_back_vertex();
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
!self.vertices.is_empty() && matches!(key, ToolKey::Enter | ToolKey::Escape | ToolKey::Backspace | ToolKey::Delete)
|
||||
}
|
||||
|
||||
/// A loop being drawn: Escape drops it. Keys the tool does not claim run their commands.
|
||||
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
|
||||
!self.vertices.is_empty()
|
||||
}
|
||||
|
||||
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
self.clear();
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn hover_ended(&mut self, _cx: &ToolContext) {
|
||||
self.hover = None;
|
||||
}
|
||||
|
||||
fn options(&self) -> serde_json::Value {
|
||||
self.mesh.options()
|
||||
}
|
||||
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id));
|
||||
let mut line = self.vertices.clone();
|
||||
line.extend(self.hover.filter(|_| !self.vertices.is_empty()));
|
||||
if line.len() >= 2 {
|
||||
out.push(Overlay::Path { path: crate::xform::polygon(&line, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
|
||||
Cursor::Lasso
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,243 @@
|
||||
use super::*;
|
||||
use crate::testutil::*;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, Selection};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
fn click(tool: &mut dyn Tool, cx: &ToolContext, (x, y): (f64, f64), mods: Mods) -> Vec<Action> {
|
||||
let mut acts = tool.pointer(cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(mods));
|
||||
acts.extend(tool.pointer(cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(mods)));
|
||||
acts
|
||||
}
|
||||
|
||||
/// Clicks each vertex in turn with `first` held at the first click only.
|
||||
fn clicks(tool: &mut dyn Tool, cx: &ToolContext, vertices: &[(f64, f64)], first: Mods) {
|
||||
for (i, v) in vertices.iter().enumerate() {
|
||||
let acts = click(tool, cx, *v, if i == 0 { first } else { Mods::default() });
|
||||
assert!(acts.is_empty(), "a vertex click selects nothing: {acts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors each selected path has in a `select.anchorsMany` command, and its mode.
|
||||
fn selected(acts: &[Action]) -> (Vec<(u64, usize)>, String) {
|
||||
let [Action::Exec(c, v)] = acts else { panic!("one selection command: {acts:?}") };
|
||||
assert_eq!(c, "select.anchorsMany");
|
||||
let items = v["items"].as_array().unwrap();
|
||||
let ids = items.iter().map(|it| (it["id"].as_u64().unwrap(), it["anchors"].as_array().unwrap().len())).collect();
|
||||
(ids, v["mode"].as_str().unwrap().to_owned())
|
||||
}
|
||||
|
||||
/// A triangle around the rectangle's top left corner (100, 100) only.
|
||||
const CORNER: &[(f64, f64)] = &[(80.0, 80.0), (140.0, 80.0), (80.0, 140.0)];
|
||||
|
||||
#[test]
|
||||
fn a_double_click_enter_or_a_click_on_the_first_vertex_closes_the_loop() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
type Closing<'a> = &'a dyn Fn(&mut dyn Tool) -> Vec<Action>;
|
||||
let closings: [Closing; 3] = [
|
||||
&|t| {
|
||||
let mut acts = click(t, &cx, (80.0, 141.0), Mods::default());
|
||||
acts.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 141.0)));
|
||||
acts
|
||||
},
|
||||
&|t| t.key(&cx, ToolKey::Enter, Mods::default()),
|
||||
&|t| click(t, &cx, (82.0, 81.0), Mods::default()),
|
||||
];
|
||||
for (i, close) in closings.iter().enumerate() {
|
||||
let mut tool = crate::create(ID);
|
||||
assert_eq!(tool.id(), ID);
|
||||
clicks(tool.as_mut(), &cx, CORNER, Mods::default());
|
||||
assert!(tool.ends_on_escape(&cx) && tool.claims_key(&cx, ToolKey::Enter), "closing {i}");
|
||||
assert_eq!(selected(&close(tool.as_mut())), (vec![(id.0, 1)], "set".to_owned()), "closing {i}");
|
||||
assert!(!tool.ends_on_escape(&cx), "closing {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_at_a_new_point_sets_that_vertex_and_closes() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
|
||||
let mut acts = click(&mut tool, &cx, (80.0, 140.0), Mods::default());
|
||||
acts.extend(click(&mut tool, &cx, (80.0, 140.0), Mods::default()));
|
||||
assert!(acts.is_empty(), "{acts:?}");
|
||||
assert_eq!(tool.vertices.len(), 3, "the second click of the double-click sets no vertex");
|
||||
let acts = tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 140.0));
|
||||
assert_eq!(selected(&acts), (vec![(id.0, 1)], "set".to_owned()));
|
||||
assert!(!tool.ends_on_escape(&cx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_or_delete_removes_the_last_vertex() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
// (300, 300) would take in the corner at (200, 200) too.
|
||||
clicks(&mut tool, &cx, &[(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)], Mods::default());
|
||||
assert!(tool.claims_key(&cx, ToolKey::Backspace));
|
||||
assert!(tool.key(&cx, ToolKey::Backspace, Mods::default()).is_empty());
|
||||
assert_eq!(tool.vertices.len(), 2);
|
||||
// The preview runs along the two vertices left, not back to the removed one.
|
||||
let overlays = tool.overlays(&cx);
|
||||
let [Overlay::Path { path, .. }] = overlays.as_slice() else { panic!("one preview path") };
|
||||
assert_eq!(path.elements().len(), 2);
|
||||
clicks(&mut tool, &cx, &[(300.0, 300.0)], Mods::default());
|
||||
assert!(tool.claims_key(&cx, ToolKey::Delete));
|
||||
assert!(tool.key(&cx, ToolKey::Delete, Mods::default()).is_empty());
|
||||
assert_eq!(tool.vertices.len(), 2);
|
||||
clicks(&mut tool, &cx, &[(80.0, 140.0)], Mods::default());
|
||||
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(id.0, 1)], "set".to_owned()));
|
||||
assert!(!tool.claims_key(&cx, ToolKey::Delete), "with no loop open, Delete deletes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_drops_the_loop_and_leaves_the_selection() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, CORNER, Mods::default());
|
||||
assert!(tool.claims_key(&cx, ToolKey::Escape));
|
||||
assert!(tool.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
|
||||
assert!(!tool.ends_on_escape(&cx) && !tool.claims_key(&cx, ToolKey::Enter));
|
||||
assert!(tool.overlays(&cx).is_empty());
|
||||
assert!(tool.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
|
||||
assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 140.0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_keeps_the_segment_to_45_degree_steps() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &[(100.0, 100.0)], Mods::default());
|
||||
tool.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 110.0).with_mods(shift));
|
||||
let hover = tool.hover.unwrap();
|
||||
assert!((hover.y - 100.0).abs() < 1e-9 && hover.x > 199.0, "{hover:?}");
|
||||
assert_eq!(tool.overlays(&cx).len(), 1, "the segment follows the pointer");
|
||||
click(&mut tool, &cx, (190.0, 175.0), shift);
|
||||
let v = tool.vertices[1];
|
||||
assert!(((v.x - 100.0) - (v.y - 100.0)).abs() < 1e-9 && v.x > 150.0, "on the 45° line: {v:?}");
|
||||
tool.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 110.0));
|
||||
assert_eq!(tool.hover, Some(Point::new(200.0, 110.0)), "without Shift the segment goes to the pointer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_or_alt_at_the_first_click_adds_or_subtracts() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
for (first, mode) in [(shift, "add"), (alt, "subtract"), (Mods::default(), "set")] {
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, CORNER, first);
|
||||
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(id.0, 1)], mode.to_owned()));
|
||||
}
|
||||
// Shift held only at a later click constrains that segment and does not add.
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
|
||||
click(&mut tool, &cx, (80.0, 140.0), shift);
|
||||
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())).1, "set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_concave_loop_leaves_out_anchors_in_its_notch() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
// An L: the bottom left corner (100, 200) is in the notch.
|
||||
clicks(&mut tool, &cx, &[(60.0, 60.0), (240.0, 60.0), (240.0, 240.0), (160.0, 240.0), (160.0, 170.0), (60.0, 170.0)], Mods::default());
|
||||
let acts = tool.key(&cx, ToolKey::Enter, Mods::default());
|
||||
assert_eq!(selected(&acts), (vec![(id.0, 3)], "set".to_owned()));
|
||||
let Action::Exec(_, v) = &acts[0] else { panic!() };
|
||||
let picked: Vec<Value> = v["items"][0]["anchors"].as_array().unwrap().clone();
|
||||
// The rectangle's anchors run (100, 100), (200, 100), (200, 200), (100, 200).
|
||||
assert!(!picked.contains(&serde_json::json!([0, 3])), "{picked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fewer_than_three_vertices_select_nothing() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
|
||||
// A click on the first vertex of a two-vertex loop sets no vertex on top of it and closes nothing.
|
||||
assert!(click(&mut tool, &cx, (81.0, 80.0), Mods::default()).is_empty());
|
||||
assert_eq!(tool.vertices.len(), 2);
|
||||
assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 81.0, 80.0)).is_empty());
|
||||
assert!(!tool.ends_on_escape(&cx));
|
||||
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
|
||||
assert!(tool.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
|
||||
assert!(!tool.ends_on_escape(&cx));
|
||||
// A double-click on empty canvas: its second click sets no second vertex.
|
||||
assert!(click(&mut tool, &cx, (80.0, 80.0), Mods::default()).is_empty());
|
||||
assert!(click(&mut tool, &cx, (81.0, 80.0), Mods::default()).is_empty());
|
||||
assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 81.0, 80.0)).is_empty());
|
||||
assert!(!tool.ends_on_escape(&cx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_that_crosses_itself_selects_by_the_even_odd_rule() {
|
||||
// A small square in the middle of a five-pointed star, where the star's edges wind twice, and
|
||||
// one in the star's top point, where they wind once.
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let (middle, point) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(middle, shapes::rectangle(Rect::new(140.0, 140.0, 160.0, 160.0)), Appearance::default_art())).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(point, shapes::rectangle(Rect::new(148.0, 78.0, 152.0, 82.0)), Appearance::default_art())).unwrap();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let star: Vec<(f64, f64)> = (0..5)
|
||||
.map(|k| {
|
||||
let a = f64::from(-90 + 144 * k).to_radians();
|
||||
(150.0 + 100.0 * a.cos(), 150.0 + 100.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &star, Mods::default());
|
||||
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(point.0, 4)], "set".to_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_press_takes_back_only_its_vertex() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
|
||||
tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 140.0));
|
||||
assert!(tool.drop_press(&cx).is_empty());
|
||||
assert_eq!(tool.vertices, vec![Point::new(80.0, 80.0), Point::new(140.0, 80.0)]);
|
||||
assert_eq!(tool.hover, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_press_after_backspace_keeps_the_earlier_vertices() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut tool = PolygonalLassoTool::default();
|
||||
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
|
||||
tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 140.0));
|
||||
assert!(tool.key(&cx, ToolKey::Backspace, Mods::default()).is_empty());
|
||||
assert!(tool.drop_press(&cx).is_empty());
|
||||
assert_eq!(tool.vertices, vec![Point::new(80.0, 80.0), Point::new(140.0, 80.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tool_shows_the_lasso_cursor() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
assert_eq!(PolygonalLassoTool::default().cursor(&cx, Point::new(10.0, 10.0), Mods::default()), Cursor::Lasso);
|
||||
}
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user