mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 23:50:13 +00:00
Merge main into feat/transform-rect-ellipse-angle
This commit is contained in:
@@ -135,6 +135,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dash-exact.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dimension.svg` | Osama Amin | Original work, drawn for VectorCraft: a dimension line with arrowheads between two extension lines | MIT OR Apache-2.0 | |
|
||||
@@ -220,6 +221,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
Generated
+11
@@ -6700,6 +6700,16 @@ dependencies = [
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cdr"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"proptest",
|
||||
"vectorcraft-cdr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.24.1"
|
||||
@@ -6814,6 +6824,7 @@ dependencies = [
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-cad",
|
||||
"vectorcraft-cdr",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-eps",
|
||||
|
||||
@@ -77,6 +77,7 @@ vectorcraft-affinity = { path = "crates/affinity" }
|
||||
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
|
||||
vectorcraft-js = { path = "crates/js" }
|
||||
vectorcraft-apischema = { path = "crates/apischema" }
|
||||
vectorcraft-cdr = { path = "crates/cdr" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
|
||||
@@ -35,6 +35,11 @@ based in part on the work of the Independent JPEG Group.
|
||||
WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is
|
||||
under the Apache License 2.0 with the LLVM exception.
|
||||
|
||||
The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification
|
||||
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach
|
||||
Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part
|
||||
of either specification is copied into the crate; the license text is in crates/cdr/LICENSE-kaitai.txt.
|
||||
|
||||
Builds made with craft-fonts (the CRAFT_FONTS_DIR build option; all official releases) embed the
|
||||
fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic,
|
||||
Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest;
|
||||
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
|
||||
|
||||
@@ -140,8 +142,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
@@ -150,10 +154,12 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-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-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). 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-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19Q12 4 21 19"/><circle cx="12" cy="16.9" r="5.4"/><circle cx="12" cy="16.9" r="1" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 306 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 18 L9.5 18 A5.75 5.75 0 0 1 21 18"/><circle cx="3" cy="18" r="1.6" fill="currentColor"/><circle cx="9.5" cy="18" r="1.6" fill="currentColor"/><circle cx="21" cy="18" r="1.6" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 397 B |
@@ -12,13 +12,17 @@ fn luminance(c: &Color) -> f32 {
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
// Black ink alone is its own tint: its amount is the tint, not how light it displays (100% K
|
||||
// displays lighter than black).
|
||||
let light = match *c {
|
||||
/// How light `c` is for colorization, 0 black to 1 white. Black ink alone is its own tint: its
|
||||
/// amount is the tint, not how light it displays (100% K displays lighter than black).
|
||||
fn lightness(c: &Color) -> f32 {
|
||||
match *c {
|
||||
Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 => 1.0 - k,
|
||||
_ => luminance(c),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
let light = lightness(c);
|
||||
// A process or gray stroke color's tints and shades stay in its model.
|
||||
let (white, black) = match key {
|
||||
Color::Cmyk { .. } => (Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0)),
|
||||
@@ -47,45 +51,61 @@ fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
fn map_paint(p: &mut Paint, mode: Colorization, key: &Color) {
|
||||
/// The swatch a stroke paint links to and its tint, for colorization: Tints of a linked color are
|
||||
/// tints of its swatch (a spot color's tints print on its own plate).
|
||||
type Link<'a> = Option<(&'a str, f32)>;
|
||||
|
||||
fn map_paint(p: &mut Paint, mode: Colorization, key: &Color, link: Link<'_>) {
|
||||
if let Paint::Solid { color, .. } = p {
|
||||
*p = Paint::solid(map_color(color, mode, key));
|
||||
*p = match (mode, link) {
|
||||
(Colorization::Tints, Some((swatch, tint))) => {
|
||||
let t = (1.0 - lightness(color)).clamp(0.0, 1.0);
|
||||
Paint::Solid { color: key.tinted(t), swatch: Some(swatch.to_string()), tint: tint * t }
|
||||
}
|
||||
_ => Paint::solid(map_color(color, mode, key)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Recolour `n` (recursively) for a stroke painted `stroke`, and strip brushes from its strokes so
|
||||
/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Type is
|
||||
/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Under Tints,
|
||||
/// a stroke color linked to a swatch gives tints of that swatch, linked to it, as a spot color's
|
||||
/// tints are (the art's darkest parts the stroke's own tint, white none of it). Type is
|
||||
/// recolored like paths: its characters' solid fills and strokes as well as its own.
|
||||
pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
let key = match (mode, stroke.color()) {
|
||||
(Colorization::None, _) | (_, None) => None,
|
||||
(_, Some(c)) => Some(c),
|
||||
};
|
||||
fn walk(n: &mut Node, mode: Colorization, key: Option<Color>) {
|
||||
let link = match stroke {
|
||||
Paint::Solid { swatch: Some(s), tint, .. } => Some((s.as_str(), *tint)),
|
||||
_ => None,
|
||||
};
|
||||
fn walk(n: &mut Node, mode: Colorization, key: Option<Color>, link: Link<'_>) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(f) => {
|
||||
if let Some(k) = &key {
|
||||
map_paint(&mut f.paint, mode, k);
|
||||
map_paint(&mut f.paint, mode, k, link);
|
||||
}
|
||||
}
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.brush = None;
|
||||
if let Some(k) = &key {
|
||||
map_paint(&mut s.paint, mode, k);
|
||||
map_paint(&mut s.paint, mode, k, link);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(k), NodeKind::Text(t)) = (&key, &mut n.kind) {
|
||||
for r in &mut t.runs {
|
||||
map_paint(&mut r.style.fill, mode, k);
|
||||
map_paint(&mut r.style.stroke, mode, k);
|
||||
map_paint(&mut r.style.fill, mode, k, link);
|
||||
map_paint(&mut r.style.stroke, mode, k, link);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
walk(Arc::make_mut(c), mode, key);
|
||||
walk(Arc::make_mut(c), mode, key, link);
|
||||
}
|
||||
}
|
||||
// A mask's art is drawn too: a brush on its strokes would run this brush again. Its colours
|
||||
@@ -94,7 +114,7 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
strip_brushes(Arc::make_mut(&mut m.art));
|
||||
}
|
||||
}
|
||||
walk(n, mode, key);
|
||||
walk(n, mode, key, link);
|
||||
}
|
||||
|
||||
/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own
|
||||
|
||||
@@ -921,6 +921,47 @@ fn tints_colorization_uses_stroke_colour() {
|
||||
assert_eq!(white.appearance.fill_paint().color().unwrap().to_rgb(), [1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// Under Tints, a stroke color linked to a swatch gives tints of that swatch, linked to it: black
|
||||
/// art the stroke's own tint of it, 60% black ink 60% of that, white none; the colors shown are the
|
||||
/// same as for the unlinked color, a process or an RGB swatch. Tints and Shades stay unlinked.
|
||||
#[test]
|
||||
fn tints_of_a_swatch_stay_linked_to_it() {
|
||||
let spot = Color::cmyk(0.0, 0.5, 1.0, 0.0);
|
||||
let stroke = Paint::Solid { color: spot.tinted(0.8), swatch: Some("Brand orange".into()), tint: 0.8 };
|
||||
let mapped = |art: Color| {
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(art));
|
||||
colorize(&mut n, Colorization::Tints, &stroke);
|
||||
let mut plain = rect_art(1.0, 1.0);
|
||||
plain.appearance.set_fill(Paint::solid(art));
|
||||
colorize(&mut plain, Colorization::Tints, &Paint::solid(spot.tinted(0.8)));
|
||||
(n.appearance.fill_paint(), plain.appearance.fill_paint().color().unwrap())
|
||||
};
|
||||
for (art, want) in [(Color::cmyk(0.0, 0.0, 0.0, 1.0), 0.8), (Color::cmyk(0.0, 0.0, 0.0, 0.6), 0.48), (Color::cmyk(0.0, 0.0, 0.0, 0.0), 0.0)] {
|
||||
let (paint, shown) = mapped(art);
|
||||
let Paint::Solid { color, swatch: Some(s), tint } = paint else { panic!("linked: {paint:?}") };
|
||||
assert_eq!(s, "Brand orange");
|
||||
assert!((tint - want).abs() < 1e-5, "{art:?}: {tint}");
|
||||
let close = color.to_cmyk().iter().zip(shown.to_cmyk()).all(|(a, b)| (a - b).abs() < 1e-5);
|
||||
assert!(close, "{color:?} {shown:?}");
|
||||
}
|
||||
// An RGB swatch: its tints mix toward white, as the unlinked color's do.
|
||||
let rgb = Color::rgb(1.0, 0.4, 0.0);
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.5)));
|
||||
colorize(&mut n, Colorization::Tints, &Paint::Solid { color: rgb, swatch: Some("Brand red".into()), tint: 1.0 });
|
||||
let Paint::Solid { color, swatch: Some(s), tint } = n.appearance.fill_paint() else { panic!("linked") };
|
||||
assert_eq!(s, "Brand red");
|
||||
assert!((tint - 0.5).abs() < 1e-5, "{tint}");
|
||||
let [r, g, b] = color.to_rgb();
|
||||
assert!((r - 1.0).abs() < 1e-5 && (g - 0.7).abs() < 1e-5 && (b - 0.5).abs() < 1e-5, "{r} {g} {b}");
|
||||
// Tints and Shades darken past the swatch, which a tint can't: its pieces stay unlinked.
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
colorize(&mut n, Colorization::TintsAndShades, &stroke);
|
||||
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
|
||||
}
|
||||
|
||||
/// Black ink alone is a tint by its amount: a process black stroke leaves it as it is, and another
|
||||
/// process stroke color takes that share of its inks. Tints of a process color stay process.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "vectorcraft-cdr"
|
||||
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer.
|
||||
synth = []
|
||||
|
||||
[dependencies]
|
||||
crc32fast = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
vectorcraft-cdr = { path = ".", features = ["synth"] }
|
||||
@@ -0,0 +1,33 @@
|
||||
The record layouts this crate reads are described in the Kaitai Struct
|
||||
specification `coreldraw_cdr.ksy`
|
||||
(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit
|
||||
9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the
|
||||
license below. No part of that specification is copied into this crate;
|
||||
`PROVENANCE.md` cites it by line.
|
||||
|
||||
Some layouts are also taken from the fork of that specification by Zach Wolfe
|
||||
(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit
|
||||
2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same
|
||||
license and copyright notice.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Kaitai team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,127 @@
|
||||
# Where each layout comes from
|
||||
|
||||
The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and
|
||||
`tests/it/provenance.rs` fails when a cited id has no row here.
|
||||
|
||||
Sources:
|
||||
|
||||
- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`),
|
||||
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy
|
||||
- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same
|
||||
MIT license and notice as K (`LICENSE-kaitai.txt`),
|
||||
https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy
|
||||
- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at
|
||||
the same commit as K,
|
||||
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md
|
||||
and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk
|
||||
- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10,
|
||||
https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE),
|
||||
https://www.rfc-editor.org/rfc/rfc1951
|
||||
- **F**: the magic database of the `file` utility (BSD-2-Clause),
|
||||
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and
|
||||
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff
|
||||
- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0,
|
||||
https://pronom.nationalarchives.gov.uk/fmt/467.xml,
|
||||
https://pronom.nationalarchives.gov.uk/fmt/466.xml and
|
||||
https://pronom.nationalarchives.gov.uk/fmt/465.xml
|
||||
- **S**: own inspection of the bytes of public sample files, checked against the picture each file
|
||||
carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry
|
||||
none). The files come from:
|
||||
- **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name
|
||||
- **LT**: https://git.libreoffice.org/libcdr-test at commit
|
||||
`dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset/<version>/<file>`
|
||||
- **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision
|
||||
434, by file name
|
||||
- **TDF**: attachments to The Document Foundation's bug tracker,
|
||||
https://bugs.documentfoundation.org/attachment.cgi?id=<id>
|
||||
- **NR**: Natural Resources Canada's tactile maps,
|
||||
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and
|
||||
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr
|
||||
- **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name
|
||||
- **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The
|
||||
nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`,
|
||||
`gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture
|
||||
of their drawing.
|
||||
- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout
|
||||
"confirmed" when the program's authors found it in sample files,
|
||||
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md.
|
||||
The same program's `.cmx` reader at that commit,
|
||||
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs,
|
||||
was read for the order of fields that the notes do not spell out (the table entries, the rendering
|
||||
attributes and the curve body); no code was copied from it
|
||||
|
||||
Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks
|
||||
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
|
||||
listed so it can be checked against a file, with what the reader does when it is wrong).
|
||||
|
||||
Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as
|
||||
the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the
|
||||
sample files they name.
|
||||
The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample
|
||||
file is committed.
|
||||
|
||||
| Id | What the code relies on | Source | Status |
|
||||
|---|---|---|---|
|
||||
| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) |
|
||||
| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec |
|
||||
| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec |
|
||||
| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec |
|
||||
| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec |
|
||||
| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec |
|
||||
| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec |
|
||||
| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec |
|
||||
| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec |
|
||||
| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec |
|
||||
| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr<version>.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) |
|
||||
| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) |
|
||||
| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr<version>.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample |
|
||||
| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) |
|
||||
| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec |
|
||||
| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec |
|
||||
| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) |
|
||||
| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) |
|
||||
| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) |
|
||||
| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec |
|
||||
| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec |
|
||||
| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample |
|
||||
| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample |
|
||||
| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec |
|
||||
| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec |
|
||||
| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec |
|
||||
| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec |
|
||||
| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) |
|
||||
| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr<version>.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) |
|
||||
| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) |
|
||||
| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) |
|
||||
| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) |
|
||||
| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) |
|
||||
| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec |
|
||||
| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) |
|
||||
| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) |
|
||||
| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample |
|
||||
| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec |
|
||||
| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample |
|
||||
| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) |
|
||||
| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample |
|
||||
| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample |
|
||||
| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample |
|
||||
| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) |
|
||||
| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) |
|
||||
| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) |
|
||||
| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) |
|
||||
| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample |
|
||||
| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample |
|
||||
| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) |
|
||||
| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec |
|
||||
| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) |
|
||||
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
|
||||
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
|
||||
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
|
||||
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
|
||||
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
|
||||
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample |
|
||||
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
|
||||
| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) |
|
||||
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
|
||||
| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) |
|
||||
| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample |
|
||||
@@ -0,0 +1,98 @@
|
||||
# vectorcraft-cdr
|
||||
|
||||
A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates).
|
||||
It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its
|
||||
compressed lists, the ZIP packages that versions 14 and later save (with the data streams of
|
||||
versions 16 and later) and the records listed below, and hands the engine a drawing in points,
|
||||
with each object's transform. It does not write `.cdr` files.
|
||||
|
||||
## What is read
|
||||
|
||||
| In the `.cdr` file | Read as |
|
||||
|---|---|
|
||||
| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it |
|
||||
| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side |
|
||||
| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind |
|
||||
| The hidden and locked flags of layers, groups and objects | flags |
|
||||
| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle |
|
||||
| Groups (`LIST grp `) | groups |
|
||||
| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips |
|
||||
| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths |
|
||||
| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius |
|
||||
| Ellipses, arcs and pies | ellipses, and paths for arcs and pies |
|
||||
| Polygons and stars (a base side copied for each side) | paths |
|
||||
| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints |
|
||||
| The fill's winding flag | the nonzero fill rule, or even-odd |
|
||||
| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines |
|
||||
| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode |
|
||||
| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own |
|
||||
|
||||
Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain,
|
||||
pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform
|
||||
transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not
|
||||
read; the drawing's
|
||||
`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages
|
||||
that are encrypted, ZIP64 archives or split across files.
|
||||
|
||||
VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque,
|
||||
100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own
|
||||
readings: no public source states either direction.
|
||||
|
||||
## Versions 1 to 4
|
||||
|
||||
Public specifications cover only parts of these versions, such as the version 3 fill and page
|
||||
settings. For the rest, the reader follows the layouts of public sample files that
|
||||
`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that
|
||||
`src/synth.rs` builds from those rows.
|
||||
|
||||
| Version | Read | Left out or refused |
|
||||
|---|---|---|
|
||||
| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning |
|
||||
| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads |
|
||||
| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 |
|
||||
|
||||
A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of
|
||||
`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader
|
||||
reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names
|
||||
a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as
|
||||
not a `.cdr` drawing.
|
||||
|
||||
## `.cmx` files
|
||||
|
||||
`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same
|
||||
drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and
|
||||
arrowhead tables, then each page's instructions in drawing order:
|
||||
|
||||
| In the `.cmx` file | Read as |
|
||||
|---|---|
|
||||
| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them |
|
||||
| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out |
|
||||
| Groups | groups |
|
||||
| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths |
|
||||
| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors |
|
||||
| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines |
|
||||
|
||||
Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline
|
||||
arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping
|
||||
path is left out and the objects it clips are read without it. Files in big-endian byte order and
|
||||
files with 16-bit coordinates are refused.
|
||||
|
||||
## Provenance
|
||||
|
||||
`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status.
|
||||
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
|
||||
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
|
||||
`synth` feature); no third-party file is committed.
|
||||
|
||||
## Limits
|
||||
|
||||
`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the
|
||||
size of one package member, the number of members, the nesting depth, the chunk count, the
|
||||
objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an
|
||||
error or leaves the rest out with a warning; it does not recurse and does not panic. Each record
|
||||
of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3
|
||||
object are held to the arguments one record may have. A package's
|
||||
data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected
|
||||
list whose bytes overlap those of an earlier redirected list is left out with the damage warning.
|
||||
Other records may share bytes, and the bytes read again may add up to the member limit; past it
|
||||
the records are left out with the limit warning.
|
||||
@@ -0,0 +1,816 @@
|
||||
//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name
|
||||
//! (R19 to R23). Records are decoded only when an object refers to them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::bytes::Rd;
|
||||
use crate::geometry;
|
||||
use crate::inline;
|
||||
use crate::layout::{self, Profile};
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
|
||||
use crate::records::{self, Loda};
|
||||
use crate::riff::{Chunk, Index, push};
|
||||
use crate::styles::Styles;
|
||||
use crate::{Error, Warning};
|
||||
|
||||
/// Object types (R6).
|
||||
const RECTANGLE: u32 = 1;
|
||||
const ELLIPSE: u32 = 2;
|
||||
const CURVE: u32 = 3;
|
||||
const POLYGON: u32 = 0x14;
|
||||
const GUIDELINE: u32 = 0x16;
|
||||
const PATH: u32 = 0x25;
|
||||
/// Argument types (R6, R20, R21, R33, R52).
|
||||
const ARG_OUTLINE: u32 = 10;
|
||||
const ARG_FILL: u32 = 20;
|
||||
const ARG_COORDS: u32 = 30;
|
||||
const ARG_TRANSFORMS: u32 = 100;
|
||||
const ARG_STYLE: u32 = 200;
|
||||
const ARG_NAME: u32 = 1000;
|
||||
const ARG_LENS: u32 = 8000;
|
||||
const ARG_CONTAINER: u32 = 8005;
|
||||
const ARG_POLYGON: u32 = 11000;
|
||||
const ARG_WINDING: u32 = 14001;
|
||||
const ARG_GUIDE: u32 = 16000;
|
||||
const ARG_PAGE_SIZE: u32 = 19130;
|
||||
|
||||
/// What a RIFF file that names a version before 3 is refused as.
|
||||
const BEFORE_3: &str = "RIFF files of versions before 3";
|
||||
|
||||
/// What one read keeps while mapping.
|
||||
struct Ctx<'a, 'b> {
|
||||
ix: &'b Index<'a>,
|
||||
p: Profile,
|
||||
budget: &'b mut Budget,
|
||||
warn: &'b mut Vec<Warning>,
|
||||
/// Fill and outline records by id, decoded on first use.
|
||||
fill_chunks: HashMap<u32, &'b [u8]>,
|
||||
outline_chunks: HashMap<u32, &'b [u8]>,
|
||||
fills: HashMap<u32, Option<Color>>,
|
||||
outlines: HashMap<u32, Option<Outline>>,
|
||||
/// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't
|
||||
/// parse.
|
||||
styles: Result<Styles, ()>,
|
||||
/// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46).
|
||||
clips: HashMap<u32, &'b Chunk>,
|
||||
/// The clipped groups being read, innermost last.
|
||||
open_clips: Vec<u32>,
|
||||
/// Whether the walk of a clipped group stopped at the clipped chunk limit.
|
||||
clip_cut: bool,
|
||||
}
|
||||
|
||||
/// The most clipped groups read one inside another: VectorCraft's own limit.
|
||||
const MAX_CLIP_DEPTH: usize = 64;
|
||||
|
||||
pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Drawing, Error> {
|
||||
let root = ix.root().ok_or(Error::NotCdr)?;
|
||||
let version = ix.version();
|
||||
// A template whose `vrsn` chunk doesn't name a version read (R28).
|
||||
if version == 0 {
|
||||
return Err(Error::NotCdr);
|
||||
}
|
||||
// Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version
|
||||
// before 3.
|
||||
if version < layout::OLDEST_RIFF {
|
||||
return Err(Error::Unsupported(BEFORE_3));
|
||||
}
|
||||
let p = layout::for_version(version).ok_or(Error::Version(version))?;
|
||||
let mut found = Found::default();
|
||||
collect(ix, root, &mut found);
|
||||
let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p));
|
||||
// Before version 7 a `LIST stlt` holds chunks, not the style table (R4).
|
||||
let styles = match found.stlt {
|
||||
Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()),
|
||||
_ => Ok(Styles::default()),
|
||||
};
|
||||
let mut cx = Ctx {
|
||||
ix,
|
||||
p,
|
||||
budget,
|
||||
warn,
|
||||
fill_chunks: HashMap::new(),
|
||||
outline_chunks: HashMap::new(),
|
||||
fills: HashMap::new(),
|
||||
outlines: HashMap::new(),
|
||||
styles,
|
||||
clips: HashMap::new(),
|
||||
open_clips: Vec::new(),
|
||||
clip_cut: false,
|
||||
};
|
||||
// The `spnd` id is a u16 in files of 16-bit fields (R46).
|
||||
let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() };
|
||||
for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) {
|
||||
if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) {
|
||||
cx.clips.entry(id).or_insert(g);
|
||||
}
|
||||
}
|
||||
for c in &found.fills {
|
||||
if let Some(id) = Rd::new(ix.data(c)).u32() {
|
||||
cx.fill_chunks.entry(id).or_insert(ix.data(c));
|
||||
}
|
||||
}
|
||||
for c in &found.outlines {
|
||||
if let Some(id) = Rd::new(ix.data(c)).u32() {
|
||||
cx.outline_chunks.entry(id).or_insert(ix.data(c));
|
||||
}
|
||||
}
|
||||
let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default();
|
||||
let mut pages = Vec::new();
|
||||
let mut master = Vec::new();
|
||||
for page in &found.pages {
|
||||
let (is_master, read) = cx.page(page);
|
||||
if is_master {
|
||||
// Guidelines on any of the master page's layers show on every page.
|
||||
for mut layer in read.layers {
|
||||
guides.append(&mut layer.guides);
|
||||
if !layer.objects.is_empty() && layer.kind != LayerKind::Grid {
|
||||
master.push(layer);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pages.push(read);
|
||||
}
|
||||
}
|
||||
// A file of only a master page keeps it as its page.
|
||||
if pages.is_empty() && !master.is_empty() {
|
||||
pages.push(Page { size: None, layers: std::mem::take(&mut master) });
|
||||
}
|
||||
Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) })
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Found<'i> {
|
||||
fills: Vec<&'i Chunk>,
|
||||
outlines: Vec<&'i Chunk>,
|
||||
mcfg: Option<&'i Chunk>,
|
||||
guid: Option<&'i Chunk>,
|
||||
stlt: Option<&'i Chunk>,
|
||||
clpt: Vec<&'i Chunk>,
|
||||
pages: Vec<&'i Chunk>,
|
||||
}
|
||||
|
||||
/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and
|
||||
/// `LIST stlt`; pages are not looked into.
|
||||
fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) {
|
||||
let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect();
|
||||
while let Some(c) = stack.pop() {
|
||||
match &c.id {
|
||||
b"fild" | b"fill" => found.fills.push(c),
|
||||
b"outl" => found.outlines.push(c),
|
||||
b"mcfg" => found.mcfg = found.mcfg.or(Some(c)),
|
||||
b"guid" => found.guid = found.guid.or(Some(c)),
|
||||
// Before version 7 the list holds chunks, which are looked through.
|
||||
_ if c.is_list(b"stlt") => {
|
||||
found.stlt = found.stlt.or(Some(c));
|
||||
stack.extend(ix.children(c).iter().rev());
|
||||
}
|
||||
_ if c.is_list(b"clpt") => found.clpt.push(c),
|
||||
_ if c.is_list(b"page") => found.pages.push(c),
|
||||
_ => stack.extend(ix.children(c).iter().rev()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after
|
||||
/// 2 bytes (R38).
|
||||
fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> {
|
||||
let mut r = Rd::at(b, p.mcfg_skip);
|
||||
if p.mcfg_corners {
|
||||
r.skip(2)?;
|
||||
let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?);
|
||||
return sane_size(x1 - x0, y1 - y0);
|
||||
}
|
||||
sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?)
|
||||
}
|
||||
|
||||
fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> {
|
||||
let (w, h) = (w.abs(), h.abs());
|
||||
(w > 0.0 && h > 0.0).then_some((w, h))
|
||||
}
|
||||
|
||||
/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000.
|
||||
/// Each guideline counts toward the objects a read maps; past them the rest are left out.
|
||||
fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Vec<Guideline> {
|
||||
let mut r = Rd::new(b);
|
||||
let Some(n) = r.u32() else { return Vec::new() };
|
||||
let _again = r.u32();
|
||||
let fits = r.left() / 40;
|
||||
if n as usize > fits {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let n = (n as usize).min(fits);
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
if !budget.take_object() {
|
||||
push(warn, Warning::TooDeep);
|
||||
break;
|
||||
}
|
||||
out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point.
|
||||
fn guideline(b: &[u8], p: &Profile) -> Option<Guideline> {
|
||||
if p.short {
|
||||
return None;
|
||||
}
|
||||
let mut r = Rd::at(b, 12);
|
||||
let angle = f64::from(r.i32()?) / 1_000_000.0;
|
||||
let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? };
|
||||
Some(Guideline { at, angle, hidden: false })
|
||||
}
|
||||
|
||||
/// Marks the guidelines from `from` on hidden when `flags` hide what holds them.
|
||||
fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) {
|
||||
if flags.hidden {
|
||||
for g in guides.iter_mut().skip(from) {
|
||||
g.hidden = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A list's flags (R19): four bytes.
|
||||
fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> {
|
||||
let c = ix.children(list).iter().find(|c| &c.id == b"flgs")?;
|
||||
ix.data(c).get(..4)?.try_into().ok()
|
||||
}
|
||||
|
||||
/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of
|
||||
/// byte 0) (R19).
|
||||
fn state(ix: &Index, list: &Chunk) -> Flags {
|
||||
flags(ix, list).map_or(Flags::default(), |[b0, b1, _, _]| Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 })
|
||||
}
|
||||
|
||||
/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's.
|
||||
fn inherit(o: &mut Object, f: Flags) {
|
||||
let own = match o {
|
||||
Object::Shape(s) => &mut s.flags,
|
||||
Object::Group { flags, .. } => flags,
|
||||
Object::Clip { container, .. } => &mut container.flags,
|
||||
};
|
||||
own.hidden |= f.hidden;
|
||||
own.locked |= f.locked;
|
||||
}
|
||||
|
||||
/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a
|
||||
/// drawing layer. Version 3 counts its types from 0, one less (R32).
|
||||
fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind {
|
||||
match kind.saturating_add(u32::from(types_from_zero)) {
|
||||
11 => LayerKind::Grid,
|
||||
12 => LayerKind::Guides,
|
||||
17 => LayerKind::Desktop,
|
||||
_ => LayerKind::Drawing,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a layer's flags make it, for a layer without an object type of its own (R19). The low
|
||||
/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13
|
||||
/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear.
|
||||
/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10
|
||||
/// alone does not make a grid.
|
||||
fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind {
|
||||
let [b0, b1, b2, _] = f;
|
||||
let grid_bit = b0 & 0x10 != 0;
|
||||
match b0 & 0x0f {
|
||||
0x0a if grid_bit => LayerKind::Grid,
|
||||
0x0a => LayerKind::Guides,
|
||||
0x02 if version_below_14 && grid_bit => LayerKind::Grid,
|
||||
0x02 if version_below_14 => LayerKind::Guides,
|
||||
0x08 if b2 != 0 => LayerKind::Desktop,
|
||||
0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop,
|
||||
_ => LayerKind::Drawing,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own
|
||||
/// chunks, or in its `lgob` list and the `trfl` list there (R22).
|
||||
fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> {
|
||||
let mut stack: Vec<(&Chunk, u8)> = ix.children(list).iter().rev().map(|c| (c, 0)).collect();
|
||||
while let Some((c, depth)) = stack.pop() {
|
||||
if ids.contains(&&c.id) {
|
||||
return Some(c);
|
||||
}
|
||||
if depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) {
|
||||
stack.extend(ix.children(c).iter().rev().map(|k| (k, depth + 1)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `loda` (or `lobj`) a page, layer or object keeps for itself.
|
||||
fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> {
|
||||
own_chunk(ix, list, &[b"loda", b"lobj"])
|
||||
}
|
||||
|
||||
/// A page's layer lists in file order: its own, and those in the lists it holds, such as the
|
||||
/// `gobj` list of files of versions 7 to 13 (R22).
|
||||
fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect();
|
||||
while let Some(c) = stack.pop() {
|
||||
if c.is_list(b"layr") {
|
||||
out.push(c);
|
||||
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
|
||||
stack.extend(ix.children(c).iter().rev());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far.
|
||||
struct Frame<'i> {
|
||||
chunks: &'i [Chunk],
|
||||
next: usize,
|
||||
objects: Vec<Object>,
|
||||
/// Whether its objects form a group in the frame below.
|
||||
group: bool,
|
||||
/// The group's own flags.
|
||||
flags: Flags,
|
||||
/// The first of the guidelines read inside it.
|
||||
guides_from: usize,
|
||||
/// What places its objects after their own transforms: the matrices of the version 3 groups
|
||||
/// around them (R33). The identity in other versions, whose objects hold their whole transform.
|
||||
outer: Matrix,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Ctx<'a, 'b> {
|
||||
/// A page: whether it is the master page, and its layers.
|
||||
fn page(&mut self, page: &Chunk) -> (bool, Page) {
|
||||
let ix = self.ix;
|
||||
let is_master = flags(ix, page).is_some_and(|f| f[2] != 0);
|
||||
let size = own_loda(ix, page)
|
||||
.and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn))
|
||||
.and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b)));
|
||||
let mut layers = Vec::new();
|
||||
for l in page_layers(ix, page) {
|
||||
let layer = self.layer(l);
|
||||
let empty = layer.objects.is_empty() && layer.guides.is_empty();
|
||||
// The entries that stand for the master page's layers hold nothing of the page's own.
|
||||
if empty && (is_master || layer.kind != LayerKind::Drawing) {
|
||||
continue;
|
||||
}
|
||||
layers.push(layer);
|
||||
}
|
||||
(is_master, Page { size, layers })
|
||||
}
|
||||
|
||||
fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut r = Rd::new(b);
|
||||
sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?)
|
||||
}
|
||||
|
||||
fn layer(&mut self, list: &Chunk) -> Layer {
|
||||
let ix = self.ix;
|
||||
let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn));
|
||||
// The layer's own object type says what it is; its flags, only when it has none (R19).
|
||||
let kind = match &loda {
|
||||
Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero),
|
||||
None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)),
|
||||
};
|
||||
let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default();
|
||||
let mut guides = Vec::new();
|
||||
let objects = self.objects(ix.children(list), &mut guides);
|
||||
let flags = state(ix, list);
|
||||
hide_guides(&mut guides, 0, flags);
|
||||
Layer { name, kind, flags, objects, guides }
|
||||
}
|
||||
|
||||
/// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`.
|
||||
fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec<Guideline>) -> Vec<Object> {
|
||||
let ix = self.ix;
|
||||
let mut stack = vec![Frame {
|
||||
chunks,
|
||||
next: 0,
|
||||
objects: Vec::new(),
|
||||
group: false,
|
||||
flags: Flags::default(),
|
||||
guides_from: guides.len(),
|
||||
outer: Matrix::IDENTITY,
|
||||
}];
|
||||
loop {
|
||||
let Some(top) = stack.last_mut() else { return Vec::new() };
|
||||
let (here, outer) = (top.chunks, top.outer);
|
||||
let Some(c) = here.get(top.next) else {
|
||||
let Some(done) = stack.pop() else { return Vec::new() };
|
||||
// A hidden group hides the guidelines inside it.
|
||||
hide_guides(guides, done.guides_from, done.flags);
|
||||
match stack.last_mut() {
|
||||
// A group counts toward the objects a read maps; past them its objects stay,
|
||||
// ungrouped, with the group's flags.
|
||||
Some(parent) if done.group && !done.objects.is_empty() => {
|
||||
if self.budget.take_object() {
|
||||
parent.objects.push(Object::Group { objects: done.objects, flags: done.flags });
|
||||
} else {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
let mut objects = done.objects;
|
||||
for o in &mut objects {
|
||||
inherit(o, done.flags);
|
||||
}
|
||||
parent.objects.extend(objects);
|
||||
}
|
||||
}
|
||||
Some(parent) if !done.group => parent.objects.extend(done.objects),
|
||||
Some(_) => {}
|
||||
None => return done.objects,
|
||||
}
|
||||
continue;
|
||||
};
|
||||
top.next += 1;
|
||||
// Every chunk of a clipped group counts, empty groups included, each time a container
|
||||
// names the group; past the limit the group is left out.
|
||||
if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
self.clip_cut = true;
|
||||
return Vec::new();
|
||||
}
|
||||
if c.is_list(b"obj ") {
|
||||
if let Some(o) = self.object(c, guides, &outer) {
|
||||
top.objects.push(o);
|
||||
}
|
||||
} else if c.is_list(b"grp ") {
|
||||
let own = self.group_placement(c);
|
||||
let flags = state(ix, c);
|
||||
let guides_from = guides.len();
|
||||
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) });
|
||||
} else if c.is_list(b"lnkg") {
|
||||
// Linked groups (brush strokes, blends, contours) place their objects with a
|
||||
// matrix of their own, which this reader doesn't apply: they are left out.
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
|
||||
// Other lists under a layer are looked through (R22).
|
||||
let guides_from = guides.len();
|
||||
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The matrix a group places its objects with. Only a version 3 group has one, in the
|
||||
/// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the
|
||||
/// group's objects stay where their own transforms put them.
|
||||
fn group_placement(&mut self, list: &Chunk) -> Matrix {
|
||||
if !self.p.inline_styles {
|
||||
return Matrix::IDENTITY;
|
||||
}
|
||||
let ix = self.ix;
|
||||
let Some(arg) =
|
||||
own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS))
|
||||
else {
|
||||
return Matrix::IDENTITY;
|
||||
};
|
||||
self.placement(arg)
|
||||
}
|
||||
|
||||
/// The matrices of a transforms argument (R33). An envelope among them is not applied: the
|
||||
/// shapes keep their outlines, placed by the matrices alone, with the envelopes warning.
|
||||
fn placement(&mut self, arg: &[u8]) -> Matrix {
|
||||
match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) {
|
||||
Some(t) => {
|
||||
if t.envelope {
|
||||
push(self.warn, Warning::Envelopes);
|
||||
}
|
||||
t.matrix
|
||||
}
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
Matrix::IDENTITY
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a
|
||||
/// guideline goes to `guides`).
|
||||
fn object(&mut self, list: &Chunk, guides: &mut Vec<Guideline>, outer: &Matrix) -> Option<Object> {
|
||||
let ix = self.ix;
|
||||
let Some(loda) = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
};
|
||||
// Guidelines count toward the objects a read maps.
|
||||
if !self.budget.take_object() {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
let flags = state(ix, list);
|
||||
if loda.kind == GUIDELINE {
|
||||
guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g }));
|
||||
return None;
|
||||
}
|
||||
if self.p.inline_styles {
|
||||
return self.inline_object(&loda, outer, flags);
|
||||
}
|
||||
let geometry = self.geometry(&loda)?;
|
||||
// A uniform transparency from version 13 applies (R47); a lens, and a transparency of
|
||||
// another kind or version, is not applied: the shape shows opaque.
|
||||
let (opacity, blend) = match loda.arg(ARG_LENS) {
|
||||
None => (1.0, Blend::Normal),
|
||||
Some(b) => match records::transparency(b).filter(|_| self.p.tagged) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
push(self.warn, Warning::Lenses);
|
||||
(1.0, Blend::Normal)
|
||||
}
|
||||
},
|
||||
};
|
||||
let nonzero = self.nonzero(&loda);
|
||||
// A transform that is there but can't be read is damage; the shape stays where it is.
|
||||
let matrix = match own_chunk(ix, list, &[b"trfd"]) {
|
||||
None => Matrix::IDENTITY,
|
||||
Some(c) => records::trfd(ix.data(c), &self.p).unwrap_or_else(|| {
|
||||
push(self.warn, Warning::Damaged);
|
||||
Matrix::IDENTITY
|
||||
}),
|
||||
};
|
||||
// Without a fill or outline argument of its own, an object takes its style's (R45). The
|
||||
// style id is a u16 in files of 16-bit fields.
|
||||
let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) });
|
||||
let fill_id = match loda.arg(ARG_FILL) {
|
||||
Some(b) => self.id(b),
|
||||
None => style.and_then(|s| self.style_entry(s, Styles::fill)),
|
||||
};
|
||||
let outline_id = match loda.arg(ARG_OUTLINE) {
|
||||
Some(b) => self.id(b),
|
||||
None => style.and_then(|s| self.style_entry(s, Styles::outline)),
|
||||
};
|
||||
let fill = fill_id.and_then(|id| self.fill(id));
|
||||
let outline = outline_id.and_then(|id| self.outline(id));
|
||||
let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags });
|
||||
// A container clips the group its argument 8005 names (R46).
|
||||
Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) {
|
||||
Some(id) => self.clip(shape, id, guides),
|
||||
None => Object::Shape(shape),
|
||||
})
|
||||
}
|
||||
|
||||
/// `container` and the objects of the clipped group `id`, which keep their own transforms.
|
||||
/// A group that isn't there is damage; one already being read, past the depth limit or past
|
||||
/// the chunks clipped groups may walk is left out with the limit warning, the guidelines it
|
||||
/// holds included. Either way the container stays, as a plain shape.
|
||||
fn clip(&mut self, container: Box<Shape>, id: u32, guides: &mut Vec<Guideline>) -> Object {
|
||||
let Some(&group) = self.clips.get(&id) else {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return Object::Shape(container);
|
||||
};
|
||||
if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
return Object::Shape(container);
|
||||
}
|
||||
self.open_clips.push(id);
|
||||
let (ix, mark) = (self.ix, guides.len());
|
||||
let objects = self.objects(ix.children(group), guides);
|
||||
self.open_clips.pop();
|
||||
if std::mem::take(&mut self.clip_cut) {
|
||||
guides.truncate(mark);
|
||||
return Object::Shape(container);
|
||||
}
|
||||
// The clipped group's own flags hide or lock the objects it holds; it and the container
|
||||
// hide its guidelines.
|
||||
let flags = state(ix, group);
|
||||
hide_guides(guides, mark, flags);
|
||||
hide_guides(guides, mark, container.flags);
|
||||
if objects.is_empty() {
|
||||
return Object::Shape(container);
|
||||
}
|
||||
let mut objects = objects;
|
||||
for o in &mut objects {
|
||||
inherit(o, flags);
|
||||
}
|
||||
Object::Clip { container, objects }
|
||||
}
|
||||
|
||||
/// The record id that argument `b` names; an argument too short for one is damage.
|
||||
fn id(&mut self, b: &[u8]) -> Option<u32> {
|
||||
let id = id_of(b);
|
||||
if id.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// A u16 id at the start of argument `b`; an argument too short for one is damage.
|
||||
fn short_id(&mut self, b: &[u8]) -> Option<u32> {
|
||||
let id = Rd::new(b).u16().map(u32::from);
|
||||
if id.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the
|
||||
/// argument the fill is even-odd; an argument without its byte is damage.
|
||||
fn nonzero(&mut self, loda: &Loda) -> bool {
|
||||
let Some(b) = loda.arg(ARG_WINDING) else { return false };
|
||||
match b.first() {
|
||||
Some(v) => *v != 0,
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill or outline record that style `id` names; a style table that doesn't parse is
|
||||
/// damage, and the object is drawn without it.
|
||||
fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option<u32>) -> Option<u32> {
|
||||
match &self.styles {
|
||||
Ok(s) => entry(s, id),
|
||||
Err(()) => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A version 3 object, whose transforms, fill and outline are arguments of its own record
|
||||
/// (R33, R34, R35). A fill or an outline that is there but can't be read is damage.
|
||||
fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option<Object> {
|
||||
let own = match loda.arg(ARG_TRANSFORMS) {
|
||||
None => Matrix::IDENTITY,
|
||||
Some(arg) => self.placement(arg),
|
||||
};
|
||||
let geometry = self.geometry(loda)?;
|
||||
let fill = loda.arg(ARG_FILL).and_then(|b| {
|
||||
let read = inline::fill(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.flatten()
|
||||
});
|
||||
let outline = loda.arg(ARG_OUTLINE).and_then(|b| {
|
||||
let read = inline::outline(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.flatten()
|
||||
});
|
||||
// Past the dashes a read takes, the outline is solid.
|
||||
let outline = outline.map(|mut o| {
|
||||
if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) {
|
||||
o.dashes = Vec::new();
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
o
|
||||
});
|
||||
let nonzero = self.nonzero(loda);
|
||||
let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) };
|
||||
Some(Object::Shape(Box::new(shape)))
|
||||
}
|
||||
|
||||
fn geometry(&mut self, loda: &Loda) -> Option<Geometry> {
|
||||
let coords = loda.arg(ARG_COORDS);
|
||||
// Version 3 counts the first object types from 0, one below the later numbers (R32).
|
||||
let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind };
|
||||
// A shape without its coordinates, or a polygon without its sides, is damage like a shape
|
||||
// whose coordinates can't be read; one left out at the coordinate limit is not.
|
||||
self.budget.coordinates_refused();
|
||||
let g = match kind {
|
||||
RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)),
|
||||
ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)),
|
||||
CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path),
|
||||
PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path),
|
||||
POLYGON => match loda.arg(ARG_POLYGON) {
|
||||
Some(sides) => coords
|
||||
.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn))
|
||||
.and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)),
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if g.is_none() && !self.budget.coordinates_refused() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
fn fill(&mut self, id: u32) -> Option<Color> {
|
||||
if let Some(f) = self.fills.get(&id) {
|
||||
return f.clone();
|
||||
}
|
||||
// A record that is missing or can't be read is damage, and the shape is drawn without a
|
||||
// fill; id 0 without a record is no fill.
|
||||
if id != 0 && !self.fill_chunks.contains_key(&id) {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
let read = self.fill_chunks.get(&id).and_then(|b| {
|
||||
let read = records::fill(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.and_then(|(_, c)| c)
|
||||
});
|
||||
self.fills.insert(id, read.clone());
|
||||
read
|
||||
}
|
||||
|
||||
/// The outline of record `id`. Its dashes count toward the read's dashes for every shape that
|
||||
/// uses it; past them the shape's outline is solid.
|
||||
fn outline(&mut self, id: u32) -> Option<Outline> {
|
||||
if !self.outlines.contains_key(&id) {
|
||||
// A record that is missing is damage, as one that can't be read is; id 0 without a
|
||||
// record is no outline.
|
||||
if id != 0 && !self.outline_chunks.contains_key(&id) {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
let read = self.outline_chunks.get(&id).and_then(|b| {
|
||||
let read = records::outline(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.and_then(|(_, o)| o)
|
||||
});
|
||||
// An outline with more dashes than the read may still take is kept solid.
|
||||
let read = read.map(|mut o| {
|
||||
if o.dashes.len() > self.budget.dashes_left() {
|
||||
o.dashes = Vec::new();
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
o
|
||||
});
|
||||
self.outlines.insert(id, read);
|
||||
}
|
||||
let o = self.outlines.get_mut(&id)?.as_mut()?;
|
||||
// The dashes left only shrink, so an outline refused once is refused for every later
|
||||
// shape: its dashes are dropped from the cache, and later shapes take it solid.
|
||||
if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) {
|
||||
o.dashes = Vec::new();
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
Some(o.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill or outline argument: the record id (R20).
|
||||
fn id_of(b: &[u8]) -> Option<u32> {
|
||||
Rd::new(b).u32()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layer_flags_name_the_kinds() {
|
||||
assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing);
|
||||
assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides);
|
||||
assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides);
|
||||
assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid);
|
||||
assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid);
|
||||
// From version 14 the master page flags its layers by byte 0 alone.
|
||||
assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides);
|
||||
assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid);
|
||||
assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing);
|
||||
assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing);
|
||||
// Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample
|
||||
// files flag them, and desktop and guides layers with bit 0x40 or 0x10 set.
|
||||
for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] {
|
||||
assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}");
|
||||
assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}");
|
||||
}
|
||||
assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides);
|
||||
}
|
||||
|
||||
/// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes
|
||||
/// that use it later copy none.
|
||||
#[test]
|
||||
fn an_outline_past_the_dash_limit_keeps_no_dashes() {
|
||||
let v = crate::synth::V(1100);
|
||||
let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 };
|
||||
let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]);
|
||||
let file = crate::synth::riff(1100, &[]);
|
||||
let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() });
|
||||
let mut warn = Vec::new();
|
||||
let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap();
|
||||
let mut cx = Ctx {
|
||||
ix: &ix,
|
||||
p: layout::for_version(1100).unwrap(),
|
||||
budget: &mut budget,
|
||||
warn: &mut warn,
|
||||
fill_chunks: HashMap::new(),
|
||||
outline_chunks: HashMap::from([(1, record.as_slice())]),
|
||||
fills: HashMap::new(),
|
||||
outlines: HashMap::new(),
|
||||
styles: Ok(Styles::default()),
|
||||
clips: HashMap::new(),
|
||||
open_clips: Vec::new(),
|
||||
clip_cut: false,
|
||||
};
|
||||
assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3));
|
||||
for _ in 0..3 {
|
||||
assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0));
|
||||
assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0));
|
||||
}
|
||||
assert_eq!(*cx.warn, vec![Warning::TooDeep]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Little-endian reads that fail instead of panicking.
|
||||
|
||||
/// A cursor over one record's bytes. Every read returns `None` past the end.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Rd<'a> {
|
||||
b: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Rd<'a> {
|
||||
pub(crate) fn new(b: &'a [u8]) -> Self {
|
||||
Rd { b, pos: 0 }
|
||||
}
|
||||
|
||||
pub(crate) fn at(b: &'a [u8], pos: usize) -> Self {
|
||||
Rd { b, pos }
|
||||
}
|
||||
|
||||
pub(crate) fn pos(&self) -> usize {
|
||||
self.pos
|
||||
}
|
||||
|
||||
pub(crate) fn left(&self) -> usize {
|
||||
self.b.len().saturating_sub(self.pos)
|
||||
}
|
||||
|
||||
pub(crate) fn skip(&mut self, n: usize) -> Option<()> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
(end <= self.b.len()).then(|| self.pos = end)
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
let s = self.b.get(self.pos..end)?;
|
||||
self.pos = end;
|
||||
Some(s)
|
||||
}
|
||||
|
||||
fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
self.bytes(N)?.try_into().ok()
|
||||
}
|
||||
|
||||
pub(crate) fn u8(&mut self) -> Option<u8> {
|
||||
Some(self.array::<1>()?[0])
|
||||
}
|
||||
|
||||
pub(crate) fn u16(&mut self) -> Option<u16> {
|
||||
self.array().map(u16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn i16(&mut self) -> Option<i16> {
|
||||
self.array().map(i16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn u32(&mut self) -> Option<u32> {
|
||||
self.array().map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn i32(&mut self) -> Option<i32> {
|
||||
self.array().map(i32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// A finite f64; NaN and the infinities read as `None`.
|
||||
pub(crate) fn f64(&mut self) -> Option<f64> {
|
||||
self.array().map(f64::from_le_bytes).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> {
|
||||
self.array()
|
||||
}
|
||||
}
|
||||
|
||||
/// The u32 at `pos` of `b`.
|
||||
pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option<u32> {
|
||||
Rd::at(b, pos).u32()
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its
|
||||
//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the
|
||||
//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills
|
||||
//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses
|
||||
//! are left out with a warning.
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::geometry::path_of;
|
||||
use crate::layout::{self, Profile};
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
|
||||
use crate::records::{name, property_color};
|
||||
use crate::riff::{LIST, push};
|
||||
use crate::{Error, Warning};
|
||||
|
||||
const FORM: [u8; 4] = *b"CMX1";
|
||||
/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample
|
||||
/// file with 32-bit coordinates (R54).
|
||||
const DEFAULT_UNIT: f64 = 1e-7;
|
||||
/// How far past a chunk that runs short the next chunk id is looked for (R53).
|
||||
const RESYNC: usize = 64;
|
||||
/// The chunks the reader uses (R53 to R60).
|
||||
const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"];
|
||||
/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them.
|
||||
const MAX_NAME_UNITS: usize = 4096;
|
||||
|
||||
// Instruction codes (R60).
|
||||
const BEGIN_PAGE: i16 = 9;
|
||||
const END_PAGE: i16 = 10;
|
||||
const BEGIN_LAYER: i16 = 11;
|
||||
const END_LAYER: i16 = 12;
|
||||
const BEGIN_GROUP: i16 = 13;
|
||||
const END_GROUP: i16 = 14;
|
||||
const BEGIN_TEXT: i16 = 20;
|
||||
const END_TEXT: i16 = 21;
|
||||
const GLYPH_RUN: i16 = 65;
|
||||
const ELLIPSE: i16 = 66;
|
||||
const CURVE: i16 = 67;
|
||||
const RECTANGLE: i16 = 68;
|
||||
const IMAGE: i16 = 69;
|
||||
const ADD_CLIP: i16 = 88;
|
||||
const REMOVE_CLIP: i16 = 89;
|
||||
const JUMP: i16 = 111;
|
||||
|
||||
/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)?
|
||||
pub(crate) fn is_cmx(bytes: &[u8]) -> bool {
|
||||
matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice())
|
||||
}
|
||||
|
||||
/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file.
|
||||
struct Chunk<'a> {
|
||||
id: [u8; 4],
|
||||
body: &'a [u8],
|
||||
start: usize,
|
||||
}
|
||||
|
||||
/// The tables that page instructions refer to by 1-based index (R55 to R59).
|
||||
#[derive(Default)]
|
||||
struct Tables {
|
||||
colors: Vec<Option<Color>>,
|
||||
/// Outline widths in points.
|
||||
pens: Vec<Option<f64>>,
|
||||
/// Flags, and the caps and join.
|
||||
line_types: Vec<Option<(u8, u8)>>,
|
||||
dashes: Vec<Vec<u16>>,
|
||||
/// Line type, screen, color, arrowheads, pen and dashes.
|
||||
outlines: Vec<Option<[u16; 6]>>,
|
||||
arrowheads: Vec<(u16, u16)>,
|
||||
}
|
||||
|
||||
pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
|
||||
if !is_cmx(bytes) {
|
||||
return Err(Error::NotCmx);
|
||||
}
|
||||
if bytes.get(0..4) == Some(b"RIFX") {
|
||||
return Err(Error::Unsupported("big-endian CMX files"));
|
||||
}
|
||||
let mut warn = Vec::new();
|
||||
let chunks = chunks(bytes, budget, &mut warn)?;
|
||||
let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
|
||||
match cont.get(52) {
|
||||
Some(b'4') => {}
|
||||
Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")),
|
||||
_ => return Err(Error::Damaged("CMX header")),
|
||||
}
|
||||
let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT);
|
||||
let unit = meters / 0.0254 * 72.0;
|
||||
let tables = Tables::read(&chunks, unit, budget, &mut warn)?;
|
||||
let mut pages = Vec::new();
|
||||
for c in chunks.iter().filter(|c| c.id == *b"page") {
|
||||
pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?);
|
||||
}
|
||||
Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
|
||||
}
|
||||
|
||||
/// The chunks of the file in order, those inside `LIST` chunks in place (R53).
|
||||
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Vec<Chunk<'a>>, Error> {
|
||||
let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len());
|
||||
if declared > b.len() {
|
||||
// The file was cut short of the size its header gives.
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let end = declared.min(b.len());
|
||||
let mut out = Vec::new();
|
||||
// (position, end, depth) of the lists still to walk; a list's children go before the rest of
|
||||
// the list that holds it.
|
||||
let mut stack = vec![(12usize, end, 0usize)];
|
||||
while let Some((mut pos, end, depth)) = stack.pop() {
|
||||
while pos.saturating_add(8) <= end {
|
||||
let Some(id) = Rd::at(b, pos).fourcc() else { break };
|
||||
if !is_id(&id) {
|
||||
match resync(b, pos, end) {
|
||||
Some(next) => {
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
None => {
|
||||
push(warn, Warning::Damaged);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
budget.take_chunk()?;
|
||||
let size = u32_at(b, pos + 4).map_or(0, |s| s as usize);
|
||||
let start = pos + 8;
|
||||
let stop = start.saturating_add(size);
|
||||
if stop > end {
|
||||
// Stray bytes that happen to start with four letters give a length past the list:
|
||||
// look for the next chunk id after them. A chunk the reader uses is kept, cut at
|
||||
// the end of the list.
|
||||
if !READ_IDS.contains(&id)
|
||||
&& let Some(next) = resync(b, pos, end)
|
||||
{
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let stop = stop.min(end);
|
||||
let next = stop.saturating_add(size & 1);
|
||||
if id == LIST {
|
||||
if depth >= budget.limits.depth {
|
||||
push(warn, Warning::TooDeep);
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
stack.push((next, end, depth));
|
||||
stack.push((start + 4, stop, depth + 1));
|
||||
break;
|
||||
}
|
||||
if let Some(body) = b.get(start..stop) {
|
||||
out.push(Chunk { id, body, start });
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)?
|
||||
fn is_id(t: &[u8]) -> bool {
|
||||
matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' '))
|
||||
}
|
||||
|
||||
/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`]
|
||||
/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list
|
||||
/// that ends at `end` (R53).
|
||||
fn resync(b: &[u8], pos: usize, end: usize) -> Option<usize> {
|
||||
let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end);
|
||||
let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p)));
|
||||
(pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p))
|
||||
}
|
||||
|
||||
/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs
|
||||
/// past it (R55).
|
||||
fn list_end(b: &[u8], mut pos: usize) -> usize {
|
||||
while let Some(&tag) = b.get(pos) {
|
||||
if tag == 0xff {
|
||||
return pos + 1;
|
||||
}
|
||||
match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) {
|
||||
Some(n) if pos + n <= b.len() => pos += n,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// The data of field `tag` in the field list `b` (R55).
|
||||
fn field(b: &[u8], tag: u8) -> Option<&[u8]> {
|
||||
let mut pos = 0;
|
||||
while let Some(&t) = b.get(pos) {
|
||||
if t == 0xff {
|
||||
return None;
|
||||
}
|
||||
let n = usize::from(Rd::at(b, pos + 1).u16()?);
|
||||
let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?;
|
||||
if t == tag {
|
||||
return Some(data);
|
||||
}
|
||||
pos += n;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward
|
||||
/// the chunk limit.
|
||||
fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result<Vec<&'a [u8]>, Error> {
|
||||
let count = Rd::new(d).u16().map_or(0, usize::from);
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 2;
|
||||
for _ in 0..count {
|
||||
if pos >= d.len() {
|
||||
break;
|
||||
}
|
||||
budget.take_chunk()?;
|
||||
let end = list_end(d, pos);
|
||||
out.push(d.get(pos..end).unwrap_or_default());
|
||||
pos = end;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Tables {
|
||||
/// The first chunk of each table; a table that is missing is empty.
|
||||
fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Tables, Error> {
|
||||
let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body);
|
||||
// A color record of field 10 holds a property list as a `.cdr` fill does (R56).
|
||||
let record = layout::for_version(1300);
|
||||
let mut t = Tables::default();
|
||||
for e in entries(first(b"rclr"), budget)? {
|
||||
t.colors.push(color(e, record.as_ref(), warn));
|
||||
}
|
||||
for e in entries(first(b"rpen"), budget)? {
|
||||
t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit));
|
||||
}
|
||||
for e in entries(first(b"rott"), budget)? {
|
||||
t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0)))));
|
||||
}
|
||||
for e in entries(first(b"rdot"), budget)? {
|
||||
let mut r = Rd::new(field(e, 1).unwrap_or_default());
|
||||
let n = r.u16().map_or(0, usize::from);
|
||||
t.dashes.push((0..n).map_while(|_| r.u16()).collect());
|
||||
}
|
||||
for e in entries(first(b"rotl"), budget)? {
|
||||
t.outlines.push(field(e, 1).and_then(|f| {
|
||||
let mut r = Rd::new(f);
|
||||
Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?])
|
||||
}));
|
||||
}
|
||||
// Arrowhead pairs are plain u16 pairs after the count, not field lists (R59).
|
||||
let mut r = Rd::new(first(b"rota"));
|
||||
let n = r.u16().map_or(0, usize::from);
|
||||
for _ in 0..n {
|
||||
let Some(pair) = r.u16().zip(r.u16()) else { break };
|
||||
budget.take_chunk()?;
|
||||
t.arrowheads.push(pair);
|
||||
}
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
/// Entry `index` (1-based) of `list`, or `None` with a warning when there is none.
|
||||
fn get<T: Clone>(list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
|
||||
let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten();
|
||||
if found.is_none() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn color(&self, index: u16, warn: &mut Vec<Warning>) -> Color {
|
||||
Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
|
||||
}
|
||||
|
||||
/// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58).
|
||||
fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Outline> {
|
||||
let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?;
|
||||
let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0));
|
||||
if flags & 1 != 0 {
|
||||
return None;
|
||||
}
|
||||
let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0);
|
||||
let mut dashes = Vec::new();
|
||||
if flags & 4 != 0 {
|
||||
let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i));
|
||||
match stored {
|
||||
// A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48).
|
||||
Some(d) if d.iter().all(|x| *x == 0) => {}
|
||||
Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(),
|
||||
Some(_) => push(warn, Warning::TooDeep),
|
||||
None => push(warn, Warning::Damaged),
|
||||
}
|
||||
}
|
||||
if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) {
|
||||
push(warn, Warning::Arrowheads);
|
||||
}
|
||||
Some(Outline {
|
||||
width,
|
||||
color: self.color(color, warn),
|
||||
cap: match caps_join & 0x0f {
|
||||
1 => Cap::Round,
|
||||
2 => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
},
|
||||
join: match caps_join >> 4 {
|
||||
1 => Join::Round,
|
||||
2 => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
},
|
||||
dashes,
|
||||
behind_fill: flags & 8 != 0,
|
||||
scale_with: flags & 16 != 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A color entry (R56): the property list of field 10 when there is one, else the model and
|
||||
/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a
|
||||
/// warning.
|
||||
fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec<Warning>) -> Option<Color> {
|
||||
if let (Some(f), Some(p)) = (field(e, 10), record) {
|
||||
let mut r = Rd::new(f);
|
||||
let len = r.u32()? as usize;
|
||||
return property_color(r.bytes(len.min(r.left()))?, p, warn);
|
||||
}
|
||||
let model = *field(e, 1)?.first()?;
|
||||
let v = field(e, 2)?;
|
||||
let byte = |i: usize| v.get(i).map(|b| f32::from(*b));
|
||||
let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0));
|
||||
let full = |i: usize| byte(i).map(|x| x / 255.0);
|
||||
Some(match model {
|
||||
2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]),
|
||||
3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]),
|
||||
4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]),
|
||||
5 => Color::Rgb([full(0)?, full(1)?, full(2)?]),
|
||||
9 => Color::Gray(1.0 - full(0)?),
|
||||
_ => {
|
||||
push(warn, Warning::UnknownColors);
|
||||
Color::Rgb([0.0; 3])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects of one layer while it is read: the layer's own list, then one list for each group
|
||||
/// left open.
|
||||
struct LayerRead {
|
||||
name: String,
|
||||
lists: Vec<Vec<Object>>,
|
||||
}
|
||||
|
||||
impl LayerRead {
|
||||
/// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds
|
||||
/// them front to back.
|
||||
fn finish(mut self) -> Layer {
|
||||
while self.lists.len() > 1 {
|
||||
close_group(&mut self.lists);
|
||||
}
|
||||
let mut objects = self.lists.pop().unwrap_or_default();
|
||||
objects.reverse();
|
||||
Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the innermost open group of `lists` into the one that holds it.
|
||||
fn close_group(lists: &mut Vec<Vec<Object>>) {
|
||||
if lists.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut objects = lists.pop().unwrap_or_default();
|
||||
objects.reverse();
|
||||
if let Some(top) = lists.last_mut() {
|
||||
top.push(Object::Group { objects, flags: Default::default() });
|
||||
}
|
||||
}
|
||||
|
||||
/// The reading of one page chunk.
|
||||
struct PageRead<'t, 'b> {
|
||||
tables: &'t Tables,
|
||||
unit: f64,
|
||||
budget: &'b mut Budget,
|
||||
warn: &'b mut Vec<Warning>,
|
||||
size: Option<(f64, f64)>,
|
||||
/// The page's center in the file's coordinates when the page takes its size from the
|
||||
/// drawing's bounds; points are moved by it so the art lies on the page.
|
||||
center: (f64, f64),
|
||||
layers: Vec<Layer>,
|
||||
open: Option<LayerRead>,
|
||||
/// Groups nested past the depth limit that are still open; their content is left out.
|
||||
skipped: usize,
|
||||
}
|
||||
|
||||
impl<'t, 'b> PageRead<'t, 'b> {
|
||||
fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec<Warning>) -> Self {
|
||||
PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 }
|
||||
}
|
||||
|
||||
/// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code,
|
||||
/// or 0xFFFF, a u32 size and the code; then the code's field lists (R60).
|
||||
fn read(mut self, c: &Chunk) -> Result<Page, Error> {
|
||||
let d = c.body;
|
||||
let mut pos = 0usize;
|
||||
while pos.saturating_add(4) <= d.len() {
|
||||
self.budget.take_chunk()?;
|
||||
let mut r = Rd::at(d, pos);
|
||||
let (size, code, head) = match r.u16() {
|
||||
Some(0xFFFF) => match (r.u32(), r.i16()) {
|
||||
(Some(size), Some(code)) => (size as usize, code, 8),
|
||||
_ => break,
|
||||
},
|
||||
Some(size) => match r.i16() {
|
||||
Some(code) => (usize::from(size), code, 4),
|
||||
None => break,
|
||||
},
|
||||
None => break,
|
||||
};
|
||||
if size < head {
|
||||
push(self.warn, Warning::Damaged);
|
||||
break;
|
||||
}
|
||||
let end = pos.saturating_add(size);
|
||||
if end > d.len() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
let body = d.get(pos + head..end.min(d.len())).unwrap_or_default();
|
||||
if code == JUMP {
|
||||
// Field 1 is the file offset the instructions go on from; the bytes passed over
|
||||
// hold the page's images (R60).
|
||||
let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start));
|
||||
pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end);
|
||||
if pos > end {
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.instruction(code, body);
|
||||
pos = end;
|
||||
}
|
||||
if pos < d.len() {
|
||||
// An instruction whose head runs past the page was not read.
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
self.close_layer();
|
||||
// A layer that holds nothing (the special layers every sample file lists empty) is left
|
||||
// out. The file lists layers back to front.
|
||||
let mut layers = self.layers;
|
||||
layers.retain(|l| !l.objects.is_empty());
|
||||
layers.reverse();
|
||||
Ok(Page { size: self.size, layers })
|
||||
}
|
||||
|
||||
fn instruction(&mut self, code: i16, body: &[u8]) {
|
||||
match code {
|
||||
BEGIN_PAGE => {
|
||||
// Field 4: the page's width and height (R61).
|
||||
let mut r = Rd::new(field(body, 4).unwrap_or_default());
|
||||
if let (Some(w), Some(h)) = (r.u32(), r.u32()) {
|
||||
let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit);
|
||||
self.size = (w > 0.0 && h > 0.0).then_some((w, h));
|
||||
}
|
||||
if self.size.is_none() {
|
||||
self.size_from_bounds(field(body, 1).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
BEGIN_LAYER => {
|
||||
self.close_layer();
|
||||
// A layer without a name is left unnamed, as in a `.cdr` drawing.
|
||||
let name = self.layer_name(body).unwrap_or_default();
|
||||
self.open = Some(LayerRead { name, lists: vec![Vec::new()] });
|
||||
}
|
||||
END_LAYER => self.close_layer(),
|
||||
BEGIN_GROUP => {
|
||||
let open = self.layer().lists.len();
|
||||
if self.skipped > 0 || open > self.budget.limits.depth {
|
||||
self.skipped += 1;
|
||||
push(self.warn, Warning::TooDeep);
|
||||
} else if self.budget.take_object() {
|
||||
self.layer().lists.push(Vec::new());
|
||||
} else {
|
||||
// Past the object limit the group's content joins the group that holds it.
|
||||
self.skipped += 1;
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
END_GROUP => {
|
||||
if self.skipped > 0 {
|
||||
self.skipped -= 1;
|
||||
} else {
|
||||
close_group(&mut self.layer().lists);
|
||||
}
|
||||
}
|
||||
CURVE if self.skipped == 0 => {
|
||||
if let Some(shape) = self.curve(body) {
|
||||
if self.budget.take_object() {
|
||||
if let Some(list) = self.layer().lists.last_mut() {
|
||||
list.push(Object::Shape(Box::new(shape)));
|
||||
}
|
||||
} else {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
}
|
||||
BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects),
|
||||
// These and the other codes (text styles and characters, color contexts) draw nothing
|
||||
// on their own.
|
||||
END_PAGE | END_TEXT | REMOVE_CLIP => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16
|
||||
/// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in
|
||||
/// coordinate units. The page is centered on those bounds.
|
||||
fn size_from_bounds(&mut self, f: &[u8]) {
|
||||
let mut r = Rd::new(f);
|
||||
if r.u16().is_none() || r.u32().is_none() {
|
||||
return;
|
||||
}
|
||||
let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else {
|
||||
return;
|
||||
};
|
||||
let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit);
|
||||
let (w, h) = ((rt - l).abs(), (t - b).abs());
|
||||
if w > 0.0 && h > 0.0 {
|
||||
self.size = Some((w, h));
|
||||
self.center = ((l + rt) / 2.0, (t + b) / 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The open layer, or a new unnamed one when objects come before any layer begins.
|
||||
fn layer(&mut self) -> &mut LayerRead {
|
||||
self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] })
|
||||
}
|
||||
|
||||
fn close_layer(&mut self) {
|
||||
self.skipped = 0;
|
||||
if let Some(l) = self.open.take() {
|
||||
self.layers.push(l.finish());
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a
|
||||
/// u16 count and 8-bit characters (R62).
|
||||
fn layer_name(&mut self, body: &[u8]) -> Option<String> {
|
||||
// A field 4 that can't be read leaves the name to field 1.
|
||||
let wide = field(body, 4).and_then(|f| {
|
||||
let mut r = Rd::new(f);
|
||||
let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2);
|
||||
Some((r.bytes(n * 2)?, layout::for_version(1200)?))
|
||||
});
|
||||
if let Some((units, l)) = wide {
|
||||
let s = name(units, &l, self.warn);
|
||||
if !s.trim().is_empty() {
|
||||
return Some(s);
|
||||
}
|
||||
}
|
||||
let mut r = Rd::at(field(body, 1)?, 12);
|
||||
let n = usize::from(r.u16()?).min(r.left());
|
||||
let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn);
|
||||
(!s.trim().is_empty()).then_some(s)
|
||||
}
|
||||
|
||||
/// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32
|
||||
/// x and y) and one type byte for each. Points are from the page's center, y up.
|
||||
fn curve(&mut self, body: &[u8]) -> Option<Shape> {
|
||||
let mut r = Rd::new(field(body, 2).unwrap_or_default());
|
||||
let Some(count) = r.u16().map(usize::from) else {
|
||||
// A curve without its points is lost.
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
};
|
||||
// `stored` points are read, so the type bytes are found after all of them, and the first
|
||||
// `n`, those that have a type byte, are kept. When the field holds every point, a short
|
||||
// field has lost type bytes. When it holds whole points and their types for fewer points,
|
||||
// the count is too large. Otherwise the field lost points, and its type bytes can't be
|
||||
// found: the curve is lost.
|
||||
let left = r.left();
|
||||
let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) {
|
||||
Some(c) => (count, count.min(left - c)),
|
||||
None if left.is_multiple_of(9) => (left / 9, left / 9),
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if n < count {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
if !self.budget.take_coordinates(stored) {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(stored);
|
||||
for _ in 0..stored {
|
||||
let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit);
|
||||
points.push(Pt { x: x - self.center.0, y: y - self.center.1 });
|
||||
}
|
||||
points.truncate(n);
|
||||
let path = path_of(&points, r.bytes(n)?);
|
||||
if path.subpaths.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default());
|
||||
Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline))
|
||||
}
|
||||
|
||||
/// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the
|
||||
/// fill and one for the outline when the mask names them.
|
||||
fn attributes(&mut self, a: &[u8]) -> (Option<Color>, Option<Outline>) {
|
||||
let Some(&mask) = a.first() else { return (None, None) };
|
||||
let mut pos = 1;
|
||||
let mut fill = None;
|
||||
if mask & 1 != 0 {
|
||||
let end = list_end(a, pos);
|
||||
let list = a.get(pos..end).unwrap_or_default();
|
||||
pos = end;
|
||||
// Field 1: the fill type (u16), then its own field list; type 1, uniform, names its
|
||||
// color in field 1.
|
||||
let v = field(list, 1).unwrap_or_default();
|
||||
match Rd::new(v).u16() {
|
||||
Some(0) | None => {}
|
||||
Some(1) => {
|
||||
let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16());
|
||||
fill = Some(match index {
|
||||
Some(i) => self.tables.color(i, self.warn),
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
Color::Rgb([0.0; 3])
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(_) => push(self.warn, Warning::UnsupportedFills),
|
||||
}
|
||||
}
|
||||
let mut outline = None;
|
||||
if mask & 2 != 0 {
|
||||
let list = a.get(pos..list_end(a, pos)).unwrap_or_default();
|
||||
match field(list, 1).and_then(|f| Rd::new(f).u16()) {
|
||||
Some(i) => outline = self.tables.outline(i, self.budget, self.warn),
|
||||
None => push(self.warn, Warning::Damaged),
|
||||
}
|
||||
}
|
||||
if mask & 4 != 0 {
|
||||
push(self.warn, Warning::Lenses);
|
||||
}
|
||||
// A canvas (8) or a container (16) is not read.
|
||||
if mask & (8 | 16) != 0 {
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
}
|
||||
(fill, outline)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles
|
||||
//! (R15), ellipses and arcs (R17) and polygons (R18).
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use crate::Warning;
|
||||
use crate::bytes::Rd;
|
||||
use crate::layout::Profile;
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Geometry, Path, Pt, Segment, SubPath};
|
||||
use crate::records::{angle, coord};
|
||||
use crate::riff::push;
|
||||
|
||||
/// The most sides a polygon record may give (VectorCraft's own bound).
|
||||
const MAX_POLYGON_SIDES: u32 = 1000;
|
||||
/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points.
|
||||
const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0;
|
||||
|
||||
/// What a point type byte asks for (R16): bits 7 and 6.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Op {
|
||||
Move,
|
||||
Line,
|
||||
Curve,
|
||||
Control,
|
||||
}
|
||||
|
||||
fn op(t: u8) -> Op {
|
||||
match t >> 6 {
|
||||
0 => Op::Move,
|
||||
1 => Op::Line,
|
||||
2 => Op::Curve,
|
||||
_ => Op::Control,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bit 3 closes the subpath (R16).
|
||||
const CLOSES: u8 = 0x08;
|
||||
|
||||
/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from
|
||||
/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold;
|
||||
/// `None` when the points are past the budget.
|
||||
pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
|
||||
let mut r = Rd::new(b);
|
||||
let count = if p.short {
|
||||
let count = usize::from(r.u16()?);
|
||||
r.skip(2)?;
|
||||
count
|
||||
} else {
|
||||
r.u32()? as usize
|
||||
};
|
||||
points(b, r, count, p, budget, warn)
|
||||
}
|
||||
|
||||
/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16
|
||||
/// bytes, then the points and their type bytes as in a point list.
|
||||
pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
|
||||
let mut r = Rd::new(b);
|
||||
r.skip(4)?;
|
||||
let count = usize::from(r.u16()?) + usize::from(r.u16()?);
|
||||
r.skip(16)?;
|
||||
points(b, r, count, p, budget, warn)
|
||||
}
|
||||
|
||||
/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as
|
||||
/// all `count` points with the type bytes after them, and as the points and type bytes the bytes
|
||||
/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie.
|
||||
fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
|
||||
let each = 2 * p.word();
|
||||
let left = r.left();
|
||||
let split = (left / (each + 1)).min(count);
|
||||
let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count));
|
||||
let stored = match whole {
|
||||
Some(typed) if typed >= split => count,
|
||||
_ => split,
|
||||
};
|
||||
let types = b.get(r.pos() + stored * each..)?;
|
||||
let n = stored.min(types.len());
|
||||
if count > n {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
if !budget.take_coordinates(n) {
|
||||
push(warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? });
|
||||
}
|
||||
Some(path_of(&points, types))
|
||||
}
|
||||
|
||||
/// The subpaths that points and their type bytes draw.
|
||||
pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path {
|
||||
let mut subpaths = Vec::new();
|
||||
let mut cur: Option<SubPath> = None;
|
||||
// The last two control points: a curve end uses only those.
|
||||
let mut controls: Vec<Pt> = Vec::with_capacity(2);
|
||||
for (&pt, &t) in points.iter().zip(types) {
|
||||
let o = op(t);
|
||||
if o == Op::Control {
|
||||
if controls.len() == 2 {
|
||||
controls.remove(0);
|
||||
}
|
||||
controls.push(pt);
|
||||
continue;
|
||||
}
|
||||
if o == Op::Move || cur.is_none() {
|
||||
subpaths.extend(cur.take());
|
||||
cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move });
|
||||
controls.clear();
|
||||
if o == Op::Move {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Some(sp) = cur.as_mut() else { continue };
|
||||
let seg = match (o, controls.as_slice()) {
|
||||
(Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt),
|
||||
_ => Segment::Line(pt),
|
||||
};
|
||||
controls.clear();
|
||||
sp.segments.push(seg);
|
||||
if t & CLOSES != 0 {
|
||||
sp.closed = true;
|
||||
}
|
||||
}
|
||||
subpaths.extend(cur);
|
||||
// A closed subpath with no segments, or an open one with none, draws nothing.
|
||||
subpaths.retain(|s| !s.segments.is_empty());
|
||||
Path { subpaths }
|
||||
}
|
||||
|
||||
/// A rectangle record (R15): width, height, then one corner radius for every corner, four from
|
||||
/// version 9.
|
||||
pub(crate) fn rect(b: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
if p.f64_rect {
|
||||
return rect_f64(b, p);
|
||||
}
|
||||
let mut r = Rd::new(b);
|
||||
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let first = coord(&mut r, p)?.abs();
|
||||
let mut radii = [first; 4];
|
||||
if p.four_radii {
|
||||
for slot in radii.iter_mut().skip(1) {
|
||||
*slot = coord(&mut r, p)?.abs();
|
||||
}
|
||||
}
|
||||
Some(Geometry::Rect { w, h, radii })
|
||||
}
|
||||
|
||||
/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale
|
||||
/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the
|
||||
/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter
|
||||
/// side; with it set the radius is in inches. A corner is held to half the shorter side, and
|
||||
/// sizes to the range of the 32-bit coordinates of earlier versions.
|
||||
fn rect_f64(b: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
let mut r = Rd::new(b);
|
||||
let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit());
|
||||
let (w, h) = (size(r.f64()?)?, size(r.f64()?)?);
|
||||
r.skip(8 + 8)?;
|
||||
let inches = r.u8()? != 0;
|
||||
r.skip(7)?;
|
||||
let short = w.abs().min(h.abs());
|
||||
let mut radii = [0.0; 4];
|
||||
for (k, slot) in radii.iter_mut().enumerate() {
|
||||
if k > 0 {
|
||||
r.skip(16)?;
|
||||
}
|
||||
let v = r.f64()?.abs();
|
||||
let radius = if inches { v * 72.0 } else { v * short / 2.0 };
|
||||
*slot = radius.min(short / 2.0);
|
||||
}
|
||||
Some(Geometry::Rect { w, h, radii })
|
||||
}
|
||||
|
||||
/// An ellipse record (R17): the box's width and height, the start and end angles and whether
|
||||
/// the arc closes through the centre. Equal angles make a whole ellipse.
|
||||
pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
let mut r = Rd::new(b);
|
||||
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?);
|
||||
let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 };
|
||||
let sweep = (a2 - a1).rem_euclid(360.0);
|
||||
if sweep.abs() < 1e-9 {
|
||||
return Some(Geometry::Ellipse { w, h });
|
||||
}
|
||||
Some(Geometry::Path(arc(w, h, a1, sweep, pie)))
|
||||
}
|
||||
|
||||
/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through
|
||||
/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The
|
||||
/// radii are half the size, and a negative width or height points its axis the other way (R17), so
|
||||
/// with a negative height 0 to 180 degrees is the half below the centre.
|
||||
fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path {
|
||||
let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0);
|
||||
let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() };
|
||||
let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() };
|
||||
let pieces = (sweep / 90.0).ceil().max(1.0) as usize;
|
||||
let step = sweep.to_radians() / pieces as f64;
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let t0 = start.to_radians();
|
||||
let mut segments = Vec::with_capacity(pieces + 2);
|
||||
if pie {
|
||||
segments.push(Segment::Line(at(t0)));
|
||||
}
|
||||
for i in 0..pieces {
|
||||
let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64);
|
||||
let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b));
|
||||
segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1));
|
||||
}
|
||||
let start = if pie { Pt { x: cx, y: cy } } else { at(t0) };
|
||||
Path { subpaths: vec![SubPath { start, segments, closed: pie }] }
|
||||
}
|
||||
|
||||
/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top
|
||||
/// vertex first, copied once per side and turned clockwise each time by the vertices the side
|
||||
/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives.
|
||||
/// A star whose sides skip vertices draws as one outline, or as several when the side count and
|
||||
/// the step share a factor.
|
||||
pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Geometry> {
|
||||
let mut r = Rd::new(b);
|
||||
if !p.tagged {
|
||||
r.skip(4)?;
|
||||
}
|
||||
let sides = r.u32()?;
|
||||
// The next point: the first field, or the second when the first is 0 or 1.
|
||||
let (first, second) = (r.u32()?, r.u32()?);
|
||||
let next = if first > 1 { first } else { second };
|
||||
if p.tagged {
|
||||
r.skip(4)?;
|
||||
}
|
||||
let (rx, ry) = (r.f64()?, r.f64()?);
|
||||
let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let side = base.subpaths.first()?;
|
||||
if !(1..=MAX_POLYGON_SIDES).contains(&sides) {
|
||||
push(warn, Warning::Damaged);
|
||||
return None;
|
||||
}
|
||||
if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) {
|
||||
push(warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
// The base curve's own unit radius, measured from its first point, keeps the scale right
|
||||
// whatever unit the file's coordinates are in.
|
||||
let unit = side.start.x.hypot(side.start.y);
|
||||
let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS };
|
||||
let place = |q: Pt, turn: f64| {
|
||||
let (s, c) = turn.sin_cos();
|
||||
let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c);
|
||||
Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy }
|
||||
};
|
||||
let step = side_step(side, sides, next);
|
||||
let outlines = gcd(sides, step);
|
||||
let each = sides / outlines;
|
||||
let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides);
|
||||
let mut subpaths = Vec::with_capacity(outlines as usize);
|
||||
for o in 0..outlines {
|
||||
let mut segments = Vec::with_capacity(side.segments.len() * each as usize);
|
||||
for j in 0..each {
|
||||
let turn = angle(o + j * step);
|
||||
segments.extend(side.segments.iter().map(|s| match *s {
|
||||
Segment::Line(a) => Segment::Line(place(a, turn)),
|
||||
Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)),
|
||||
}));
|
||||
}
|
||||
subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true });
|
||||
}
|
||||
Some(Geometry::Path(Path { subpaths }))
|
||||
}
|
||||
|
||||
/// How many vertices the base side moves on from its first point (R18): the vertex its last
|
||||
/// point lies at, clockwise; else the next-point field when it names one; else 1.
|
||||
fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 {
|
||||
let field = if (1..sides).contains(&next) { next } else { 1 };
|
||||
let Some(end) = side.segments.last().map(|s| match *s {
|
||||
Segment::Line(e) | Segment::Cubic(_, _, e) => e,
|
||||
}) else {
|
||||
return field;
|
||||
};
|
||||
let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y));
|
||||
if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) {
|
||||
return field;
|
||||
}
|
||||
let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides));
|
||||
let k = turned.round();
|
||||
if !k.is_finite() || (turned - k).abs() > 1e-3 {
|
||||
return field;
|
||||
}
|
||||
match k.rem_euclid(f64::from(sides)) as u32 {
|
||||
0 => field,
|
||||
k => k,
|
||||
}
|
||||
}
|
||||
|
||||
fn gcd(a: u32, b: u32) -> u32 {
|
||||
let (mut a, mut b) = (a, b);
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a.max(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pt(x: f64, y: f64) -> Pt {
|
||||
Pt { x, y }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_bytes_make_moves_lines_curves_and_closes() {
|
||||
let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)];
|
||||
// move (closed), line, control, control, curve end closing; move, line.
|
||||
let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40];
|
||||
let path = path_of(&points, &types);
|
||||
assert_eq!(path.subpaths.len(), 2);
|
||||
let first = &path.subpaths[0];
|
||||
assert!(first.closed);
|
||||
assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]);
|
||||
assert!(!path.subpaths[1].closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() {
|
||||
let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile"));
|
||||
// Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only.
|
||||
let mut b = 3u32.to_le_bytes().to_vec();
|
||||
for v in [0i32, 0, 254_000, 0, 0, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
b.extend([0x00, 0x40]);
|
||||
let mut warn = vec![];
|
||||
let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path"));
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]);
|
||||
assert_eq!(warn, vec![Warning::Damaged]);
|
||||
// A count past the points the bytes hold keeps the points that have a type byte.
|
||||
// Eight points and their eight type bytes take the bytes of nine points.
|
||||
let mut b = 9u32.to_le_bytes().to_vec();
|
||||
for i in 0..8 {
|
||||
b.extend((i * 254_000i32).to_le_bytes());
|
||||
b.extend(0i32.to_le_bytes());
|
||||
}
|
||||
b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]);
|
||||
let mut warn = vec![];
|
||||
let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path"));
|
||||
assert_eq!(path.subpaths[0].segments.len(), 7);
|
||||
assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0));
|
||||
assert_eq!(warn, vec![Warning::Damaged]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_control_points_keeps_the_last_two() {
|
||||
let points: Vec<Pt> = (0..7).map(|i| pt(f64::from(i), 0.0)).collect();
|
||||
let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]);
|
||||
assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_end_without_two_controls_is_a_line() {
|
||||
let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]);
|
||||
assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_arc_ends_on_the_ellipse() {
|
||||
let p = arc(20.0, 10.0, 0.0, 90.0, false);
|
||||
let sp = &p.subpaths[0];
|
||||
assert_eq!(sp.start, pt(20.0, 5.0));
|
||||
let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") };
|
||||
assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9);
|
||||
let pie = arc(20.0, 10.0, 0.0, 180.0, true);
|
||||
assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_height_turns_the_arc_below_the_centre() {
|
||||
let p = arc(20.0, -10.0, 0.0, 180.0, false);
|
||||
let sp = &p.subpaths[0];
|
||||
assert_eq!(sp.start, pt(20.0, -5.0));
|
||||
let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") };
|
||||
assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}");
|
||||
}
|
||||
|
||||
/// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the
|
||||
/// origin.
|
||||
fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
for v in [sides, first, second, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
b.extend(1.0f64.to_le_bytes());
|
||||
b.extend(1.0f64.to_le_bytes());
|
||||
b.extend([0; 8]);
|
||||
b
|
||||
}
|
||||
|
||||
/// Vertex `k` of `sides`, counted clockwise from the top, on the base circle.
|
||||
fn vertex(k: u32, sides: u32) -> Pt {
|
||||
let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides);
|
||||
pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin())
|
||||
}
|
||||
|
||||
fn ends(sp: &SubPath) -> Vec<Pt> {
|
||||
sp.segments
|
||||
.iter()
|
||||
.map(|s| match *s {
|
||||
Segment::Line(e) | Segment::Cubic(_, _, e) => e,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn close(a: &[Pt], b: &[Pt]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
fn star(sides: u32, step: u32, first: u32, second: u32) -> Path {
|
||||
let p = crate::layout::for_version(1300).unwrap();
|
||||
let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] };
|
||||
let mut budget = Budget::new(crate::Limits::default());
|
||||
let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else {
|
||||
panic!("no polygon")
|
||||
};
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_star_whose_sides_skip_a_vertex_chains_its_points() {
|
||||
// {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0.
|
||||
let path = star(5, 2, 2, 0);
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
let want: Vec<Pt> = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect();
|
||||
assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0]));
|
||||
// The base side alone tells the step when the field doesn't.
|
||||
assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() {
|
||||
// {6/2}: two triangles, 0-2-4 and 1-3-5.
|
||||
let path = star(6, 2, 0, 2);
|
||||
assert_eq!(path.subpaths.len(), 2);
|
||||
assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)]));
|
||||
assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)]));
|
||||
assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_polygon_turns_one_vertex_for_each_side() {
|
||||
let path = star(4, 1, 0, 1);
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! What a version 3 object holds as arguments where later versions name records: its transforms
|
||||
//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35).
|
||||
|
||||
use crate::bytes::Rd;
|
||||
use crate::layout::Profile;
|
||||
use crate::model::{Cap, Color, Join, Matrix, Outline};
|
||||
use crate::records::{self, angle, coord};
|
||||
use crate::riff::push;
|
||||
use crate::{Limits, Warning};
|
||||
|
||||
/// Transform entry types (R33): a matrix, and an envelope.
|
||||
const MATRIX: u16 = 0x8c;
|
||||
const ENVELOPE: u16 = 0x14;
|
||||
/// The bytes of one transform entry (R33).
|
||||
const ENTRY: usize = 10;
|
||||
/// The bytes an outline keeps for its dashes, one byte each (R35).
|
||||
const DASH_AREA: usize = 10;
|
||||
|
||||
/// The transforms of one object or group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Placement {
|
||||
/// The matrices composed in file order, in points.
|
||||
pub(crate) matrix: Matrix,
|
||||
/// An envelope bends the shape. The reader doesn't apply envelopes.
|
||||
pub(crate) envelope: bool,
|
||||
}
|
||||
|
||||
/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at
|
||||
/// byte 6, where the entry's data starts in the argument. The count is held to the entries the
|
||||
/// argument holds and to the arguments a record may have. Entries of other types are passed over.
|
||||
pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec<Warning>) -> Option<Placement> {
|
||||
let mut r = Rd::new(b);
|
||||
r.skip(2)?;
|
||||
let stored = usize::from(r.u16()?);
|
||||
let count = stored.min(r.left() / ENTRY).min(limits.arguments);
|
||||
if count < stored {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false };
|
||||
for _ in 0..count {
|
||||
let mut e = Rd::new(r.bytes(ENTRY)?);
|
||||
let kind = e.u16()?;
|
||||
e.skip(4)?;
|
||||
let at = usize::from(e.u16()?);
|
||||
match kind {
|
||||
MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix),
|
||||
ENVELOPE => out.envelope = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills
|
||||
/// of other types read as none with a warning. The outer `None` is an argument that can't be read.
|
||||
pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Option<Color>> {
|
||||
let mut r = Rd::new(b);
|
||||
match r.u8()? {
|
||||
0 => Some(None),
|
||||
1 => Some(Some(records::color(&mut r, p, warn)?)),
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedFills);
|
||||
Some(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the
|
||||
/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the
|
||||
/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends
|
||||
/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an
|
||||
/// argument that can't be read.
|
||||
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Option<Outline>> {
|
||||
let mut r = Rd::new(b);
|
||||
if r.u8()? & 1 == 0 {
|
||||
return Some(None);
|
||||
}
|
||||
let width = coord(&mut r, p)?.abs();
|
||||
let _stretch = r.u16()?;
|
||||
let _nib = angle(&mut r, p)?;
|
||||
let color = records::color(&mut r, p, warn)?;
|
||||
let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false };
|
||||
let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) };
|
||||
let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) };
|
||||
if stored > DASH_AREA {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let dashes: Vec<f64> = area.iter().take(stored).map(|d| f64::from(*d)).collect();
|
||||
if dashes.iter().any(|d| *d > 0.0) {
|
||||
out.dashes = dashes;
|
||||
}
|
||||
out.join = match r.u16() {
|
||||
Some(1) => Join::Round,
|
||||
Some(2) => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
};
|
||||
out.cap = match r.u16() {
|
||||
Some(1) => Cap::Round,
|
||||
Some(2) => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
};
|
||||
if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) {
|
||||
push(warn, Warning::Arrowheads);
|
||||
}
|
||||
Some(Some(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p3() -> Profile {
|
||||
crate::layout::for_version(300).unwrap()
|
||||
}
|
||||
|
||||
/// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for
|
||||
/// each entry.
|
||||
fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec<u8> {
|
||||
let mut b = vec![0, 0];
|
||||
b.extend(count.to_le_bytes());
|
||||
for (kind, at) in entries {
|
||||
b.extend(kind.to_le_bytes());
|
||||
b.extend([0; 4]);
|
||||
b.extend(at.to_le_bytes());
|
||||
b.extend([0; 2]);
|
||||
}
|
||||
b.extend(data.iter().flat_map(|v| v.to_le_bytes()));
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrices_compose_in_file_order_and_other_entries_are_passed_over() {
|
||||
// Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c.
|
||||
let scale = [131072, 0, 0, 0, 131072, 0];
|
||||
let shift = [65536, 0, 1000, 0, 65536, 0];
|
||||
let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat());
|
||||
let mut w = vec![];
|
||||
let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap();
|
||||
assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false));
|
||||
assert!(w.is_empty());
|
||||
let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale);
|
||||
assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_transform_arguments_do_not_read_past_their_bytes() {
|
||||
let scale = [131072, 0, 0, 0, 131072, 0];
|
||||
// A count of 65,535 over one entry reads that entry, with the damage warning.
|
||||
let b = arg(u16::MAX, &[(MATRIX, 14)], &scale);
|
||||
let mut w = vec![];
|
||||
assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0);
|
||||
assert_eq!(w, vec![Warning::Damaged]);
|
||||
// A data offset past the argument, and one that leaves less than a matrix.
|
||||
for at in [5000, 14 + 4] {
|
||||
assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}");
|
||||
}
|
||||
// More entries than a record may have arguments.
|
||||
let many: Vec<(u16, u16)> = vec![(0x99, 0); 100];
|
||||
let limits = Limits { arguments: 8, ..Limits::default() };
|
||||
let mut w = vec![];
|
||||
assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some());
|
||||
assert_eq!(w, vec![Warning::Damaged]);
|
||||
for len in 0..4 {
|
||||
assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads.
|
||||
fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec<u8> {
|
||||
let mut b = vec![flags];
|
||||
b.extend(28i16.to_le_bytes());
|
||||
b.extend([100, 0, 0, 0]);
|
||||
b.extend([1, 0, 0, 0, 100]);
|
||||
b.extend([0; 7]);
|
||||
b.push(count);
|
||||
let mut area = dashes.to_vec();
|
||||
area.resize(DASH_AREA, 0);
|
||||
b.extend(area);
|
||||
b.extend(join.to_le_bytes());
|
||||
b.extend(cap.to_le_bytes());
|
||||
b.extend(heads.iter().flat_map(|h| h.to_le_bytes()));
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outline_reads_its_width_color_dashes_join_and_caps() {
|
||||
let mut w = vec![];
|
||||
let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap();
|
||||
assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width);
|
||||
assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0]));
|
||||
assert!(w.is_empty());
|
||||
// Bit 0 clear: no outline, whatever follows.
|
||||
assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None));
|
||||
assert_eq!(outline(&[0], &p3(), &mut w), Some(None));
|
||||
assert!(w.is_empty());
|
||||
outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap();
|
||||
assert_eq!(w, vec![Warning::Arrowheads]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_count_past_the_dash_bytes_is_held_to_them() {
|
||||
let mut w = vec![];
|
||||
let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap();
|
||||
assert_eq!(o.dashes.len(), DASH_AREA);
|
||||
assert_eq!(w, vec![Warning::Damaged]);
|
||||
// An argument that ends inside the dashes keeps a solid line; one cut before the color is
|
||||
// unreadable.
|
||||
let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]);
|
||||
assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::<f64>::new());
|
||||
assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt);
|
||||
for len in 0..12 {
|
||||
assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_read_none_uniform_and_other_types() {
|
||||
let mut w = vec![];
|
||||
assert_eq!(fill(&[0], &p3(), &mut w), Some(None));
|
||||
assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0]))));
|
||||
assert!(w.is_empty());
|
||||
for kind in [2, 4, 6, 7, 10] {
|
||||
let mut w = vec![];
|
||||
assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None));
|
||||
assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}");
|
||||
}
|
||||
assert_eq!(fill(&[], &p3(), &mut w), None);
|
||||
assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Where the fields of each record lie, by version: one table, resolved once per file. Each field
|
||||
//! names the `PROVENANCE.md` row it rests on.
|
||||
|
||||
/// The layouts of one range of versions.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Profile {
|
||||
/// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7).
|
||||
pub(crate) short: bool,
|
||||
/// Bytes before the page size in `mcfg` (R10).
|
||||
pub(crate) mcfg_skip: usize,
|
||||
/// Bytes before a `trfd` entry's type (R8).
|
||||
pub(crate) trfd_head: usize,
|
||||
/// Bytes between a matrix entry's type and its six numbers (R8).
|
||||
pub(crate) matrix_skip: usize,
|
||||
/// Fill and outline records start with tagged records (R11, R12).
|
||||
pub(crate) tagged: bool,
|
||||
/// Outline: bytes after the join, after the stretch, after the nib angle and after the color
|
||||
/// (R12).
|
||||
pub(crate) outl_after_join: usize,
|
||||
pub(crate) outl_after_stretch: usize,
|
||||
pub(crate) outl_after_angle: usize,
|
||||
pub(crate) outl_after_color: usize,
|
||||
/// Where the start marker id lies after the first dash (R13); `None` where no source says.
|
||||
pub(crate) marker_after_dash: Option<usize>,
|
||||
/// Rectangles carry four corner radii, not one (R15).
|
||||
pub(crate) four_radii: bool,
|
||||
/// Rectangles are f64 sizes with radii as shares of half the shorter side (R29).
|
||||
pub(crate) f64_rect: bool,
|
||||
/// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19).
|
||||
pub(crate) old_master_flags: bool,
|
||||
/// Object type 0x25 is a path (R30).
|
||||
pub(crate) paths: bool,
|
||||
/// Names are UTF-16LE, not Windows-1252 (R9).
|
||||
pub(crate) utf16_names: bool,
|
||||
/// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill`
|
||||
/// or `outl` records (R33, R34, R35).
|
||||
pub(crate) inline_styles: bool,
|
||||
/// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32).
|
||||
pub(crate) types_from_zero: bool,
|
||||
/// How a color is laid out (R14, R36).
|
||||
pub(crate) color: ColorLayout,
|
||||
/// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37).
|
||||
pub(crate) fixed_matrix: bool,
|
||||
/// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38).
|
||||
pub(crate) mcfg_corners: bool,
|
||||
}
|
||||
|
||||
/// The layouts of a color.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ColorLayout {
|
||||
/// A model byte and four value bytes (R36).
|
||||
Bytes5,
|
||||
/// A model u16, four u16 values and 2 bytes (R36).
|
||||
Words12,
|
||||
/// A model u16, a palette u16, 4 bytes and four value bytes (R14).
|
||||
Record12,
|
||||
}
|
||||
|
||||
const fn profile(from: u16) -> Profile {
|
||||
let short = from < 600;
|
||||
Profile {
|
||||
short,
|
||||
inline_styles: from < 400,
|
||||
types_from_zero: from < 400,
|
||||
color: if from < 400 {
|
||||
ColorLayout::Bytes5
|
||||
} else if from < 500 {
|
||||
ColorLayout::Words12
|
||||
} else {
|
||||
ColorLayout::Record12
|
||||
},
|
||||
fixed_matrix: from < 500,
|
||||
mcfg_corners: from < 400,
|
||||
mcfg_skip: if from >= 1300 {
|
||||
12
|
||||
} else if from >= 900 {
|
||||
4
|
||||
} else if from >= 600 && from < 700 {
|
||||
28
|
||||
} else {
|
||||
0
|
||||
},
|
||||
trfd_head: if from >= 1300 { 8 } else { 0 },
|
||||
matrix_skip: if short { 0 } else { 6 },
|
||||
tagged: from >= 1300,
|
||||
outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 },
|
||||
outl_after_stretch: if short { 0 } else { 2 },
|
||||
outl_after_angle: if from >= 1300 {
|
||||
46
|
||||
} else if !short {
|
||||
52
|
||||
} else {
|
||||
0
|
||||
},
|
||||
outl_after_color: if short { 10 } else { 16 },
|
||||
marker_after_dash: if from >= 1300 {
|
||||
Some(20)
|
||||
} else if from >= 600 {
|
||||
Some(22)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
four_radii: from >= 900,
|
||||
f64_rect: from >= 1500,
|
||||
old_master_flags: from < 1400,
|
||||
paths: from >= 1000,
|
||||
utf16_names: from >= 1200,
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2).
|
||||
pub(crate) const NEWEST: u16 = 2799;
|
||||
|
||||
/// The first version of each range, with its layouts. Ranges start where a field moves.
|
||||
const PROFILES: &[(u16, Profile)] = &[
|
||||
(300, profile(300)),
|
||||
(400, profile(400)),
|
||||
(500, profile(500)),
|
||||
(600, profile(600)),
|
||||
(700, profile(700)),
|
||||
(800, profile(800)),
|
||||
(900, profile(900)),
|
||||
(1000, profile(1000)),
|
||||
(1100, profile(1100)),
|
||||
(1200, profile(1200)),
|
||||
(1300, profile(1300)),
|
||||
(1400, profile(1400)),
|
||||
(1500, profile(1500)),
|
||||
(1600, profile(1600)),
|
||||
];
|
||||
|
||||
/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`).
|
||||
pub(crate) const OLDEST_RIFF: u16 = 300;
|
||||
|
||||
/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or
|
||||
/// `None` outside 3 to 27.
|
||||
pub(crate) fn for_version(version: u16) -> Option<Profile> {
|
||||
if !(OLDEST_RIFF..=NEWEST).contains(&version) {
|
||||
return None;
|
||||
}
|
||||
PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p)
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
/// Points per coordinate unit.
|
||||
pub(crate) fn unit(&self) -> f64 {
|
||||
if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 }
|
||||
}
|
||||
|
||||
/// Bytes of a coordinate, and of header fields and counts.
|
||||
pub(crate) fn word(&self) -> usize {
|
||||
if self.short { 2 } else { 4 }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_version_from_3_to_27_has_one_profile() {
|
||||
assert!(for_version(299).is_none() && for_version(2800).is_none());
|
||||
assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix));
|
||||
assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5));
|
||||
assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix));
|
||||
assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12));
|
||||
assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12));
|
||||
assert!(for_version(1300).is_some_and(|p| p.old_master_flags));
|
||||
assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags));
|
||||
assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths));
|
||||
assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names));
|
||||
assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none()));
|
||||
assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22)));
|
||||
assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22)));
|
||||
assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22)));
|
||||
assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths));
|
||||
assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46));
|
||||
// The table is in order, so the search finds each range's own row.
|
||||
assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files
|
||||
//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP
|
||||
//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups,
|
||||
//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads
|
||||
//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and
|
||||
//! curves with uniform fills and outlines.
|
||||
//!
|
||||
//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source
|
||||
//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not
|
||||
//! panic. Nothing here writes `.cdr` or `.cmx` files.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::fmt;
|
||||
|
||||
mod build;
|
||||
mod bytes;
|
||||
mod cmx;
|
||||
mod geometry;
|
||||
mod inline;
|
||||
mod layout;
|
||||
mod limits;
|
||||
pub mod model;
|
||||
mod package;
|
||||
mod records;
|
||||
mod riff;
|
||||
mod styles;
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
pub mod synth;
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
pub mod synth_cmx;
|
||||
mod wl;
|
||||
mod zip;
|
||||
|
||||
pub use limits::Limits;
|
||||
pub use model::{Drawing, Warning};
|
||||
|
||||
/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file
|
||||
/// of version 1 or 2 whose header offsets fit the file?
|
||||
pub fn is_cdr(bytes: &[u8]) -> bool {
|
||||
riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes)
|
||||
}
|
||||
|
||||
/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type
|
||||
/// `CMX1`?
|
||||
pub fn is_cmx(bytes: &[u8]) -> bool {
|
||||
cmx::is_cmx(bytes)
|
||||
}
|
||||
|
||||
/// Why a file can't be read.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// Not a `.cdr` drawing.
|
||||
NotCdr,
|
||||
/// Not a `.cmx` file.
|
||||
NotCmx,
|
||||
/// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28).
|
||||
Version(u16),
|
||||
/// A container structure that doesn't parse.
|
||||
Damaged(&'static str),
|
||||
/// Past one of the [`Limits`].
|
||||
Limit(&'static str),
|
||||
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
|
||||
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates.
|
||||
Unsupported(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Error::NotCdr => write!(f, "not a CDR drawing"),
|
||||
Error::NotCmx => write!(f, "not a CMX file"),
|
||||
Error::Version(v) => write!(f, "version {} drawings are not read", v / 100),
|
||||
Error::Damaged(what) => write!(f, "damaged {what}"),
|
||||
Error::Limit(what) => write!(f, "past the {what} limit"),
|
||||
Error::Unsupported(what) => write!(f, "{what} are not read"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// Read a drawing within `limits`.
|
||||
pub fn read(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
if bytes.len() > limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
let mut budget = limits::Budget::new(limits);
|
||||
// Versions 1 and 2 are not RIFF files (R40).
|
||||
if wl::is_wl(bytes) {
|
||||
return wl::drawing(bytes, &mut budget);
|
||||
}
|
||||
let mut warnings = Vec::new();
|
||||
// Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26).
|
||||
let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) };
|
||||
let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?;
|
||||
let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?;
|
||||
ix.stream_warnings(&mut drawing.warnings);
|
||||
Ok(drawing)
|
||||
}
|
||||
|
||||
/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with
|
||||
/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0.
|
||||
pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
if bytes.len() > limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
let mut budget = limits::Budget::new(limits);
|
||||
cmx::drawing(bytes, &mut budget)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits.
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// The most a read may take, checked before every allocation and descent.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Bytes of input.
|
||||
pub input: usize,
|
||||
/// Bytes inflated from compressed lists and package members, all of one file together.
|
||||
pub inflated: usize,
|
||||
/// Bytes of one package member.
|
||||
pub member: usize,
|
||||
/// Members of a package.
|
||||
pub members: usize,
|
||||
/// Nested lists below the file's own. Deeper content is left out with a warning.
|
||||
pub depth: usize,
|
||||
/// Chunks in the index, nested ones included, and the entries and styles of the style table;
|
||||
/// in a `.cmx` file, its chunks, table entries and page instructions.
|
||||
pub chunks: usize,
|
||||
/// Objects mapped (shapes, groups and guidelines).
|
||||
pub objects: usize,
|
||||
/// Points of all curves together.
|
||||
pub coordinates: usize,
|
||||
/// Arguments of one `loda` record.
|
||||
pub arguments: usize,
|
||||
/// Dashes of all outlines together, an outline's counted again for every shape that uses it.
|
||||
/// Past them a shape's outline is solid, with a warning.
|
||||
pub dashes: usize,
|
||||
/// Chunks walked inside clipped groups, all containers together, a group's counted again for
|
||||
/// every container that names it. Past them a container's group is left out, with a warning.
|
||||
pub clipped_chunks: usize,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MIB: usize = 1 << 20;
|
||||
|
||||
impl Default for Limits {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
input: 512 * MIB,
|
||||
inflated: 1024 * MIB,
|
||||
member: 512 * MIB,
|
||||
members: 4096,
|
||||
depth: 256,
|
||||
chunks: 2_000_000,
|
||||
objects: 1_000_000,
|
||||
coordinates: 16_000_000,
|
||||
arguments: 64,
|
||||
dashes: 16_000_000,
|
||||
clipped_chunks: 2_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
input: 256 << 20,
|
||||
inflated: 512 << 20,
|
||||
member: 256 << 20,
|
||||
members: 4096,
|
||||
depth: 256,
|
||||
chunks: 2_000_000,
|
||||
objects: 1_000_000,
|
||||
coordinates: 16_000_000,
|
||||
arguments: 64,
|
||||
dashes: 8_000_000,
|
||||
clipped_chunks: 2_000_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The running counters of one read against its [`Limits`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Budget {
|
||||
pub(crate) limits: Limits,
|
||||
inflated: usize,
|
||||
chunks: usize,
|
||||
objects: usize,
|
||||
coordinates: usize,
|
||||
dashes: usize,
|
||||
clipped_chunks: usize,
|
||||
/// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked.
|
||||
refused: bool,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub(crate) fn new(limits: Limits) -> Self {
|
||||
Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false }
|
||||
}
|
||||
|
||||
/// Whether a request for coordinates was refused since the last call, which tells a shape
|
||||
/// left out at the limit from one whose bytes don't parse.
|
||||
pub(crate) fn coordinates_refused(&mut self) -> bool {
|
||||
std::mem::take(&mut self.refused)
|
||||
}
|
||||
|
||||
/// Bytes an inflate may still produce.
|
||||
pub(crate) fn inflate_left(&self) -> usize {
|
||||
self.limits.inflated.saturating_sub(self.inflated)
|
||||
}
|
||||
|
||||
pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn take_chunk(&mut self) -> Result<(), Error> {
|
||||
self.take_chunks(1)
|
||||
}
|
||||
|
||||
/// `n` more chunks or style table entries.
|
||||
pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.chunks = self.chunks.saturating_add(n);
|
||||
if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// One more object, or `false` when the drawing already holds as many as a read maps.
|
||||
pub(crate) fn take_object(&mut self) -> bool {
|
||||
if self.objects >= self.limits.objects {
|
||||
return false;
|
||||
}
|
||||
self.objects += 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// `n` more curve points, or `false` past the limit (nothing is taken then).
|
||||
pub(crate) fn take_coordinates(&mut self, n: usize) -> bool {
|
||||
match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) {
|
||||
Some(t) => {
|
||||
self.coordinates = t;
|
||||
true
|
||||
}
|
||||
None => {
|
||||
self.refused = true;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dashes the read may still take.
|
||||
pub(crate) fn dashes_left(&self) -> usize {
|
||||
self.limits.dashes.saturating_sub(self.dashes)
|
||||
}
|
||||
|
||||
/// `n` more dashes, or `false` past the limit (nothing is taken then).
|
||||
pub(crate) fn take_dashes(&mut self, n: usize) -> bool {
|
||||
match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) {
|
||||
Some(t) => {
|
||||
self.dashes = t;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One more chunk walked inside a clipped group, or `false` past the limit.
|
||||
pub(crate) fn take_clipped_chunk(&mut self) -> bool {
|
||||
if self.clipped_chunks >= self.limits.clipped_chunks {
|
||||
return false;
|
||||
}
|
||||
self.clipped_chunks += 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y
|
||||
//! pointing up, as the file stores them.
|
||||
|
||||
/// A point in points.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Pt {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
}
|
||||
|
||||
/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Matrix(pub [f64; 6]);
|
||||
|
||||
impl Matrix {
|
||||
pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
|
||||
/// `self` after `first`: the map that applies `first`, then `self`.
|
||||
pub fn after(&self, first: &Matrix) -> Matrix {
|
||||
let [a, b, c, d, e, f] = self.0;
|
||||
let [p, q, r, s, t, u] = first.0;
|
||||
Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f])
|
||||
}
|
||||
|
||||
pub fn apply(&self, p: Pt) -> Pt {
|
||||
let [a, b, c, d, e, f] = self.0;
|
||||
Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f }
|
||||
}
|
||||
}
|
||||
|
||||
/// One segment after the previous point.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Segment {
|
||||
Line(Pt),
|
||||
/// Two control points, then the end point.
|
||||
Cubic(Pt, Pt, Pt),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubPath {
|
||||
pub start: Pt,
|
||||
pub segments: Vec<Segment>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Path {
|
||||
pub subpaths: Vec<SubPath>,
|
||||
}
|
||||
|
||||
/// The shape of an object, in its own space ([`Shape::matrix`] places it).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Geometry {
|
||||
Path(Path),
|
||||
/// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its
|
||||
/// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0).
|
||||
Rect {
|
||||
w: f64,
|
||||
h: f64,
|
||||
radii: [f64; 4],
|
||||
},
|
||||
/// A whole ellipse in the box from the origin to (`w`, `h`).
|
||||
Ellipse {
|
||||
w: f64,
|
||||
h: f64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Color {
|
||||
Rgb([f32; 3]),
|
||||
Cmyk([f32; 4]),
|
||||
/// Ink: 0 is white, 1 black.
|
||||
Gray(f32),
|
||||
/// Every ink at full strength.
|
||||
Registration,
|
||||
/// A color of a named library, printed on its own plate. `look` is its full-strength color
|
||||
/// when the file stores one (an approximation in sRGB); `tint` is 0 to 1.
|
||||
Spot {
|
||||
name: String,
|
||||
tint: f32,
|
||||
look: Option<[f32; 3]>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Cap {
|
||||
Butt,
|
||||
Round,
|
||||
Square,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Join {
|
||||
Miter,
|
||||
Round,
|
||||
Bevel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Outline {
|
||||
pub width: f64,
|
||||
pub color: Color,
|
||||
pub cap: Cap,
|
||||
pub join: Join,
|
||||
/// Dash and gap lengths, in outline widths; empty for a solid line.
|
||||
pub dashes: Vec<f64>,
|
||||
/// Drawn behind the fill, so that a filled shape shows only the outer half of it.
|
||||
pub behind_fill: bool,
|
||||
/// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the
|
||||
/// geometry.
|
||||
pub scale_with: bool,
|
||||
}
|
||||
|
||||
/// Whether a layer, group or shape is hidden or locked.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Flags {
|
||||
pub hidden: bool,
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
/// How a shape's colors combine with the art below it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Blend {
|
||||
#[default]
|
||||
Normal,
|
||||
Multiply,
|
||||
Screen,
|
||||
Overlay,
|
||||
SoftLight,
|
||||
HardLight,
|
||||
ColorDodge,
|
||||
ColorBurn,
|
||||
Darken,
|
||||
Lighten,
|
||||
Difference,
|
||||
Exclusion,
|
||||
Hue,
|
||||
Saturation,
|
||||
Color,
|
||||
Luminosity,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Shape {
|
||||
pub geometry: Geometry,
|
||||
pub matrix: Matrix,
|
||||
pub fill: Option<Color>,
|
||||
pub outline: Option<Outline>,
|
||||
/// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that
|
||||
/// overlap leave holes (even-odd).
|
||||
pub nonzero: bool,
|
||||
/// 1 opaque, 0 clear.
|
||||
pub opacity: f32,
|
||||
pub blend: Blend,
|
||||
pub flags: Flags,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// An opaque, shown shape filled even-odd.
|
||||
pub fn new(geometry: Geometry, matrix: Matrix, fill: Option<Color>, outline: Option<Outline>) -> Shape {
|
||||
Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Object {
|
||||
Shape(Box<Shape>),
|
||||
Group {
|
||||
objects: Vec<Object>,
|
||||
flags: Flags,
|
||||
},
|
||||
/// A clipping container and the objects it clips: `objects` (front to back) show only
|
||||
/// inside the container's shape, with its fill behind them and its outline over them.
|
||||
Clip {
|
||||
container: Box<Shape>,
|
||||
objects: Vec<Object>,
|
||||
},
|
||||
}
|
||||
|
||||
/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Guideline {
|
||||
pub at: Pt,
|
||||
pub angle: f64,
|
||||
/// The guideline, a group around it or its layer is hidden.
|
||||
pub hidden: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayerKind {
|
||||
Drawing,
|
||||
/// The objects left beside the pages.
|
||||
Desktop,
|
||||
Guides,
|
||||
Grid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Layer {
|
||||
pub name: String,
|
||||
pub kind: LayerKind,
|
||||
pub flags: Flags,
|
||||
/// Front to back, as the file lists them.
|
||||
pub objects: Vec<Object>,
|
||||
pub guides: Vec<Guideline>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Page {
|
||||
/// Width and height in points, when the page gives its own.
|
||||
pub size: Option<(f64, f64)>,
|
||||
/// Front to back, as the file lists them.
|
||||
pub layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
/// What was left out or changed while reading. Each kind is listed once.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Warning {
|
||||
/// Text, bitmaps, splines and other objects not read yet.
|
||||
UnsupportedObjects,
|
||||
/// Fountain, pattern, texture and PostScript fills.
|
||||
UnsupportedFills,
|
||||
/// Colors in models not read; shown black.
|
||||
UnknownColors,
|
||||
/// Library spot colors whose look the file doesn't store; shown black.
|
||||
SpotLooks,
|
||||
/// Outline arrowheads.
|
||||
Arrowheads,
|
||||
/// Envelopes, which are not applied: the shapes under them keep their outlines.
|
||||
Envelopes,
|
||||
/// Lenses, and object transparency that isn't read, which are not applied: the objects show
|
||||
/// opaque.
|
||||
Lenses,
|
||||
/// Content nested deeper, or past the counts, that a read takes.
|
||||
TooDeep,
|
||||
/// Chunks or records that end early or don't parse.
|
||||
Damaged,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Drawing {
|
||||
/// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no
|
||||
/// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A
|
||||
/// `.cmx` file gives 0.
|
||||
pub version: u16,
|
||||
/// Page size from the document settings, in points.
|
||||
pub page_size: Option<(f64, f64)>,
|
||||
pub pages: Vec<Page>,
|
||||
/// Layers every page shows, from the master page.
|
||||
pub master: Vec<Layer>,
|
||||
/// Guidelines every page shows, kept outside any layer.
|
||||
pub guides: Vec<Guideline>,
|
||||
pub warnings: Vec<Warning>,
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as
|
||||
//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data
|
||||
//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a
|
||||
//! chunk the reader reads, or a list it splits, points into it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::{Cell, OnceCell};
|
||||
|
||||
use crate::limits::{Budget, Limits};
|
||||
use crate::riff::push;
|
||||
use crate::zip::{self, Archive};
|
||||
use crate::{Error, Warning};
|
||||
|
||||
const RIFF_DATA: &[u8] = b"content/riffData.cdr";
|
||||
const ROOT: &[u8] = b"content/root.dat";
|
||||
const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat";
|
||||
const DATA_DIR: &[u8] = b"content/data/";
|
||||
|
||||
/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream?
|
||||
pub(crate) fn is_package(bytes: &[u8]) -> bool {
|
||||
zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| a.find(RIFF_DATA).or_else(|| a.find(ROOT)).is_some())
|
||||
}
|
||||
|
||||
/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on).
|
||||
pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option<Streams<'a>>), Error> {
|
||||
let zip = Archive::open(bytes, budget.limits.members)?;
|
||||
if let Some(i) = zip.find(RIFF_DATA) {
|
||||
return Ok((member(&zip, i, budget)?, None));
|
||||
}
|
||||
let root = zip.find(ROOT).ok_or(Error::NotCdr)?;
|
||||
let root = member(&zip, root, budget)?;
|
||||
let list = match zip.find(DATA_FILE_LIST) {
|
||||
Some(i) => member(&zip, i, budget)?,
|
||||
None => Cow::Borrowed(&[][..]),
|
||||
};
|
||||
// One name for each line; a line feed after the last name ends it.
|
||||
let list = list.strip_suffix(b"\n").unwrap_or(&list);
|
||||
let mut members = Vec::new();
|
||||
if !list.is_empty() {
|
||||
for line in list.split(|&b| b == b'\n') {
|
||||
if members.len() == budget.limits.members {
|
||||
return Err(Error::Limit("package member count"));
|
||||
}
|
||||
let name = line.strip_suffix(b"\r").unwrap_or(line);
|
||||
let found = zip.find(&[DATA_DIR, name].concat());
|
||||
// A data stream that is encrypted or packed some other way refuses the file, as the
|
||||
// root stream does.
|
||||
if let Some(i) = found {
|
||||
zip.check(i)?;
|
||||
}
|
||||
members.push(found);
|
||||
}
|
||||
}
|
||||
let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect();
|
||||
let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) };
|
||||
Ok((root, Some(streams)))
|
||||
}
|
||||
|
||||
/// Member `i` within the member limit and, when deflated, what is left to inflate.
|
||||
fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result<Cow<'a, [u8]>, Error> {
|
||||
let m = zip.read(i, budget.limits.member, budget.inflate_left())?;
|
||||
if let Cow::Owned(v) = &m {
|
||||
budget.take_inflated(v.len())?;
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// What reading one package member gave.
|
||||
#[derive(Debug)]
|
||||
enum Slot<'a> {
|
||||
Read(Cow<'a, [u8]>),
|
||||
Damaged,
|
||||
PastLimit,
|
||||
}
|
||||
|
||||
/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26).
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Streams<'a> {
|
||||
zip: Archive<'a>,
|
||||
/// The member holding each stream; `None` when the archive lacks it.
|
||||
members: Vec<Option<usize>>,
|
||||
/// Each member's bytes once read, so that streams naming one member read it once.
|
||||
loaded: Vec<OnceCell<Slot<'a>>>,
|
||||
member_limit: usize,
|
||||
/// A stream, or a chunk's bytes in one, could not be found.
|
||||
damaged: Cell<bool>,
|
||||
}
|
||||
|
||||
impl<'a> Streams<'a> {
|
||||
/// The member holding stream `s`; `None` when there is no such stream.
|
||||
pub(crate) fn member_of(&self, s: usize) -> Option<usize> {
|
||||
*self.members.get(s)?
|
||||
}
|
||||
|
||||
/// The size the archive gives stream `s`; `None` when there is no such stream.
|
||||
pub(crate) fn size(&self, s: usize) -> Option<usize> {
|
||||
Some(self.zip.size(self.member_of(s)?))
|
||||
}
|
||||
|
||||
/// Stream `s`, its member read on first use within the member limit and, when deflated,
|
||||
/// within `left` more inflated bytes (which it takes from).
|
||||
pub(crate) fn get(&self, s: usize, left: &Cell<usize>) -> Option<&[u8]> {
|
||||
let Some(i) = self.member_of(s) else {
|
||||
self.damaged.set(true);
|
||||
return None;
|
||||
};
|
||||
let slot = self.loaded.get(i)?.get_or_init(|| {
|
||||
let read = self.zip.read(i, self.member_limit, left.get());
|
||||
if !matches!(read, Err(Error::Limit(_))) {
|
||||
left.set(left.get().saturating_sub(self.zip.inflate_cost(i)));
|
||||
}
|
||||
match read {
|
||||
Ok(b) => Slot::Read(b),
|
||||
Err(Error::Limit(_)) => Slot::PastLimit,
|
||||
Err(_) => {
|
||||
self.damaged.set(true);
|
||||
Slot::Damaged
|
||||
}
|
||||
}
|
||||
});
|
||||
match slot {
|
||||
Slot::Read(b) => Some(b.as_ref()),
|
||||
Slot::Damaged | Slot::PastLimit => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Was stream `s` left out because it is past a limit? Chunks in it are then not damage.
|
||||
pub(crate) fn past_limit(&self, s: usize) -> bool {
|
||||
let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get);
|
||||
matches!(slot, Some(Slot::PastLimit))
|
||||
}
|
||||
|
||||
/// Mark a chunk whose stream bytes could not be found.
|
||||
pub(crate) fn note_damage(&self) {
|
||||
self.damaged.set(true);
|
||||
}
|
||||
|
||||
/// The warnings for streams that were left out.
|
||||
pub(crate) fn warnings(&self, warn: &mut Vec<Warning>) {
|
||||
if self.damaged.get() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) {
|
||||
push(warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table
|
||||
//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13).
|
||||
|
||||
use crate::bytes::Rd;
|
||||
use crate::layout::{ColorLayout, Profile};
|
||||
use crate::model::{Blend, Cap, Color, Join, Matrix, Outline};
|
||||
use crate::riff::push;
|
||||
use crate::{Limits, Warning};
|
||||
|
||||
/// The tag of a record's current layout in tagged files (R11, R12).
|
||||
const TAG_1300: u32 = 1300;
|
||||
/// The most tagged records skipped before a fill's own (R11).
|
||||
const MAX_SKIPPED: usize = 4;
|
||||
/// The most records skipped before an outline's own (R12).
|
||||
const MAX_OUTLINE_RECORDS: usize = 16;
|
||||
/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of
|
||||
/// a layer's.
|
||||
const MAX_NAME: usize = 256;
|
||||
|
||||
/// A header field: u16 in short files, u32 otherwise.
|
||||
fn word(r: &mut Rd, p: &Profile) -> Option<usize> {
|
||||
if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) }
|
||||
}
|
||||
|
||||
/// A coordinate in points.
|
||||
pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option<f64> {
|
||||
let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) };
|
||||
Some(raw * p.unit())
|
||||
}
|
||||
|
||||
/// An angle in degrees: tenths in short files, millionths otherwise (R7).
|
||||
pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option<f64> {
|
||||
if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) }
|
||||
}
|
||||
|
||||
/// A `loda` record (R6): its object type and arguments as (type, bytes).
|
||||
pub(crate) struct Loda<'a> {
|
||||
pub(crate) kind: u32,
|
||||
pub(crate) args: Vec<(u32, &'a [u8])>,
|
||||
}
|
||||
|
||||
impl<'a> Loda<'a> {
|
||||
pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> {
|
||||
self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec<Warning>) -> Option<Loda<'a>> {
|
||||
let mut r = Rd::new(b);
|
||||
let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
|
||||
// The types table is indexed from the stored count, however many arguments are read.
|
||||
let stored = count;
|
||||
let count = if count > limits.arguments {
|
||||
push(warn, Warning::Damaged);
|
||||
limits.arguments
|
||||
} else {
|
||||
count
|
||||
};
|
||||
let mut offsets = Vec::with_capacity(count + 1);
|
||||
let mut ro = Rd::at(b, offsets_at);
|
||||
for _ in 0..=count {
|
||||
offsets.push(word(&mut ro, p)?);
|
||||
}
|
||||
let mut args = Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
// The types table runs the other way: offset i pairs with type stored - 1 - i.
|
||||
let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32;
|
||||
let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?);
|
||||
match b.get(start..end) {
|
||||
Some(body) => args.push((kind, body)),
|
||||
None => push(warn, Warning::Damaged),
|
||||
}
|
||||
}
|
||||
Some(Loda { kind: kind as u32, args })
|
||||
}
|
||||
|
||||
/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where
|
||||
/// the next offset points, and the last at the offset after it (R51); an entry too short for its
|
||||
/// matrix makes the record unreadable.
|
||||
pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option<Matrix> {
|
||||
let mut r = Rd::new(b);
|
||||
let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
|
||||
let mut m = Matrix::IDENTITY;
|
||||
let k = p.unit();
|
||||
// Each entry takes at least its offset's bytes, which bounds the count by the record's size.
|
||||
for i in 0..count.min(b.len() / p.word()) {
|
||||
let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?;
|
||||
let start = word(&mut Rd::at(b, slot), p)?;
|
||||
// A table that stops before the last entry's end offset leaves that entry the rest of the
|
||||
// record.
|
||||
let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len());
|
||||
let mut e = Rd::at(b.get(start..end)?, p.trfd_head);
|
||||
if e.u16()? != 8 {
|
||||
continue;
|
||||
}
|
||||
e.skip(p.matrix_skip)?;
|
||||
let next = if p.fixed_matrix {
|
||||
fixed_matrix(&mut e, k)?
|
||||
} else {
|
||||
let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?);
|
||||
Matrix([a, bb, c, d, tx * k, ty * k])
|
||||
};
|
||||
m = next.after(&m);
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// A number in 16.16 fixed point.
|
||||
pub(crate) fn fixed(r: &mut Rd) -> Option<f64> {
|
||||
Some(f64::from(r.i32()?) / 65536.0)
|
||||
}
|
||||
|
||||
/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point
|
||||
/// and `tx` and `ty` in coordinate units of `k` points.
|
||||
pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option<Matrix> {
|
||||
let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?));
|
||||
let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?));
|
||||
Some(Matrix([a, b, c, d, tx * k, ty * k]))
|
||||
}
|
||||
|
||||
/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a
|
||||
/// warning.
|
||||
pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
|
||||
match p.color {
|
||||
ColorLayout::Record12 => {
|
||||
let model = r.u16()?;
|
||||
let palette = r.u16()?;
|
||||
r.skip(4)?;
|
||||
let v: [u8; 4] = r.bytes(4)?.try_into().ok()?;
|
||||
Some(model_color(model, palette, v, warn))
|
||||
}
|
||||
ColorLayout::Words12 => {
|
||||
let model = r.u16()?;
|
||||
let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?];
|
||||
r.skip(2)?;
|
||||
// The models take 8-bit values, as in the other layouts; a larger value reads as 255.
|
||||
Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn))
|
||||
}
|
||||
ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 5-byte color (R36): a model byte and four value bytes.
|
||||
pub(crate) fn color5(b: [u8; 5], warn: &mut Vec<Warning>) -> Color {
|
||||
let [model, v @ ..] = b;
|
||||
early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn)
|
||||
}
|
||||
|
||||
/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and
|
||||
/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file
|
||||
/// doesn't store. Other models read as in later versions.
|
||||
fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec<Warning>) -> Color {
|
||||
let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0);
|
||||
match (model, index) {
|
||||
(1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))),
|
||||
(0, 0) => Color::Gray(pct(f32::from(tint))),
|
||||
(0, 1) => Color::Gray(0.0),
|
||||
(0, number) => {
|
||||
push(warn, Warning::SpotLooks);
|
||||
Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None }
|
||||
}
|
||||
_ => model_color(model, 0, v, warn),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of `model` with the four value bytes `v`, from version 5 (R14).
|
||||
fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec<Warning>) -> Color {
|
||||
let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3]));
|
||||
let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0);
|
||||
let byte = |x: f32| x / 255.0;
|
||||
match model {
|
||||
2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]),
|
||||
3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]),
|
||||
4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]),
|
||||
5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]),
|
||||
9 => Color::Gray(1.0 - byte(v0)),
|
||||
20 => Color::Registration,
|
||||
1 | 14 | 25 => {
|
||||
let number = u16::from_le_bytes([v[0], v[1]]);
|
||||
let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]])));
|
||||
push(warn, Warning::SpotLooks);
|
||||
// Each library numbers its own colors: the name holds the palette and the number.
|
||||
Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None }
|
||||
}
|
||||
_ => {
|
||||
push(warn, Warning::UnknownColors);
|
||||
Color::Rgb([0.0; 3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color
|
||||
/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a
|
||||
/// hash of the whole name, with a warning, so two long names that start alike stay apart.
|
||||
fn counted_utf16(r: &mut Rd, warn: &mut Vec<Warning>) -> Option<String> {
|
||||
let n = r.u32()? as usize;
|
||||
let b = r.bytes(n.checked_mul(2)?)?;
|
||||
// Trailing NULs are padding.
|
||||
let all = b.as_chunks::<2>().0;
|
||||
let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default();
|
||||
let units = all.iter().map(|c| u16::from_le_bytes(*c));
|
||||
if all.len() <= MAX_NAME {
|
||||
let units: Vec<u16> = units.collect();
|
||||
return Some(String::from_utf16_lossy(&units));
|
||||
}
|
||||
push(warn, Warning::TooDeep);
|
||||
// FNV-1a over the code units.
|
||||
let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3));
|
||||
let kept: Vec<u16> = units.take(MAX_NAME).collect();
|
||||
Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept)))
|
||||
}
|
||||
|
||||
/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color
|
||||
/// record, named by the library name it carries.
|
||||
pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
|
||||
let mut r = Rd::new(b);
|
||||
let (mut found, mut name) = (None, None);
|
||||
while r.left() >= 5 {
|
||||
let kind = r.u8()?;
|
||||
let len = r.u32()? as usize;
|
||||
if kind == 0 {
|
||||
break;
|
||||
}
|
||||
let body = r.bytes(len)?;
|
||||
let mut br = Rd::new(body);
|
||||
match kind {
|
||||
1 => found = color(&mut br, p, warn),
|
||||
8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)),
|
||||
3 => name = name.or_else(|| counted_utf16(&mut br, warn)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match (found?, name.filter(|n| !n.is_empty())) {
|
||||
// A library color with its name: the record's sRGB has the tint applied already.
|
||||
(Color::Rgb(rgb), Some(name)) => {
|
||||
let tint = b_tint(b).unwrap_or(1.0);
|
||||
Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) })
|
||||
}
|
||||
(c, _) => Some(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tint byte of the first color property of a property list (model 21 keeps it last).
|
||||
fn b_tint(b: &[u8]) -> Option<f32> {
|
||||
let mut r = Rd::new(b);
|
||||
while r.left() >= 5 {
|
||||
let kind = r.u8()?;
|
||||
let len = r.u32()? as usize;
|
||||
let body = r.bytes(len)?;
|
||||
if kind == 1 {
|
||||
let mut c = Rd::new(body);
|
||||
return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white).
|
||||
fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
|
||||
if tint <= 0.0 {
|
||||
return rgb;
|
||||
}
|
||||
rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with
|
||||
/// a warning (R11).
|
||||
pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Color>)> {
|
||||
let mut r = Rd::new(b);
|
||||
let id = r.u32()?;
|
||||
let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? };
|
||||
let mut r = Rd::new(body);
|
||||
let kind = r.u16()?;
|
||||
let color = match kind {
|
||||
0 => None,
|
||||
1 if p.tagged => {
|
||||
if r.u32()? != TAG_1300 {
|
||||
push(warn, Warning::Damaged);
|
||||
return Some((id, None));
|
||||
}
|
||||
// A uniform fill whose color can't be read is damage, not a fill of none.
|
||||
let len = r.u32()? as usize;
|
||||
Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?)
|
||||
}
|
||||
1 => {
|
||||
r.skip(2)?;
|
||||
Some(color(&mut r, p, warn)?)
|
||||
}
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedFills);
|
||||
None
|
||||
}
|
||||
};
|
||||
Some((id, color))
|
||||
}
|
||||
|
||||
/// The body of the record tagged 1300 that follows tagged records of later layouts (R11).
|
||||
fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> {
|
||||
for _ in 0..=MAX_SKIPPED {
|
||||
let (tag, len) = (r.u32()?, r.u32()? as usize);
|
||||
let body = r.bytes(len.min(r.left()))?;
|
||||
if tag == TAG_1300 {
|
||||
return Some(body);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// An outline record: its id and the outline (`None`: no outline) (R12, R13).
|
||||
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Outline>)> {
|
||||
let mut r = Rd::new(b);
|
||||
let id = r.u32()?;
|
||||
// A library color named in a record of type 2, with the warnings its read gave.
|
||||
let mut named = None;
|
||||
if p.tagged {
|
||||
let mut found = false;
|
||||
for _ in 0..MAX_OUTLINE_RECORDS {
|
||||
let (rec, len) = (r.u32()?, r.u32()? as usize);
|
||||
if rec == 1 {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
let body = r.bytes(len)?;
|
||||
// Type 2 holds the outline's color as a property list, as a uniform fill does (R12).
|
||||
// Only a library color with its name is taken from it; any other color comes from
|
||||
// the fixed field below.
|
||||
if rec == 2 {
|
||||
let mut w = Vec::new();
|
||||
if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) {
|
||||
named = Some((c, w));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?);
|
||||
r.skip(p.outl_after_join)?;
|
||||
let width = coord(&mut r, p)?.abs();
|
||||
let _stretch = r.u16()?;
|
||||
r.skip(p.outl_after_stretch)?;
|
||||
let _nib = angle(&mut r, p)?;
|
||||
r.skip(p.outl_after_angle)?;
|
||||
let color = match named {
|
||||
Some((named, w)) => {
|
||||
color(&mut r, p, &mut Vec::new())?;
|
||||
for x in w {
|
||||
push(warn, x);
|
||||
}
|
||||
named
|
||||
}
|
||||
None => color(&mut r, p, warn)?,
|
||||
};
|
||||
r.skip(p.outl_after_color)?;
|
||||
let count = usize::from(r.u16()?);
|
||||
let first_dash = r.pos();
|
||||
let fits = r.left() / 2;
|
||||
if count > fits {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
// At most 65,535; the read's dash limit is applied where shapes use them.
|
||||
let dashes: Vec<f64> = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect();
|
||||
if let Some(after) = p.marker_after_dash {
|
||||
let mut m = Rd::at(b, first_dash + after);
|
||||
if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) {
|
||||
push(warn, Warning::Arrowheads);
|
||||
}
|
||||
}
|
||||
// Bit 0 of the line type: no outline (R13).
|
||||
if line_type & 1 != 0 {
|
||||
return Some((id, None));
|
||||
}
|
||||
let cap = match cap {
|
||||
1 => Cap::Round,
|
||||
2 => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
};
|
||||
let join = match join {
|
||||
1 => Join::Round,
|
||||
2 => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
};
|
||||
// Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn
|
||||
// (R48).
|
||||
let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() };
|
||||
// Bit 4 of the line type: behind the fill (R49).
|
||||
let behind_fill = line_type & 0x10 != 0;
|
||||
// Bit 5 of the line type: scaled with the shape (R50).
|
||||
let scale_with = line_type & 0x20 != 0;
|
||||
Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with })))
|
||||
}
|
||||
|
||||
/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32
|
||||
/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform
|
||||
/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the
|
||||
/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens,
|
||||
/// and for a value out of range or a merge mode without a VectorCraft blend mode.
|
||||
pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> {
|
||||
let mut r = Rd::new(b);
|
||||
while r.left() >= 8 {
|
||||
let (since, len) = (r.u32()?, r.u32()? as usize);
|
||||
let body = r.bytes(len)?;
|
||||
if since != TAG_1300 {
|
||||
continue;
|
||||
}
|
||||
if body.len() != UNIFORM_LEN {
|
||||
return None;
|
||||
}
|
||||
let value = Rd::at(body, 61).f64()?;
|
||||
if !(0.0..=100.0).contains(&value) {
|
||||
return None;
|
||||
}
|
||||
return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The length of a uniform transparency's record body (R47).
|
||||
const UNIFORM_LEN: usize = 117;
|
||||
|
||||
/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has
|
||||
/// no blend mode for.
|
||||
fn blend(mode: u8) -> Option<Blend> {
|
||||
Some(match mode {
|
||||
0 => Blend::Normal,
|
||||
9 => Blend::Multiply,
|
||||
11 => Blend::Lighten,
|
||||
12 => Blend::Darken,
|
||||
14 => Blend::Color,
|
||||
15 => Blend::Hue,
|
||||
16 => Blend::Saturation,
|
||||
17 => Blend::Luminosity,
|
||||
24 => Blend::Difference,
|
||||
28 => Blend::Screen,
|
||||
29 => Blend::Overlay,
|
||||
30 => Blend::SoftLight,
|
||||
31 => Blend::HardLight,
|
||||
33 => Blend::ColorDodge,
|
||||
34 => Blend::ColorBurn,
|
||||
36 => Blend::Exclusion,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name
|
||||
/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a
|
||||
/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does.
|
||||
pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> String {
|
||||
if p.utf16_names {
|
||||
let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0);
|
||||
let (mut kept, hash) = capped(units, warn);
|
||||
if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) {
|
||||
kept.pop();
|
||||
}
|
||||
with_hash(String::from_utf16_lossy(&kept), hash)
|
||||
} else {
|
||||
let bytes = b.iter().copied().take_while(|c| *c != 0);
|
||||
let (kept, hash) = capped(bytes, warn);
|
||||
with_hash(kept.into_iter().map(windows_1252).collect(), hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a
|
||||
/// warning.
|
||||
fn capped<T: Copy + Into<u64>>(units: impl Iterator<Item = T> + Clone, warn: &mut Vec<Warning>) -> (Vec<T>, Option<u64>) {
|
||||
if units.clone().nth(MAX_NAME).is_none() {
|
||||
return (units.collect(), None);
|
||||
}
|
||||
push(warn, Warning::TooDeep);
|
||||
let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3));
|
||||
(units.take(MAX_NAME).collect(), Some(hash))
|
||||
}
|
||||
|
||||
/// `name`, followed by `hash` in hexadecimal when there is one.
|
||||
fn with_hash(name: String, hash: Option<u64>) -> String {
|
||||
match hash {
|
||||
Some(h) => format!("{name} {h:016x}"),
|
||||
None => name,
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes
|
||||
/// are Latin-1.
|
||||
const CP1252_HIGH: [char; 32] = [
|
||||
'€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–',
|
||||
'—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ',
|
||||
];
|
||||
|
||||
fn windows_1252(c: u8) -> char {
|
||||
match c {
|
||||
0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'),
|
||||
_ => char::from(c),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An outline that names an arrowhead says so with a warning, in each version whose arrowhead
|
||||
/// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13.
|
||||
#[test]
|
||||
fn arrowheads_are_named_from_version_6() {
|
||||
let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 };
|
||||
let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100];
|
||||
for (version, place) in [
|
||||
(500, None),
|
||||
(600, Some(22)),
|
||||
(700, Some(22)),
|
||||
(800, Some(22)),
|
||||
(900, Some(22)),
|
||||
(1000, Some(22)),
|
||||
(1100, Some(22)),
|
||||
(1200, Some(22)),
|
||||
(1300, Some(20)),
|
||||
(1700, Some(20)),
|
||||
] {
|
||||
let p = crate::layout::for_version(version).unwrap();
|
||||
let plain = crate::synth::V(version).outline(7, pen, &color, &[]);
|
||||
// The record ends with 32 bytes after its dashes, and this one has none.
|
||||
let first_dash = plain.len() - 32;
|
||||
let mut w = vec![];
|
||||
assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}");
|
||||
assert!(w.is_empty(), "{version}: {w:?}");
|
||||
let Some(place) = place else { continue };
|
||||
let mut arrow = plain.clone();
|
||||
arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes());
|
||||
let mut w = vec![];
|
||||
assert!(outline(&arrow, &p, &mut w).is_some(), "{version}");
|
||||
assert_eq!(w, vec![Warning::Arrowheads], "{version}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_byte_names_read_as_windows_1252() {
|
||||
let p = crate::layout::for_version(1100).unwrap();
|
||||
assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–");
|
||||
let p = crate::layout::for_version(1200).unwrap();
|
||||
assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB");
|
||||
}
|
||||
|
||||
/// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash
|
||||
/// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate
|
||||
/// pair.
|
||||
#[test]
|
||||
fn long_layer_names_are_cut_with_a_hash() {
|
||||
for version in [1100, 1200] {
|
||||
let p = crate::layout::for_version(version).unwrap();
|
||||
let bytes =
|
||||
|s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>() } else { s.as_bytes().to_vec() };
|
||||
let mut w = vec![];
|
||||
let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w);
|
||||
let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]);
|
||||
assert_ne!(a, b, "{version}");
|
||||
assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len());
|
||||
assert_eq!(w, vec![Warning::TooDeep], "{version}");
|
||||
let mut w = vec![];
|
||||
assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}");
|
||||
assert!(w.is_empty(), "{version}");
|
||||
}
|
||||
let p = crate::layout::for_version(1200).unwrap();
|
||||
let emoji: Vec<u8> = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let cut = name(&emoji, &p, &mut vec![]);
|
||||
assert!(!cut.contains('\u{FFFD}'), "{cut}");
|
||||
assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_read_in_their_models() {
|
||||
let p = crate::layout::for_version(500).unwrap();
|
||||
let rec = |model: u16, v: [u8; 4]| {
|
||||
let mut b = model.to_le_bytes().to_vec();
|
||||
b.extend([0; 6]);
|
||||
b.extend(v);
|
||||
let mut w = vec![];
|
||||
(color(&mut Rd::new(&b), &p, &mut w), w)
|
||||
};
|
||||
assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1])));
|
||||
assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0])));
|
||||
assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0)));
|
||||
assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None }));
|
||||
// The same number in another library is another color.
|
||||
let mut other = 25u16.to_le_bytes().to_vec();
|
||||
other.extend(3u16.to_le_bytes());
|
||||
other.extend([0; 4]);
|
||||
other.extend([7, 0, 40, 0]);
|
||||
assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None }));
|
||||
let (c, w) = rec(6, [1, 2, 3, 4]);
|
||||
assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_of_versions_3_and_4_read_models_0_and_1() {
|
||||
let read = |version: u16, model: u8, v: [u16; 4]| {
|
||||
let p = crate::layout::for_version(version).unwrap();
|
||||
let b: Vec<u8> = if version < 400 {
|
||||
std::iter::once(model).chain(v.map(|x| x as u8)).collect()
|
||||
} else {
|
||||
u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect()
|
||||
};
|
||||
let mut r = Rd::new(&b);
|
||||
let mut w = vec![];
|
||||
let c = color(&mut r, &p, &mut w);
|
||||
assert_eq!(r.left(), 0, "{version}");
|
||||
(c, w)
|
||||
};
|
||||
for version in [300, 400] {
|
||||
// Model 1 is CMYK in percent, not a library color as from version 5.
|
||||
assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}");
|
||||
assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}");
|
||||
}
|
||||
// Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes.
|
||||
assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6)));
|
||||
assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0)));
|
||||
assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks]));
|
||||
assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6)));
|
||||
assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0)));
|
||||
assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_point_matrix_reads_its_factors_and_offsets() {
|
||||
let raw: Vec<u8> = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap();
|
||||
assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0]));
|
||||
assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_names_that_start_alike_stay_apart() {
|
||||
let read = |name: &str| {
|
||||
let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec();
|
||||
b.extend(name.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
let mut w = vec![];
|
||||
(counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w)
|
||||
};
|
||||
let (a, w) = read(&"N".repeat(300));
|
||||
let (b, _) = read(&format!("{}M", "N".repeat(299)));
|
||||
assert_ne!(a, b);
|
||||
assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}");
|
||||
assert_eq!(w, vec![Warning::TooDeep]);
|
||||
assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![]));
|
||||
// Padding doesn't count toward the length or the name.
|
||||
let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1)));
|
||||
assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_mixes_toward_white_and_comes_off_again() {
|
||||
let shown = [0.6, 0.8, 1.0];
|
||||
let base = untinted(shown, 0.5);
|
||||
assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
//! The chunk index: one flat table of every chunk, a list's children contiguous, built without
|
||||
//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes
|
||||
//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27).
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Read as _;
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::layout;
|
||||
use crate::limits::Budget;
|
||||
use crate::package::Streams;
|
||||
use crate::{Error, Warning};
|
||||
|
||||
pub(crate) const LIST: [u8; 4] = *b"LIST";
|
||||
const CMPR: [u8; 4] = *b"cmpr";
|
||||
const CPNG: [u8; 4] = *b"CPng";
|
||||
/// What follows `CPng` before the zlib stream (R3).
|
||||
const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0];
|
||||
/// The size of a redirect record, and the stream number of one that holds its body (R27).
|
||||
const REDIRECT: usize = 16;
|
||||
const INLINE: u32 = u32::MAX;
|
||||
|
||||
/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its
|
||||
/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Chunk {
|
||||
pub(crate) id: [u8; 4],
|
||||
/// A list's form type; zeros for other chunks.
|
||||
pub(crate) form: [u8; 4],
|
||||
src: u32,
|
||||
start: u32,
|
||||
len: u32,
|
||||
first: u32,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool {
|
||||
self.id == LIST && &self.form == form
|
||||
}
|
||||
}
|
||||
|
||||
/// Every chunk of a file, and the bytes they point into.
|
||||
pub(crate) struct Index<'a> {
|
||||
input: &'a [u8],
|
||||
inflated: Vec<u8>,
|
||||
chunks: Vec<Chunk>,
|
||||
/// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk
|
||||
/// decides).
|
||||
pub(crate) form_version: u16,
|
||||
/// A version 16+ package's data streams; chunks of 16 bytes are redirect records then.
|
||||
streams: Option<Streams<'a>>,
|
||||
/// Bytes that inflating may still produce.
|
||||
left: Cell<usize>,
|
||||
/// The bytes redirected lists have taken: (package member, start) to end.
|
||||
lists: Cell<BTreeMap<(usize, usize), usize>>,
|
||||
/// The bytes other redirected chunks have taken, the same way.
|
||||
leaves: Cell<BTreeMap<(usize, usize), usize>>,
|
||||
/// Bytes that redirects to bytes another chunk already took may still read.
|
||||
shared_left: Cell<usize>,
|
||||
/// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names
|
||||
/// (`None` when it can't be read) (R2).
|
||||
vrsn: Option<Option<u16>>,
|
||||
}
|
||||
|
||||
/// A list still to be split into its children.
|
||||
struct Pending {
|
||||
entry: usize,
|
||||
src: u32,
|
||||
/// Its children's bytes.
|
||||
start: usize,
|
||||
end: usize,
|
||||
/// The size pool of a compressed list's stream (`start..end` in source 0).
|
||||
pool: Option<(usize, usize)>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// What reading one chunk header gives.
|
||||
enum Read {
|
||||
Chunk(Chunk),
|
||||
/// A redirect record whose body can't be found: the chunk is left out, its list read on.
|
||||
Lost,
|
||||
/// A redirect record into a data stream past a limit: the chunk is left out without the
|
||||
/// damage warning.
|
||||
PastLimit,
|
||||
/// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is
|
||||
/// left out with the limit warning.
|
||||
SharedPastLimit,
|
||||
}
|
||||
|
||||
/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I`
|
||||
/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names
|
||||
/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form
|
||||
/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28).
|
||||
pub(crate) fn form_version(form: [u8; 4]) -> Option<u16> {
|
||||
let [a, b, c, v] = form;
|
||||
match (&[a, b, c], v) {
|
||||
(b"cdr", b'8') => Some(801),
|
||||
(b"CDR" | b"cdr", b' ') => Some(300),
|
||||
(b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')),
|
||||
(b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)),
|
||||
(b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)),
|
||||
(b"CDT", b'A'..=b'Z') => Some(0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)?
|
||||
pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool {
|
||||
bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some()
|
||||
}
|
||||
|
||||
impl<'a> Index<'a> {
|
||||
pub(crate) fn build(input: &'a [u8], streams: Option<Streams<'a>>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Self, Error> {
|
||||
if input.len() > budget.limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
let mut r = Rd::new(input);
|
||||
if r.fourcc() != Some(*b"RIFF") {
|
||||
return Err(Error::NotCdr);
|
||||
}
|
||||
let declared = r.u32().ok_or(Error::NotCdr)? as usize;
|
||||
let form = r.fourcc().ok_or(Error::NotCdr)?;
|
||||
let version = form_version(form).ok_or(Error::NotCdr)?;
|
||||
// A file cut short keeps what it holds: its last chunk is truncated with a warning. A
|
||||
// length that ends inside the form type is damage too, and the chunks after it are read.
|
||||
let end = match declared.checked_add(8) {
|
||||
Some(e) if (12..=input.len()).contains(&e) => e,
|
||||
_ => {
|
||||
push(warn, Warning::Damaged);
|
||||
input.len()
|
||||
}
|
||||
};
|
||||
let left = Cell::new(budget.inflate_left());
|
||||
let mut ix = Index {
|
||||
input,
|
||||
inflated: Vec::new(),
|
||||
chunks: Vec::new(),
|
||||
form_version: version,
|
||||
streams,
|
||||
left,
|
||||
lists: Cell::default(),
|
||||
leaves: Cell::default(),
|
||||
shared_left: Cell::new(budget.limits.member),
|
||||
vrsn: None,
|
||||
};
|
||||
ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 });
|
||||
let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }];
|
||||
while let Some(p) = queue.pop() {
|
||||
ix.split(p, &mut queue, budget, warn)?;
|
||||
}
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
/// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data
|
||||
/// stream is read on first use.
|
||||
fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> {
|
||||
if src > 0 {
|
||||
let s = self.streams.as_ref()?;
|
||||
return s.get(src as usize - 1, &self.left)?.get(start..end);
|
||||
}
|
||||
let n = self.input.len();
|
||||
if end <= n {
|
||||
self.input.get(start..end)
|
||||
} else if start >= n {
|
||||
self.inflated.get(start - n..end - n)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn data(&self, c: &Chunk) -> &[u8] {
|
||||
let start = c.start as usize;
|
||||
match self.span(c.src, start, start + c.len as usize) {
|
||||
Some(b) => b,
|
||||
None => {
|
||||
if let Some(s) = &self.streams
|
||||
&& !self.past_limit(c.src)
|
||||
{
|
||||
s.note_damage();
|
||||
}
|
||||
&[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Was source `src` a data stream left out because it is past a limit? Its chunks are then
|
||||
/// left out with that warning alone.
|
||||
fn past_limit(&self, src: u32) -> bool {
|
||||
src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1))
|
||||
}
|
||||
|
||||
pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] {
|
||||
let first = c.first as usize;
|
||||
self.chunks.get(first..first + c.count as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn root(&self) -> Option<&Chunk> {
|
||||
self.chunks.first()
|
||||
}
|
||||
|
||||
/// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1,
|
||||
/// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names
|
||||
/// (R28). Letters count differently from the version 24 update on (R1), so when both name a
|
||||
/// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a
|
||||
/// file the 8.01 variant, whatever its `vrsn` chunk names (R1).
|
||||
pub(crate) fn version(&self) -> u16 {
|
||||
match self.vrsn.flatten() {
|
||||
_ if self.form_version == 801 => 801,
|
||||
Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v,
|
||||
Some(v) if self.form_version == 0 => v,
|
||||
Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v,
|
||||
_ => self.form_version,
|
||||
}
|
||||
}
|
||||
|
||||
/// The warnings for data streams that were left out.
|
||||
pub(crate) fn stream_warnings(&self, warn: &mut Vec<Warning>) {
|
||||
if let Some(s) = &self.streams {
|
||||
s.warnings(warn);
|
||||
}
|
||||
}
|
||||
|
||||
/// Split list `p` into its children, appended to the table together; their lists are queued.
|
||||
fn split(&mut self, p: Pending, queue: &mut Vec<Pending>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<(), Error> {
|
||||
let first = self.chunks.len();
|
||||
let mut at = p.start;
|
||||
let mut lists = Vec::new();
|
||||
while at < p.end {
|
||||
let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else {
|
||||
push(warn, Warning::Damaged);
|
||||
break;
|
||||
};
|
||||
if cut {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
at = next;
|
||||
// A redirect record whose body can't be found counts as well, so that lists redirected
|
||||
// to again and again can't repeat such records past the limit.
|
||||
budget.take_chunk()?;
|
||||
let chunk = match read {
|
||||
Read::Chunk(chunk) => chunk,
|
||||
Read::Lost => {
|
||||
push(warn, Warning::Damaged);
|
||||
continue;
|
||||
}
|
||||
Read::PastLimit => continue,
|
||||
Read::SharedPastLimit => {
|
||||
push(warn, Warning::TooDeep);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() {
|
||||
let at = chunk.start as usize;
|
||||
self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16()));
|
||||
}
|
||||
if chunk.id == LIST {
|
||||
lists.push(self.chunks.len());
|
||||
}
|
||||
self.chunks.push(chunk);
|
||||
}
|
||||
let count = (self.chunks.len() - first) as u32;
|
||||
if let Some(parent) = self.chunks.get_mut(p.entry) {
|
||||
parent.first = first as u32;
|
||||
parent.count = count;
|
||||
}
|
||||
for i in lists {
|
||||
let Some(c) = self.chunks.get(i).copied() else { continue };
|
||||
// From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read
|
||||
// whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn`
|
||||
// among them, are all read before this.
|
||||
if c.form == *b"stlt" && self.version() >= 700 {
|
||||
continue;
|
||||
}
|
||||
if p.depth + 1 > budget.limits.depth {
|
||||
push(warn, Warning::TooDeep);
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (c.start as usize, c.start as usize + c.len as usize);
|
||||
if c.form == CMPR && p.pool.is_none() {
|
||||
match self.inflate_cmpr(c.src, start, end) {
|
||||
Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }),
|
||||
Err(Error::Limit(what)) => return Err(Error::Limit(what)),
|
||||
Err(_) => push(warn, Warning::Damaged),
|
||||
}
|
||||
} else {
|
||||
queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a
|
||||
/// compressed stream the size field is an index into the size pool (R3); in a version 16+
|
||||
/// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a
|
||||
/// list cut short at `end`.
|
||||
fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> {
|
||||
let head = self.span(src, at, at.checked_add(8)?.min(end))?;
|
||||
let id: [u8; 4] = head.get(..4)?.try_into().ok()?;
|
||||
let raw = u32_at(head, 4)? as usize;
|
||||
let size = match pool {
|
||||
None => raw,
|
||||
Some((ps, pe)) => {
|
||||
let off = raw.checked_mul(4)?.checked_add(ps)?;
|
||||
(off.checked_add(4)? <= pe).then_some(())?;
|
||||
u32_at(self.span(0, off, off + 4)?, 0)? as usize
|
||||
}
|
||||
};
|
||||
let body = at + 8;
|
||||
// A list cut short by the end of its parent keeps the bytes it has, so the children
|
||||
// before the cut are read; the caller warns that it is damaged. Other chunks are lost.
|
||||
let (size, cut) = match body.checked_add(size) {
|
||||
Some(e) if e <= end => (size, false),
|
||||
_ if id == LIST => (end.checked_sub(body)?, true),
|
||||
_ => return None,
|
||||
};
|
||||
let next = (body + size + (size & 1)).min(end);
|
||||
if cut {
|
||||
return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true));
|
||||
}
|
||||
if self.streams.is_some() && pool.is_none() && size == REDIRECT {
|
||||
let read = match self.redirect(id, src, body) {
|
||||
Some(read) => read,
|
||||
None if self.redirect_past_limit(src, body) => Read::PastLimit,
|
||||
None => Read::Lost,
|
||||
};
|
||||
return Some((read, next, false));
|
||||
}
|
||||
Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false))
|
||||
}
|
||||
|
||||
/// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with
|
||||
/// its form type.
|
||||
fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option<Chunk> {
|
||||
let (form, start) = if id == LIST {
|
||||
let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?;
|
||||
(f, body + 4)
|
||||
} else {
|
||||
([0; 4], body)
|
||||
};
|
||||
let len = len - (start - body);
|
||||
Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 })
|
||||
}
|
||||
|
||||
/// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset
|
||||
/// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after
|
||||
/// the length. The body is not read again as a redirect record. `None` when the body can't
|
||||
/// be found.
|
||||
///
|
||||
/// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of
|
||||
/// the same package member, is left out, so that no list is split twice. Other chunks may
|
||||
/// share bytes: each one after the first to read them takes their length from the
|
||||
/// shared-bytes limit (the member limit), so that many redirects to one body can't decode it
|
||||
/// without end.
|
||||
fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option<Read> {
|
||||
let mut r = Rd::new(self.span(src, body, body + REDIRECT)?);
|
||||
let stream = r.u32()?;
|
||||
let len = r.u32()? as usize;
|
||||
if stream == INLINE {
|
||||
return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?;
|
||||
}
|
||||
let off = r.u32()? as usize;
|
||||
let streams = self.streams.as_ref()?;
|
||||
let size = streams.size(stream as usize)?;
|
||||
let end = off.checked_add(len).filter(|&e| e <= size)?;
|
||||
let member = streams.member_of(stream as usize)?;
|
||||
if id == LIST {
|
||||
if !claim(&self.lists, member, off, end) {
|
||||
return None;
|
||||
}
|
||||
} else if !claim(&self.leaves, member, off, end) {
|
||||
let left = self.shared_left.get();
|
||||
if len > left {
|
||||
return Some(Read::SharedPastLimit);
|
||||
}
|
||||
self.shared_left.set(left - len);
|
||||
}
|
||||
// Only a list's form type is read now; other bodies are read when the mapping asks.
|
||||
self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk)
|
||||
}
|
||||
|
||||
/// Does the redirect record at `body` of `src` point into a data stream past a limit?
|
||||
fn redirect_past_limit(&self, src: u32, body: usize) -> bool {
|
||||
let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0));
|
||||
stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1)))
|
||||
}
|
||||
|
||||
/// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk
|
||||
/// stream and the size pool, as ranges of source 0.
|
||||
fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> {
|
||||
let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?;
|
||||
let mut r = Rd::new(body);
|
||||
let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize;
|
||||
r.skip(4).ok_or(Error::Damaged("compressed list"))?;
|
||||
let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize;
|
||||
let block = |at: usize, len: usize| -> Result<&[u8], Error> {
|
||||
let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?;
|
||||
let mut h = Rd::new(b);
|
||||
if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) {
|
||||
return Err(Error::Damaged("compressed block"));
|
||||
}
|
||||
Ok(b.get(8..).unwrap_or_default())
|
||||
};
|
||||
let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?;
|
||||
let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec());
|
||||
let base = self.input.len();
|
||||
let stream = self.inflate(&first)?;
|
||||
let pool = self.inflate(&second)?;
|
||||
Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1)))
|
||||
}
|
||||
|
||||
/// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range
|
||||
/// there.
|
||||
fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> {
|
||||
let at = self.inflated.len();
|
||||
let left = self.left.get();
|
||||
let reader = flate2::read::ZlibDecoder::new(data);
|
||||
// One byte past what is left tells a stream that is too long from one that just fits.
|
||||
let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) {
|
||||
Ok(n) => n,
|
||||
Err(_) => {
|
||||
// What a stream inflated before it failed counts toward the limit too, so that
|
||||
// streams that fail late can't inflate past it again and again.
|
||||
let produced = self.inflated.len().saturating_sub(at);
|
||||
self.left.set(left.saturating_sub(produced));
|
||||
self.inflated.truncate(at);
|
||||
return Err(Error::Damaged("compressed block"));
|
||||
}
|
||||
};
|
||||
if got > left {
|
||||
self.inflated.truncate(at);
|
||||
return Err(Error::Limit("inflated size"));
|
||||
}
|
||||
self.left.set(left - got);
|
||||
if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize {
|
||||
return Err(Error::Limit("inflated size"));
|
||||
}
|
||||
Ok((at, at + got))
|
||||
}
|
||||
}
|
||||
|
||||
/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier
|
||||
/// redirect there took any of them. Empty ranges take nothing.
|
||||
fn claim(claimed: &Cell<BTreeMap<(usize, usize), usize>>, member: usize, start: usize, end: usize) -> bool {
|
||||
if start == end {
|
||||
return true;
|
||||
}
|
||||
let mut taken = claimed.take();
|
||||
let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start);
|
||||
let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end);
|
||||
let free = !before && !after;
|
||||
if free {
|
||||
taken.insert((member, start), end);
|
||||
}
|
||||
claimed.set(taken);
|
||||
free
|
||||
}
|
||||
|
||||
/// Add `w` to the warnings once.
|
||||
pub(crate) fn push(warn: &mut Vec<Warning>, w: Warning) {
|
||||
if !warn.contains(&w) {
|
||||
warn.push(w);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a
|
||||
//! style gives the objects that name it and have no fill or outline argument of their own.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::Error;
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::limits::Budget;
|
||||
|
||||
/// One style: its parent, and the fill and outline table entries it names (0: none).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Style {
|
||||
parent: u32,
|
||||
fill: u32,
|
||||
outline: u32,
|
||||
}
|
||||
|
||||
/// The styles of a drawing: for each style id, the fill and outline records it gives, its
|
||||
/// parents' included.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Styles {
|
||||
fills: HashMap<u32, u32>,
|
||||
outlines: HashMap<u32, u32>,
|
||||
}
|
||||
|
||||
impl Styles {
|
||||
/// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't
|
||||
/// parse to its end. Its fill and outline entries and its styles count toward the chunks a
|
||||
/// read takes.
|
||||
pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result<Option<Styles>, Error> {
|
||||
let mut limit = None;
|
||||
let styles = parse(b, version, &mut |n| match budget.take_chunks(n) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
limit = Some(e);
|
||||
false
|
||||
}
|
||||
});
|
||||
match limit {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(styles),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill record that style `id` gives.
|
||||
pub(crate) fn fill(&self, id: u32) -> Option<u32> {
|
||||
self.fills.get(&id).copied()
|
||||
}
|
||||
|
||||
/// The outline record that style `id` gives.
|
||||
pub(crate) fn outline(&self, id: u32) -> Option<u32> {
|
||||
self.outlines.get(&id).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// The style table in `b`. `take` is asked for each count of entries or styles before they are
|
||||
/// read; a `false` stops the read.
|
||||
fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option<Styles> {
|
||||
let mut r = Rd::new(b);
|
||||
let count = r.u32()? as usize;
|
||||
if count == 0 {
|
||||
return (r.left() == 0).then(Styles::default);
|
||||
}
|
||||
// Fill entries carry 48 more bytes from version 13.
|
||||
let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?;
|
||||
let outlines = table(&mut r, 12, take)?;
|
||||
// The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets,
|
||||
// indents, hyphenation and drop caps, and from version 8.01 one more.
|
||||
skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?;
|
||||
skip_table(&mut r, 12)?;
|
||||
skip_table(&mut r, 52)?;
|
||||
skip_table(&mut r, 152)?;
|
||||
skip_table(&mut r, 784)?;
|
||||
let bullets = r.u32()?;
|
||||
for _ in 0..bullets {
|
||||
bullet(&mut r, version)?;
|
||||
}
|
||||
skip_table(&mut r, 28)?;
|
||||
skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?;
|
||||
skip_table(&mut r, 28)?;
|
||||
if version >= 801 {
|
||||
skip_table(&mut r, 12)?;
|
||||
}
|
||||
// Each style is at least 32 bytes.
|
||||
if count > r.left() / 32 || !take(count) {
|
||||
return None;
|
||||
}
|
||||
let mut styles = HashMap::new();
|
||||
for _ in 0..count {
|
||||
let (id, s) = style(&mut r, version)?;
|
||||
styles.entry(id).or_insert(s);
|
||||
}
|
||||
if r.left() != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut work = 0;
|
||||
Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) })
|
||||
}
|
||||
|
||||
/// For each style, the record of `table` that its own entry names, or the nearest parent's where
|
||||
/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a
|
||||
/// chain of any length takes time in proportion to the styles; a chain that comes back to a style
|
||||
/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited
|
||||
/// and forgotten.
|
||||
fn resolve(styles: &HashMap<u32, Style>, table: &HashMap<u32, u32>, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap<u32, u32> {
|
||||
// `None`: resolved to no record.
|
||||
let mut done: HashMap<u32, Option<u32>> = HashMap::new();
|
||||
let mut path = Vec::new();
|
||||
let mut on_path = HashSet::new();
|
||||
for &start in styles.keys() {
|
||||
let mut id = start;
|
||||
let found = loop {
|
||||
*work += 1;
|
||||
if let Some(&known) = done.get(&id) {
|
||||
break known;
|
||||
}
|
||||
let Some(s) = styles.get(&id) else { break None };
|
||||
// Back at a style on this path: a cycle.
|
||||
if !on_path.insert(id) {
|
||||
break None;
|
||||
}
|
||||
path.push(id);
|
||||
match entry(s) {
|
||||
0 => id = s.parent,
|
||||
e => break table.get(&e).copied(),
|
||||
}
|
||||
};
|
||||
for id in path.drain(..) {
|
||||
*work += 1;
|
||||
on_path.remove(&id);
|
||||
done.insert(id, found);
|
||||
}
|
||||
}
|
||||
done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect()
|
||||
}
|
||||
|
||||
/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id.
|
||||
fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option<HashMap<u32, u32>> {
|
||||
let n = r.u32()? as usize;
|
||||
if n > r.left() / size || !take(n) {
|
||||
return None;
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
for _ in 0..n {
|
||||
let e = r.bytes(size)?;
|
||||
out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A table of a u32 count and entries of `size` bytes, passed over.
|
||||
fn skip_table(r: &mut Rd, size: usize) -> Option<()> {
|
||||
let n = r.u32()? as usize;
|
||||
r.skip(n.checked_mul(size)?)
|
||||
}
|
||||
|
||||
/// A bullet record, passed over: its length depends on a u32 inside it.
|
||||
fn bullet(r: &mut Rd, version: u16) -> Option<()> {
|
||||
r.skip(40)?;
|
||||
if version >= 1300 {
|
||||
if version >= 1400 {
|
||||
r.skip(4)?;
|
||||
}
|
||||
let more = r.u32()?;
|
||||
return r.skip(if more != 0 { 68 } else { 12 });
|
||||
}
|
||||
r.skip(if version >= 1000 { 28 } else { 20 })?;
|
||||
let more = r.u32()?;
|
||||
if more != 0 {
|
||||
r.skip(8)?;
|
||||
}
|
||||
r.skip(8)
|
||||
}
|
||||
|
||||
/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before
|
||||
/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text
|
||||
/// styles (kinds 2 and 3).
|
||||
fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> {
|
||||
let kind = r.u32()?;
|
||||
let (id, parent) = (r.u32()?, r.u32()?);
|
||||
r.skip(8)?;
|
||||
let len = r.u32()? as usize;
|
||||
r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?;
|
||||
let (fill, outline) = (r.u32()?, r.u32()?);
|
||||
if kind > 1 {
|
||||
r.skip(if version >= 801 { 20 } else { 16 })?;
|
||||
}
|
||||
if kind > 2 {
|
||||
r.skip(20)?;
|
||||
}
|
||||
Some((id, Style { parent, fill, outline }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Limits;
|
||||
use crate::synth::{self, V};
|
||||
|
||||
fn read(b: &[u8], version: u16) -> Option<Styles> {
|
||||
Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_that_name_each_other_as_parents_end() {
|
||||
let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }];
|
||||
let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap();
|
||||
assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() {
|
||||
let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }];
|
||||
chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 }));
|
||||
let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap();
|
||||
assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None));
|
||||
}
|
||||
|
||||
/// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000
|
||||
/// other styles no more work than the styles they visit.
|
||||
#[test]
|
||||
fn one_long_walk_does_not_slow_the_walks_after_it() {
|
||||
let mut styles: HashMap<u32, Style> = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect();
|
||||
styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 })));
|
||||
let table = HashMap::from([(0x100, 7)]);
|
||||
let mut work = 0;
|
||||
let fills = resolve(&styles, &table, |s| s.fill, &mut work);
|
||||
assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000));
|
||||
assert!(work <= 4 * styles.len(), "{work}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_missing_from_its_table_names_no_record() {
|
||||
let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }];
|
||||
let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap();
|
||||
assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_past_the_body_do_not_parse() {
|
||||
let mut b = synth::stlt_body(V(900), &[], &[], &[], false);
|
||||
b[..4].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(read(&b, 900).is_none());
|
||||
let empty = 0u32.to_le_bytes();
|
||||
assert!(read(&empty, 900).is_some());
|
||||
assert!(read(&[], 900).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_and_styles_count_toward_the_chunk_limit() {
|
||||
let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect();
|
||||
let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false);
|
||||
let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() });
|
||||
assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count")));
|
||||
let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() });
|
||||
assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some()));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,287 @@
|
||||
//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53
|
||||
//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files.
|
||||
|
||||
/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53).
|
||||
pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut out = id.to_vec();
|
||||
out.extend((body.len() as u32).to_le_bytes());
|
||||
out.extend(body);
|
||||
if body.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A `LIST` chunk of form `form`.
|
||||
pub fn list(form: &[u8; 4], children: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut body = form.to_vec();
|
||||
body.extend(children.concat());
|
||||
chunk(b"LIST", &body)
|
||||
}
|
||||
|
||||
/// The RIFF form `CMX1` around `children`.
|
||||
pub fn riff(children: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut body = b"CMX1".to_vec();
|
||||
body.extend(children.concat());
|
||||
chunk(b"RIFF", &body)
|
||||
}
|
||||
|
||||
/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size
|
||||
/// of a coordinate unit. The header string and the system name, which the reader doesn't read,
|
||||
/// are left as zeros.
|
||||
pub fn cont(coord: u8, meters: f64) -> Vec<u8> {
|
||||
let mut c = vec![0u8; 180];
|
||||
c[48] = b'2';
|
||||
c[52] = coord;
|
||||
c[54] = b'2';
|
||||
c[64..72].copy_from_slice(&meters.to_le_bytes());
|
||||
chunk(b"cont", &c)
|
||||
}
|
||||
|
||||
/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55).
|
||||
pub fn field(tag: u8, data: &[u8]) -> Vec<u8> {
|
||||
let mut f = vec![tag];
|
||||
f.extend(((data.len() + 3) as u16).to_le_bytes());
|
||||
f.extend(data);
|
||||
f
|
||||
}
|
||||
|
||||
/// A field list: the fields, then 0xff (R55).
|
||||
pub fn fields(fields: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut l = fields.concat();
|
||||
l.push(0xff);
|
||||
l
|
||||
}
|
||||
|
||||
/// A table chunk: a u16 count, then the entries (field lists) (R55).
|
||||
pub fn table(id: &[u8; 4], entries: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut d = (entries.len() as u16).to_le_bytes().to_vec();
|
||||
d.extend(entries.concat());
|
||||
chunk(id, &d)
|
||||
}
|
||||
|
||||
/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2
|
||||
/// (R56).
|
||||
pub fn color(model: u8, values: &[u8]) -> Vec<u8> {
|
||||
fields(&[field(1, &[model, 5]), field(2, values)])
|
||||
}
|
||||
|
||||
/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and
|
||||
/// the four value bytes `v` (R56).
|
||||
pub fn color_record(model: u16, v: [u8; 4]) -> Vec<u8> {
|
||||
color_record_named(model, v, None)
|
||||
}
|
||||
|
||||
/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units)
|
||||
/// after the color when `name` is given (R56).
|
||||
pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec<u8> {
|
||||
let mut part = vec![1u8];
|
||||
part.extend(12u32.to_le_bytes());
|
||||
part.extend(model.to_le_bytes());
|
||||
part.extend(5u16.to_le_bytes());
|
||||
part.extend([0; 4]);
|
||||
part.extend(v);
|
||||
if let Some(name) = name {
|
||||
let units: Vec<u16> = name.encode_utf16().collect();
|
||||
part.push(3);
|
||||
part.extend((4 + 2 * units.len() as u32).to_le_bytes());
|
||||
part.extend((units.len() as u32).to_le_bytes());
|
||||
part.extend(units.iter().flat_map(|u| u.to_le_bytes()));
|
||||
}
|
||||
let mut rec = (part.len() as u32).to_le_bytes().to_vec();
|
||||
rec.extend(part);
|
||||
fields(&[field(10, &rec)])
|
||||
}
|
||||
|
||||
/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the
|
||||
/// identity matrix.
|
||||
pub fn pen(width: u32) -> Vec<u8> {
|
||||
let mut d = width.to_le_bytes().to_vec();
|
||||
d.extend(100u16.to_le_bytes());
|
||||
d.extend(0i32.to_le_bytes());
|
||||
d.extend(1u16.to_le_bytes());
|
||||
fields(&[field(1, &d)])
|
||||
}
|
||||
|
||||
/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits).
|
||||
pub fn line_type(flags: u8, caps_join: u8) -> Vec<u8> {
|
||||
fields(&[field(1, &[flags, caps_join])])
|
||||
}
|
||||
|
||||
/// A dash pattern entry (R57): the lengths in outline widths.
|
||||
pub fn dashes(lengths: &[u16]) -> Vec<u8> {
|
||||
let mut d = (lengths.len() as u16).to_le_bytes().to_vec();
|
||||
d.extend(lengths.iter().flat_map(|l| l.to_le_bytes()));
|
||||
fields(&[field(1, &d)])
|
||||
}
|
||||
|
||||
/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and
|
||||
/// dash pattern.
|
||||
pub fn outline(parts: [u16; 6]) -> Vec<u8> {
|
||||
fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())])
|
||||
}
|
||||
|
||||
/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each).
|
||||
pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec<u8> {
|
||||
let mut d = (pairs.len() as u16).to_le_bytes().to_vec();
|
||||
for (s, e) in pairs {
|
||||
d.extend(s.to_le_bytes());
|
||||
d.extend(e.to_le_bytes());
|
||||
}
|
||||
chunk(b"rota", &d)
|
||||
}
|
||||
|
||||
/// An instruction in the short form: a u16 size counting the whole instruction, the code, the
|
||||
/// body (R60).
|
||||
pub fn instr(code: i16, body: &[u8]) -> Vec<u8> {
|
||||
let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec();
|
||||
i.extend(code.to_le_bytes());
|
||||
i.extend(body);
|
||||
i
|
||||
}
|
||||
|
||||
/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code,
|
||||
/// the body (R60).
|
||||
pub fn long_instr(code: i16, body: &[u8]) -> Vec<u8> {
|
||||
let mut i = 0xFFFFu16.to_le_bytes().to_vec();
|
||||
i.extend(((body.len() + 8) as u32).to_le_bytes());
|
||||
i.extend(code.to_le_bytes());
|
||||
i.extend(body);
|
||||
i
|
||||
}
|
||||
|
||||
/// Begin a page (R61), with its width and height in coordinate units in field 4 when given.
|
||||
pub fn begin_page(size: Option<(u32, u32)>) -> Vec<u8> {
|
||||
let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])];
|
||||
if let Some((w, h)) = size {
|
||||
let mut d = w.to_le_bytes().to_vec();
|
||||
d.extend(h.to_le_bytes());
|
||||
f.push(field(4, &d));
|
||||
}
|
||||
instr(9, &fields(&f))
|
||||
}
|
||||
|
||||
/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom
|
||||
/// edges in field 1.
|
||||
pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec<u8> {
|
||||
let mut d = vec![1, 0, 0, 0, 0, 0];
|
||||
for v in [left, top, right, bottom] {
|
||||
d.extend(v.to_le_bytes());
|
||||
}
|
||||
instr(9, &fields(&[field(1, &d)]))
|
||||
}
|
||||
|
||||
/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in
|
||||
/// field 4 when `wide` is given.
|
||||
pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec<u8> {
|
||||
let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
d.extend((name.len() as u16).to_le_bytes());
|
||||
d.extend(name.bytes());
|
||||
let mut f = vec![field(1, &d)];
|
||||
if let Some(w) = wide {
|
||||
let units: Vec<u16> = w.encode_utf16().collect();
|
||||
let mut d = (units.len() as u32).to_le_bytes().to_vec();
|
||||
d.extend(units.iter().flat_map(|u| u.to_le_bytes()));
|
||||
f.push(field(4, &d));
|
||||
}
|
||||
instr(11, &fields(&f))
|
||||
}
|
||||
|
||||
pub fn end_layer() -> Vec<u8> {
|
||||
instr(12, &[])
|
||||
}
|
||||
|
||||
pub fn end_page() -> Vec<u8> {
|
||||
instr(10, &[])
|
||||
}
|
||||
|
||||
pub fn begin_group() -> Vec<u8> {
|
||||
instr(13, &fields(&[field(1, &[0; 26])]))
|
||||
}
|
||||
|
||||
pub fn end_group() -> Vec<u8> {
|
||||
instr(14, &[])
|
||||
}
|
||||
|
||||
/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based
|
||||
/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit.
|
||||
pub fn attrs(fill: Option<u16>, outline: Option<u16>, lens: bool) -> Vec<u8> {
|
||||
let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2);
|
||||
let mut a = vec![mask];
|
||||
if let Some(c) = fill {
|
||||
let mut v = 1u16.to_le_bytes().to_vec();
|
||||
let mut uniform = c.to_le_bytes().to_vec();
|
||||
uniform.extend(0u16.to_le_bytes());
|
||||
v.extend(fields(&[field(1, &uniform)]));
|
||||
a.extend(fields(&[field(1, &v)]));
|
||||
}
|
||||
if let Some(o) = outline {
|
||||
a.extend(fields(&[field(1, &o.to_le_bytes())]));
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Rendering attributes with a fill of type `kind` and no settings of its own.
|
||||
pub fn attrs_fill_type(kind: u16) -> Vec<u8> {
|
||||
let mut a = vec![1u8];
|
||||
a.extend(fields(&[field(1, &kind.to_le_bytes())]));
|
||||
a
|
||||
}
|
||||
|
||||
/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes.
|
||||
pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec<u8> {
|
||||
let mut g = (points.len() as u16).to_le_bytes().to_vec();
|
||||
for (x, y) in points {
|
||||
g.extend(x.to_le_bytes());
|
||||
g.extend(y.to_le_bytes());
|
||||
}
|
||||
g.extend(types);
|
||||
instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])]))
|
||||
}
|
||||
|
||||
/// A closed square of side `side` with its lower left corner at (`x`, `y`).
|
||||
pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec<u8> {
|
||||
curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48])
|
||||
}
|
||||
|
||||
/// A `page` chunk of `instructions`.
|
||||
pub fn page(instructions: &[Vec<u8>]) -> Vec<u8> {
|
||||
chunk(b"page", &instructions.concat())
|
||||
}
|
||||
|
||||
/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record,
|
||||
/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none,
|
||||
/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair.
|
||||
pub fn tables() -> Vec<Vec<u8>> {
|
||||
vec![
|
||||
table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]),
|
||||
table(b"rpen", &[pen(5_000), pen(10_000)]),
|
||||
table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]),
|
||||
table(b"rdot", &[dashes(&[3, 1])]),
|
||||
table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]),
|
||||
arrowheads(&[(0, 0)]),
|
||||
]
|
||||
}
|
||||
|
||||
/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a
|
||||
/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black
|
||||
/// square drawn last. Units are 0.1 µm.
|
||||
pub fn sample() -> Vec<u8> {
|
||||
let p = page(&[
|
||||
begin_page(Some((2_100_000, 2_970_000))),
|
||||
begin_layer("Art", None),
|
||||
square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000),
|
||||
begin_group(),
|
||||
square(&attrs(Some(2), Some(2), false), 0, 0, 100_000),
|
||||
square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000),
|
||||
end_group(),
|
||||
end_layer(),
|
||||
begin_layer("Top", Some("Top")),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 10_000),
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let mut children = vec![cont(b'4', 1e-7), p];
|
||||
children.extend(tables());
|
||||
riff(&children)
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A
|
||||
//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes
|
||||
//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill,
|
||||
//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one
|
||||
//! layer and keeps no groups.
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::geometry;
|
||||
use crate::layout::{self, Profile};
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape};
|
||||
use crate::records::{self, coord, fixed};
|
||||
use crate::riff::push;
|
||||
use crate::{Error, Warning};
|
||||
|
||||
/// The header: the signature, a marker byte, a zero and five u32 offsets (R40).
|
||||
const HEADER: usize = 28;
|
||||
/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2.
|
||||
const MARKERS: [u8; 3] = *b"elm";
|
||||
/// Where the page's box lies after the start of the settings (R41).
|
||||
const PAGE_BOX: usize = 2;
|
||||
/// The bytes of a group or layer record (R42).
|
||||
const GROUP: usize = 28;
|
||||
/// The u32 that starts every record (R42).
|
||||
const RECORD_START: u32 = 24;
|
||||
/// The flag bit, in byte 26, of a drawn object (R42).
|
||||
const DRAWN: u8 = 0x40;
|
||||
/// The bytes after a drawn object's body size (R42).
|
||||
const AFTER_BODY: usize = 32;
|
||||
/// Where a drawn object's fields lie (R43, R44).
|
||||
const POINT: usize = 32;
|
||||
const KIND: usize = 60;
|
||||
const OUTLINED: usize = 67;
|
||||
const OUTLINE_WIDTH: usize = 68;
|
||||
const OUTLINE_COLOR: usize = 74;
|
||||
|
||||
/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Fields {
|
||||
fill_kind: usize,
|
||||
shape: usize,
|
||||
}
|
||||
|
||||
impl Fields {
|
||||
fn of(marker: u8) -> Self {
|
||||
if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } }
|
||||
}
|
||||
|
||||
/// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size.
|
||||
fn least(self) -> usize {
|
||||
self.shape + 4
|
||||
}
|
||||
}
|
||||
/// Object types (R43).
|
||||
const RECTANGLE: u8 = 0;
|
||||
const ELLIPSE: u8 = 1;
|
||||
const CURVE: u8 = 2;
|
||||
const TEXT: u8 = 3;
|
||||
|
||||
/// Where the settings start, and where the records start and end, when `b` has a `WL` header
|
||||
/// whose offsets fit the file.
|
||||
fn header(b: &[u8]) -> Option<(usize, usize, usize)> {
|
||||
if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 {
|
||||
return None;
|
||||
}
|
||||
let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize);
|
||||
(settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end))
|
||||
}
|
||||
|
||||
/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the
|
||||
/// marker byte, the zero after it and the record offsets must fit too.
|
||||
pub(crate) fn is_wl(b: &[u8]) -> bool {
|
||||
header(b).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
|
||||
let (settings, start, end) = header(b).ok_or(Error::NotCdr)?;
|
||||
let marker = b.get(2).copied().ok_or(Error::NotCdr)?;
|
||||
let fields = Fields::of(marker);
|
||||
// Lengths are i16 in 1/1000 inch, as in version 3 (R5).
|
||||
let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?;
|
||||
let mut warn = Vec::new();
|
||||
let mut objects = Vec::new();
|
||||
let mut at = start;
|
||||
// Every step takes at least a group record's bytes, so the file's size bounds the steps.
|
||||
while end - at >= GROUP {
|
||||
budget.take_chunk()?;
|
||||
// A record that doesn't start as records do is past one whose length isn't known.
|
||||
if u32_at(b, at) != Some(RECORD_START) {
|
||||
break;
|
||||
}
|
||||
if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) {
|
||||
at += GROUP;
|
||||
continue;
|
||||
}
|
||||
// A drawn object of another type than rectangle, ellipse, curve and text doesn't say its
|
||||
// length in the same way, so the records after it can't be found.
|
||||
if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) {
|
||||
push(&mut warn, Warning::UnsupportedObjects);
|
||||
at = end;
|
||||
break;
|
||||
}
|
||||
let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY);
|
||||
let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else {
|
||||
push(&mut warn, Warning::Damaged);
|
||||
at = end;
|
||||
break;
|
||||
};
|
||||
at += len;
|
||||
if !budget.take_object() {
|
||||
push(&mut warn, Warning::TooDeep);
|
||||
at = end;
|
||||
break;
|
||||
}
|
||||
objects.extend(object(rec, fields, &p, budget, &mut warn));
|
||||
}
|
||||
if at != end {
|
||||
push(&mut warn, Warning::Damaged);
|
||||
}
|
||||
let version = if marker == b'e' { 100 } else { 200 };
|
||||
let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() };
|
||||
let pages = vec![Page { size: None, layers: vec![layer] }];
|
||||
Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
|
||||
}
|
||||
|
||||
/// The page's size from its box (R41): left, top, right and bottom around the page's centre.
|
||||
fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> {
|
||||
let mut r = Rd::at(b, settings + PAGE_BOX);
|
||||
let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let (w, h) = ((right - left).abs(), (top - bottom).abs());
|
||||
(w > 0.0 && h > 0.0).then_some((w, h))
|
||||
}
|
||||
|
||||
/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object
|
||||
/// of another type and for a shape that can't be read.
|
||||
fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Object> {
|
||||
// A curve left out at the coordinate limit is not damage.
|
||||
budget.coordinates_refused();
|
||||
let read = shape(rec, fields, p, budget, warn);
|
||||
if read.is_none() && !budget.coordinates_refused() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
read?.map(|s| Object::Shape(Box::new(s)))
|
||||
}
|
||||
|
||||
/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object
|
||||
/// the reader leaves out, with its warning.
|
||||
fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Option<Shape>> {
|
||||
let k = p.unit();
|
||||
let mut r = Rd::at(rec, POINT);
|
||||
let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?));
|
||||
// x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point.
|
||||
let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?);
|
||||
let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]);
|
||||
let body = rec.get(fields.shape..)?;
|
||||
let geometry = match *rec.get(KIND)? {
|
||||
RECTANGLE => rect(body, p)?,
|
||||
ELLIPSE => {
|
||||
let mut s = Rd::new(body);
|
||||
let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?);
|
||||
// Two angles follow. No source confirms how they make an arc, so an ellipse whose
|
||||
// angles differ is left out; one whose angles are missing is damage.
|
||||
let (from, to) = (s.i16()?, s.i16()?);
|
||||
if from != to {
|
||||
push(warn, Warning::UnsupportedObjects);
|
||||
return Some(None);
|
||||
}
|
||||
Geometry::Ellipse { w, h }
|
||||
}
|
||||
CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?),
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedObjects);
|
||||
return Some(None);
|
||||
}
|
||||
};
|
||||
let color_at = |at: usize, warn: &mut Vec<Warning>| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn));
|
||||
let fill = match *rec.get(fields.fill_kind)? {
|
||||
0 => None,
|
||||
1 => Some(color_at(fields.fill_kind + 1, warn)?),
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedFills);
|
||||
None
|
||||
}
|
||||
};
|
||||
let outline = if *rec.get(OUTLINED)? != 0 {
|
||||
let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k;
|
||||
Some(Outline {
|
||||
width,
|
||||
color: color_at(OUTLINE_COLOR, warn)?,
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
dashes: Vec::new(),
|
||||
behind_fill: false,
|
||||
scale_with: false,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(Some(Shape::new(geometry, matrix, fill, outline)))
|
||||
}
|
||||
|
||||
/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most
|
||||
/// half the shorter side.
|
||||
fn rect(body: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
let mut r = Rd::new(body);
|
||||
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0);
|
||||
Some(Geometry::Rect { w, h, radii: [radius; 4] })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Limits;
|
||||
use crate::model::Color;
|
||||
use crate::synth::{self, WlShape};
|
||||
|
||||
fn read(b: &[u8]) -> Result<Drawing, Error> {
|
||||
drawing(b, &mut Budget::new(Limits::default()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_header_is_taken_only_when_its_offsets_fit() {
|
||||
let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]);
|
||||
assert!(is_wl(&file));
|
||||
// The two letters, a marker and a zero are not enough.
|
||||
assert!(!is_wl(b"WLe\0"));
|
||||
assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets"));
|
||||
let with = |at: usize, v: u32| {
|
||||
let mut f = file.clone();
|
||||
f[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
f
|
||||
};
|
||||
// Records that start inside the header, start after their end, or end past the file.
|
||||
assert!(!is_wl(&with(8, 27)));
|
||||
assert!(!is_wl(&with(8, file.len() as u32)));
|
||||
assert!(!is_wl(&with(12, file.len() as u32 + 1)));
|
||||
// Settings that start inside the header or after the records.
|
||||
assert!(!is_wl(&with(4, 27)));
|
||||
assert!(!is_wl(&with(4, 65)));
|
||||
let mut other = file.clone();
|
||||
other[2] = b'x';
|
||||
assert!(!is_wl(&other));
|
||||
// No sample shows the marker `d`, so it is not taken.
|
||||
other[2] = b'd';
|
||||
assert!(!is_wl(&other));
|
||||
for marker in *b"lm" {
|
||||
assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()])));
|
||||
}
|
||||
other[2] = b'e';
|
||||
other[3] = 1;
|
||||
assert!(!is_wl(&other));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() {
|
||||
let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]);
|
||||
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black)));
|
||||
for marker in *b"elm" {
|
||||
let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect));
|
||||
// Version 2 files start their settings after a picture, not after the header.
|
||||
assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e');
|
||||
let d = read(&file).unwrap();
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 0.02;
|
||||
assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![]));
|
||||
assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size);
|
||||
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
|
||||
assert!(
|
||||
matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)),
|
||||
"{}",
|
||||
marker as char
|
||||
);
|
||||
assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char);
|
||||
assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawn_object_is_marked_by_its_flag_bit() {
|
||||
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None);
|
||||
let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]);
|
||||
// Files with the marker `l` set another flag bit beside it.
|
||||
file[64 + 26] = 0xc0;
|
||||
let d = read(&file).unwrap();
|
||||
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walk_stops_where_records_can_no_longer_be_found() {
|
||||
let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None);
|
||||
// An object of another type doesn't give its length in the same way.
|
||||
let mut other = rect();
|
||||
other[KIND] = 0xff;
|
||||
let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap();
|
||||
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects]));
|
||||
// A record that doesn't start as records do.
|
||||
let mut lost = rect();
|
||||
lost[0] = 0x84;
|
||||
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap();
|
||||
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() {
|
||||
let p = layout::for_version(300).unwrap();
|
||||
let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
|
||||
let radius_of = |b: &[u8]| match rect(b, &p) {
|
||||
Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0],
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9);
|
||||
for radius in [300, -5, 0] {
|
||||
assert_eq!(radius_of(&body(radius)), 0.0, "{radius}");
|
||||
}
|
||||
// A record that ends after the size has square corners.
|
||||
assert_eq!(radius_of(&body(200)[..4]), 0.0);
|
||||
assert_eq!(rect(&body(200)[..3], &p), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() {
|
||||
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None);
|
||||
let mut short = rect.clone();
|
||||
// A body size that leaves less than the fixed fields.
|
||||
short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes());
|
||||
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
assert_eq!(d.warnings, vec![Warning::Damaged]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ellipse_without_its_angles_is_damage() {
|
||||
let ellipse =
|
||||
synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None);
|
||||
let mut cut = ellipse.clone();
|
||||
// A body size that ends the record after the ellipse's width and height.
|
||||
cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes());
|
||||
cut.truncate(Fields::of(b'e').least());
|
||||
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
assert_eq!(d.warnings, vec![Warning::Damaged]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_types_other_than_uniform_and_unknown_inks_are_named() {
|
||||
let mut textured =
|
||||
synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None);
|
||||
let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap();
|
||||
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
|
||||
assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None }));
|
||||
assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks]));
|
||||
textured[Fields::of(b'e').fill_kind] = 5;
|
||||
let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap();
|
||||
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
|
||||
assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored
|
||||
//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted
|
||||
//! members are refused; so are directories whose members overlap or repeat a name.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::io::Read as _;
|
||||
|
||||
use crate::Error;
|
||||
use crate::bytes::Rd;
|
||||
|
||||
/// End of central directory record: signature and fixed length.
|
||||
const END: u32 = 0x0605_4b50;
|
||||
const END_LEN: usize = 22;
|
||||
/// The longest archive comment, which the end record may be followed by.
|
||||
const MAX_COMMENT: usize = 0xFFFF;
|
||||
/// ZIP64 end of central directory locator, 20 bytes before the end record when present.
|
||||
const ZIP64_LOCATOR: u32 = 0x0706_4b50;
|
||||
/// Central directory header: signature and fixed length.
|
||||
const CENTRAL: u32 = 0x0201_4b50;
|
||||
const CENTRAL_LEN: usize = 46;
|
||||
/// Local file header: signature and fixed length.
|
||||
const LOCAL: u32 = 0x0403_4b50;
|
||||
const LOCAL_LEN: usize = 30;
|
||||
/// General purpose flag bit 0: the member is encrypted.
|
||||
const ENCRYPTED: u16 = 1;
|
||||
const STORED: u16 = 0;
|
||||
const DEFLATED: u16 = 8;
|
||||
/// What members packed by another method are refused as.
|
||||
const OTHER_METHODS: &str = "package compression methods other than storing and deflate";
|
||||
|
||||
/// One member, as the central directory and its local header give it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Entry<'a> {
|
||||
name: &'a [u8],
|
||||
flags: u16,
|
||||
method: u16,
|
||||
crc: u32,
|
||||
packed: usize,
|
||||
size: usize,
|
||||
/// Where its local header starts and where its packed bytes start.
|
||||
header: usize,
|
||||
data: usize,
|
||||
}
|
||||
|
||||
/// An archive's directory over its bytes.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Archive<'a> {
|
||||
bytes: &'a [u8],
|
||||
entries: Vec<Entry<'a>>,
|
||||
/// The entries in name order, for lookups.
|
||||
by_name: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Does `bytes` start with a local file header?
|
||||
pub(crate) fn is_zip(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"PK\x03\x04")
|
||||
}
|
||||
|
||||
impl<'a> Archive<'a> {
|
||||
/// The directory of `bytes`, holding at most `max_entries` members.
|
||||
pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result<Self, Error> {
|
||||
let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?;
|
||||
if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) {
|
||||
return Err(Error::Unsupported("ZIP64 packages"));
|
||||
}
|
||||
let mut r = Rd::at(bytes, end + 4);
|
||||
let dir = || Error::Damaged("package directory");
|
||||
let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?);
|
||||
let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?);
|
||||
let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?);
|
||||
if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX {
|
||||
return Err(Error::Unsupported("ZIP64 packages"));
|
||||
}
|
||||
if disk != 0 || dir_disk != 0 || on_disk != total {
|
||||
return Err(Error::Unsupported("packages split across files"));
|
||||
}
|
||||
let total = usize::from(total);
|
||||
if total > max_entries {
|
||||
return Err(Error::Limit("package member count"));
|
||||
}
|
||||
let (dir_at, dir_len) = (dir_at as usize, dir_len as usize);
|
||||
let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?;
|
||||
let mut r = Rd::at(bytes, dir_at);
|
||||
let mut entries = Vec::with_capacity(total);
|
||||
for _ in 0..total {
|
||||
let e = central_entry(bytes, &mut r, dir_end)?;
|
||||
entries.push(e);
|
||||
}
|
||||
// Each member's bytes end before the next member's header and before the directory.
|
||||
let mut order: Vec<&Entry> = entries.iter().collect();
|
||||
order.sort_unstable_by_key(|e| e.header);
|
||||
for (i, e) in order.iter().enumerate() {
|
||||
let stop = order.get(i + 1).map_or(dir_at, |n| n.header);
|
||||
if e.data.checked_add(e.packed).is_none_or(|x| x > stop) {
|
||||
return Err(Error::Damaged("package members overlap"));
|
||||
}
|
||||
}
|
||||
let mut by_name: Vec<usize> = (0..entries.len()).collect();
|
||||
by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name));
|
||||
let name = |i: &usize| entries.get(*i).map(|e| e.name);
|
||||
if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) {
|
||||
return Err(Error::Damaged("package member named twice"));
|
||||
}
|
||||
Ok(Archive { bytes, entries, by_name })
|
||||
}
|
||||
|
||||
/// The member named `name`.
|
||||
pub(crate) fn find(&self, name: &[u8]) -> Option<usize> {
|
||||
let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?;
|
||||
self.by_name.get(at).copied()
|
||||
}
|
||||
|
||||
/// The size member `i`'s directory entry gives.
|
||||
pub(crate) fn size(&self, i: usize) -> usize {
|
||||
self.entries.get(i).map_or(0, |e| e.size)
|
||||
}
|
||||
|
||||
/// How many members the archive holds.
|
||||
pub(crate) fn count(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
/// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0.
|
||||
pub(crate) fn inflate_cost(&self, i: usize) -> usize {
|
||||
self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size)
|
||||
}
|
||||
|
||||
/// An error when member `i` is encrypted or packed by a method other than storing or deflate.
|
||||
pub(crate) fn check(&self, i: usize) -> Result<(), Error> {
|
||||
let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?;
|
||||
if e.flags & ENCRYPTED != 0 {
|
||||
return Err(Error::Unsupported("encrypted packages"));
|
||||
}
|
||||
if e.method != STORED && e.method != DEFLATED {
|
||||
return Err(Error::Unsupported(OTHER_METHODS));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they
|
||||
/// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to
|
||||
/// at most its stated size plus one byte, so a member that inflates past what it states stops
|
||||
/// there. The length and CRC-32 must match the directory's.
|
||||
pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result<Cow<'a, [u8]>, Error> {
|
||||
self.check(i)?;
|
||||
let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?;
|
||||
if e.size > limit {
|
||||
return Err(Error::Limit("package member size"));
|
||||
}
|
||||
if e.method == DEFLATED && e.size > inflate_left {
|
||||
return Err(Error::Limit("inflated size"));
|
||||
}
|
||||
let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?;
|
||||
let out: Cow<'a, [u8]> = match e.method {
|
||||
STORED if e.packed == e.size => Cow::Borrowed(packed),
|
||||
STORED => return Err(Error::Damaged("package member")),
|
||||
DEFLATED => {
|
||||
let mut out = Vec::new();
|
||||
let got = flate2::read::DeflateDecoder::new(packed)
|
||||
.take(e.size as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|_| Error::Damaged("package member"))?;
|
||||
if got != e.size {
|
||||
return Err(Error::Damaged("package member"));
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
_ => return Err(Error::Unsupported(OTHER_METHODS)),
|
||||
};
|
||||
if crc32fast::hash(&out) != e.crc {
|
||||
return Err(Error::Damaged("package member"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the end of central directory record starts: searched back from the end over at most the
|
||||
/// longest comment, among the records whose comment reaches exactly to the end the first that
|
||||
/// names members in a directory before it, else the first. A comment or a member may hold bytes
|
||||
/// that look like an empty archive's end record.
|
||||
fn find_end(bytes: &[u8]) -> Option<usize> {
|
||||
let last = bytes.len().checked_sub(END_LEN)?;
|
||||
let first = last.saturating_sub(MAX_COMMENT);
|
||||
let mut found = None;
|
||||
for at in (first..=last).rev() {
|
||||
let mut r = Rd::at(bytes, at);
|
||||
if r.u32() != Some(END) || r.skip(6).is_none() {
|
||||
continue;
|
||||
}
|
||||
let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16());
|
||||
if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) {
|
||||
continue;
|
||||
}
|
||||
let names_members = total.is_some_and(|t| t > 0)
|
||||
&& dir_len.zip(dir_at).is_some_and(|(len, dir)| {
|
||||
(dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL)
|
||||
});
|
||||
if names_members {
|
||||
return Some(at);
|
||||
}
|
||||
found = found.or(Some(at));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The central directory entry at `r` (before `dir_end`) and its local header.
|
||||
fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result<Entry<'a>, Error> {
|
||||
let dir = || Error::Damaged("package directory");
|
||||
if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) {
|
||||
return Err(dir());
|
||||
}
|
||||
r.skip(4).ok_or_else(dir)?;
|
||||
let flags = r.u16().ok_or_else(dir)?;
|
||||
let method = r.u16().ok_or_else(dir)?;
|
||||
r.skip(4).ok_or_else(dir)?;
|
||||
let crc = r.u32().ok_or_else(dir)?;
|
||||
let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?);
|
||||
let name_len = usize::from(r.u16().ok_or_else(dir)?);
|
||||
let extra_len = usize::from(r.u16().ok_or_else(dir)?);
|
||||
let comment_len = usize::from(r.u16().ok_or_else(dir)?);
|
||||
let disk = r.u16().ok_or_else(dir)?;
|
||||
r.skip(6).ok_or_else(dir)?;
|
||||
let header = r.u32().ok_or_else(dir)?;
|
||||
if packed == u32::MAX || size == u32::MAX || header == u32::MAX {
|
||||
return Err(Error::Unsupported("ZIP64 packages"));
|
||||
}
|
||||
if disk != 0 {
|
||||
return Err(Error::Unsupported("packages split across files"));
|
||||
}
|
||||
let name = r.bytes(name_len).ok_or_else(dir)?;
|
||||
r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?;
|
||||
if r.pos() > dir_end {
|
||||
return Err(dir());
|
||||
}
|
||||
// The local header repeats the name; its own extra field may differ in length.
|
||||
let header = header as usize;
|
||||
let mut l = Rd::at(bytes, header);
|
||||
let local = || Error::Damaged("package member header");
|
||||
if l.u32() != Some(LOCAL) {
|
||||
return Err(local());
|
||||
}
|
||||
// The signature, 22 bytes, then the name and extra field lengths.
|
||||
l.skip(LOCAL_LEN - 8).ok_or_else(local)?;
|
||||
let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?));
|
||||
if l.bytes(local_name) != Some(name) {
|
||||
return Err(local());
|
||||
}
|
||||
l.skip(local_extra).ok_or_else(local)?;
|
||||
Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::synth::{Member, zip};
|
||||
|
||||
fn stored(name: &str, data: &[u8]) -> Member {
|
||||
Member { name: name.into(), data: data.to_vec(), deflate: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_and_deflated_members_read_back() {
|
||||
let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b"");
|
||||
let a = Archive::open(&bytes, 10).unwrap();
|
||||
assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello")));
|
||||
assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]);
|
||||
assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size")));
|
||||
assert_eq!(a.find(b"c"), None);
|
||||
// What is left to inflate holds back deflated members only.
|
||||
assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size")));
|
||||
assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_record_is_found_behind_a_comment() {
|
||||
let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]);
|
||||
assert!(Archive::open(&bytes, 10).is_ok());
|
||||
// A comment longer than the record says leaves no end record to find.
|
||||
let mut cut = bytes.clone();
|
||||
cut.push(0);
|
||||
assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory"));
|
||||
// A comment that ends in bytes like an empty archive's end record: the record that names
|
||||
// members in a directory is the archive's.
|
||||
let mut fake = END.to_le_bytes().to_vec();
|
||||
fake.resize(END_LEN, 0);
|
||||
let bytes = zip(&[stored("a", b"x")], &fake);
|
||||
let a = Archive::open(&bytes, 10).unwrap();
|
||||
assert_eq!(a.count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_whose_crc_or_length_is_wrong_is_damage() {
|
||||
let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b"");
|
||||
let a = Archive::open(&bytes, 10).unwrap();
|
||||
// The directory's CRC-32 sits 16 bytes into its entry.
|
||||
let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap();
|
||||
let mut bad = bytes.clone();
|
||||
bad[dir_at + 16] ^= 1;
|
||||
let b = Archive::open(&bad, 10).unwrap();
|
||||
assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member"));
|
||||
// A stated size one short: the inflate runs past it.
|
||||
let mut short = bytes.clone();
|
||||
short[dir_at + 24] -= 1;
|
||||
let s = Archive::open(&short, 10).unwrap();
|
||||
assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member"));
|
||||
assert!(a.read(0, 1000, 1000).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Read time of a large synthetic drawing. Run with
|
||||
//! `cargo test --release -p vectorcraft-cdr --test it bench -- --ignored --nocapture`.
|
||||
|
||||
use vectorcraft_cdr::synth::{self, V, chunk, list};
|
||||
use vectorcraft_cdr::{Limits, read};
|
||||
|
||||
/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when
|
||||
/// `compress`.
|
||||
fn many_curves(n: usize, compress: bool) -> Vec<u8> {
|
||||
let v = V(1300);
|
||||
let red = synth::color(5, [0, 0, 255, 0]);
|
||||
let black = synth::color(2, [0, 0, 0, 100]);
|
||||
let styles = list(
|
||||
b"doc ",
|
||||
vec![
|
||||
synth::mcfg(v, 612.0, 792.0),
|
||||
list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]),
|
||||
list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]),
|
||||
],
|
||||
);
|
||||
let objects: Vec<_> = (0..n)
|
||||
.map(|i| {
|
||||
let o = (i % 500) as f64;
|
||||
// A move, then curves of two control points and an end point each.
|
||||
let kind = |k: i32| {
|
||||
if k == 0 {
|
||||
0x08
|
||||
} else if k % 3 == 0 {
|
||||
0x80
|
||||
} else {
|
||||
0xC0
|
||||
}
|
||||
};
|
||||
let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect();
|
||||
let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))];
|
||||
synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o]))
|
||||
})
|
||||
.collect();
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]);
|
||||
let body = vec![styles, page];
|
||||
let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())];
|
||||
if compress {
|
||||
kids.push(synth::cmpr(&body));
|
||||
} else {
|
||||
kids.extend(body);
|
||||
}
|
||||
synth::riff(1300, &kids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn read_a_large_drawing() {
|
||||
for compress in [false, true] {
|
||||
let file = many_curves(50_000, compress);
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let t = std::time::Instant::now();
|
||||
let d = read(&file, Limits::default()).unwrap();
|
||||
times.push(t.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and
|
||||
//! hostile ones.
|
||||
|
||||
use proptest::prelude::*;
|
||||
use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape};
|
||||
use vectorcraft_cdr::synth_cmx::*;
|
||||
use vectorcraft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
|
||||
|
||||
fn shape(o: &Object) -> &Shape {
|
||||
match o {
|
||||
Object::Shape(s) => s,
|
||||
other => panic!("not a shape: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The (x, y) bounds of a shape's path.
|
||||
fn bounds(s: &Shape) -> (f64, f64, f64, f64) {
|
||||
let Geometry::Path(p) = &s.geometry else { panic!("not a path") };
|
||||
let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for sp in &p.subpaths {
|
||||
for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s {
|
||||
vectorcraft_cdr::model::Segment::Line(p) | vectorcraft_cdr::model::Segment::Cubic(_, _, p) => *p,
|
||||
})) {
|
||||
b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y));
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// The file with `children` after a 32-bit header and the sample tables.
|
||||
fn file(pages: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(pages.iter().cloned());
|
||||
children.extend(tables());
|
||||
riff(&children)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmx_file_is_told_from_a_cdr_drawing() {
|
||||
let f = sample();
|
||||
assert!(is_cmx(&f) && !is_cdr(&f));
|
||||
let mut rifx = f.clone();
|
||||
rifx[..4].copy_from_slice(b"RIFX");
|
||||
assert!(is_cmx(&rifx));
|
||||
assert!(!is_cmx(b"RIFF\0\0\0\0CDR9"));
|
||||
assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_layers_groups_and_curves() {
|
||||
let d = read_cmx(&sample(), Limits::default()).unwrap();
|
||||
assert_eq!(d.version, 0);
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
let page = &d.pages[0];
|
||||
// 2,100,000 units of 0.1 µm are 210 mm.
|
||||
let (w, h) = page.size.unwrap();
|
||||
assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}");
|
||||
// The layer drawn last is in front: the model lists layers front to back.
|
||||
let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["Top", "Art"]);
|
||||
let art = &page.layers[1].objects;
|
||||
assert_eq!(art.len(), 2);
|
||||
// The group, drawn after the red square, is in front of it.
|
||||
let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) };
|
||||
assert_eq!(kids.len(), 2);
|
||||
let red = shape(&art[1]);
|
||||
assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0])));
|
||||
// 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center.
|
||||
let mm = 72.0 / 25.4;
|
||||
let b = bounds(red);
|
||||
assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}");
|
||||
let Geometry::Path(p) = &red.geometry else { panic!() };
|
||||
assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4);
|
||||
let o = red.outline.as_ref().unwrap();
|
||||
assert!(near(o.width, 0.5 * mm));
|
||||
assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round));
|
||||
assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with);
|
||||
// Line type 1 draws no outline.
|
||||
let blue = shape(&kids[0]);
|
||||
let black = shape(&kids[1]);
|
||||
assert!(black.outline.is_none());
|
||||
assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])));
|
||||
// The color record's values are blue, green and red.
|
||||
assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0])));
|
||||
let o = blue.outline.as_ref().unwrap();
|
||||
assert!(near(o.width, 1.0 * mm));
|
||||
assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter));
|
||||
assert_eq!(page.layers[0].name, "Top");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_names_and_layers_without_objects() {
|
||||
let p = page(&[
|
||||
begin_page(None),
|
||||
begin_layer("Ebene 1", Some("Слой 1")),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
end_layer(),
|
||||
begin_layer("Gitter", None),
|
||||
end_layer(),
|
||||
begin_layer("Caf\u{e9}", None),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let page = &d.pages[0];
|
||||
assert_eq!(page.size, None);
|
||||
// The empty layer is left out, and the UTF-16 name wins over the 8-bit one.
|
||||
let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_before_any_layer_get_one() {
|
||||
let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages[0].layers.len(), 1);
|
||||
// The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place.
|
||||
assert_eq!(d.pages[0].layers[0].name, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_without_a_size_takes_the_drawings_bounds() {
|
||||
// A square of 100 mm whose bounds lie off the file's origin, above and to the right.
|
||||
let p = page(&[
|
||||
begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000),
|
||||
begin_layer("L", None),
|
||||
square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000),
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let page = &d.pages[0];
|
||||
let side = 100.0 / 25.4 * 72.0;
|
||||
let (w, h) = page.size.unwrap();
|
||||
assert!(near(w, side) && near(h, side), "{w} x {h}");
|
||||
// The page is centered on the bounds, so the square fills it.
|
||||
let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0]));
|
||||
assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curves_and_open_groups() {
|
||||
let c =
|
||||
curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]);
|
||||
// A group the layer leaves open closes with it.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") };
|
||||
let s = shape(&kids[0]);
|
||||
assert!(s.fill.is_none());
|
||||
let Geometry::Path(p) = &s.geometry else { panic!() };
|
||||
assert_eq!(p.subpaths.len(), 2);
|
||||
assert!(matches!(p.subpaths[0].segments[..], [vectorcraft_cdr::model::Segment::Cubic(..)]));
|
||||
assert!(!p.subpaths[1].closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_without_its_points_is_reported() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() {
|
||||
let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0];
|
||||
d.extend(b"Art");
|
||||
let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])]));
|
||||
let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].name, "Art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_read_is_reported() {
|
||||
let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])]));
|
||||
let p = page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
other(66),
|
||||
other(68),
|
||||
other(20),
|
||||
other(88),
|
||||
square(&attrs_fill_type(2), 0, 0, 1000),
|
||||
square(&attrs(Some(1), None, true), 0, 0, 1000),
|
||||
end_layer(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] {
|
||||
assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings);
|
||||
}
|
||||
// A fill of another type leaves the curve unfilled; the curve is still read.
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(objects.len(), 2);
|
||||
assert!(shape(&objects[1]).fill.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_of_other_models_and_missing_entries() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(9), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 1000),
|
||||
]));
|
||||
children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0])));
|
||||
assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray_cmy_and_rgb_colors_of_the_older_fields() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(3), None, false), 0, 0, 1000),
|
||||
]));
|
||||
children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
// The model holds objects front to back: the RGB square, the CMY one, then the gray one.
|
||||
assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0])));
|
||||
match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) {
|
||||
(Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => {
|
||||
assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");
|
||||
assert!((g - 0.8).abs() < 1e-6, "{g}");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_arrowheads_are_reported() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
|
||||
children.push(arrowheads(&[(0, 2)]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.warnings, vec![Warning::Arrowheads]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_instruction_and_a_jump_over_image_bytes() {
|
||||
// The jump's target counts from the start of the file: header, `cont`, then the page body.
|
||||
let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8;
|
||||
let head = [begin_page(None), begin_layer("L", None)].concat();
|
||||
let jump_len = 4 + 1 + 3 + 4;
|
||||
let image = vec![0xEEu8; 37];
|
||||
let target = (before + 8 + head.len() + jump_len + image.len()) as u32;
|
||||
let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())]));
|
||||
assert_eq!(jump.len(), jump_len);
|
||||
let body = [
|
||||
head,
|
||||
jump,
|
||||
image,
|
||||
long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]),
|
||||
end_layer(),
|
||||
]
|
||||
.concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
// The images jumped over are not read, and the warning says so.
|
||||
assert_eq!(d.warnings, [Warning::UnsupportedObjects]);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
|
||||
let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff];
|
||||
let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_byte_orders_and_coordinate_sizes_are_refused() {
|
||||
let mut f = sample();
|
||||
f[..4].copy_from_slice(b"RIFX");
|
||||
assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
|
||||
let mut children = vec![cont(b'2', 1e-3)];
|
||||
children.extend(tables());
|
||||
assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
|
||||
assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_without_a_usable_unit_reads_0_1_micrometers() {
|
||||
for meters in [0.0, -1.0, f64::NAN, 2.0] {
|
||||
let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let (w, _) = d.pages[0].size.unwrap();
|
||||
assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_past_the_depth_limit_are_left_out() {
|
||||
let mut ins = vec![begin_page(None), begin_layer("L", None)];
|
||||
for _ in 0..6 {
|
||||
ins.push(begin_group());
|
||||
}
|
||||
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
|
||||
for _ in 0..6 {
|
||||
ins.push(end_group());
|
||||
}
|
||||
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
|
||||
let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
// The square after the groups is still read, beside the three groups kept.
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(objects.len(), 2);
|
||||
let mut depth = 0;
|
||||
let mut o = &objects[1];
|
||||
while let Object::Group { objects: kids, .. } = o {
|
||||
depth += 1;
|
||||
match kids.first() {
|
||||
Some(k) => o = k,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
assert_eq!(depth, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_past_the_limits_are_bounded() {
|
||||
let ins: Vec<Vec<u8>> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect();
|
||||
let f = file(&[page(&ins)]);
|
||||
let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 10);
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 2);
|
||||
assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
|
||||
assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
|
||||
let dashed = |n: u16| {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)]));
|
||||
children.extend(tables());
|
||||
read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
|
||||
};
|
||||
let d = dashed(3);
|
||||
let o: Vec<usize> = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect();
|
||||
assert_eq!(o, [0, 2]);
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_cut_short_keeps_the_points_it_holds() {
|
||||
let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]);
|
||||
// Claim 9 points where 3 are stored: the field's own length still covers only 3.
|
||||
let at = c.windows(2).position(|w| w == [3, 0]).unwrap();
|
||||
c[at] = 9;
|
||||
let p = page(&[begin_page(None), c]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged));
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_that_lost_type_bytes_keeps_its_first_points() {
|
||||
// Three whole points and only two of their type bytes.
|
||||
let mut g = 3u16.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] {
|
||||
g.extend(x.to_le_bytes());
|
||||
g.extend(y.to_le_bytes());
|
||||
}
|
||||
g.extend([0x0c, 0x44]);
|
||||
let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)]));
|
||||
let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() };
|
||||
let side = 100.0 / 25.4 * 72.0;
|
||||
assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0));
|
||||
match p.subpaths[0].segments[..] {
|
||||
[vectorcraft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"),
|
||||
ref other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_cut_short_of_its_declared_size_is_reported() {
|
||||
let mut f = file(&[]);
|
||||
let declared = (f.len() as u32 - 8 + 100).to_le_bytes();
|
||||
f[4..8].copy_from_slice(&declared);
|
||||
let d = read_cmx(&f, Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_that_ends_inside_an_instruction_is_reported() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_64_bytes_past_stray_bytes_is_found() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stray_letters_with_a_length_past_the_file_are_passed_over() {
|
||||
let mut stray = b"abcd".to_vec();
|
||||
stray.extend(0xFFFF_FF00u32.to_le_bytes());
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl")));
|
||||
children.push(table(b"rdot", &[dashes(&[0, 0])]));
|
||||
children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap();
|
||||
assert!(o.dashes.is_empty(), "{:?}", o.dashes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_field_that_lost_points_is_left_out() {
|
||||
// Three points claimed, two whole points stored and the third cut inside its y: the type
|
||||
// bytes can't be found, so no node types are read from coordinates.
|
||||
let mut g = 3u16.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0i32, 0i32), (1_000_000, 0)] {
|
||||
g.extend(x.to_le_bytes());
|
||||
g.extend(y.to_le_bytes());
|
||||
}
|
||||
g.extend(1_000_000i32.to_le_bytes());
|
||||
g.extend([0x40, 0x42]);
|
||||
let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)]));
|
||||
let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() {
|
||||
// Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 6];
|
||||
b.extend(chunk(b"inf1", &[0; 70]));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() {
|
||||
// After stray bytes, four spaces with a small length, or letters with a length past the list,
|
||||
// come before the page: neither is taken for a chunk, so the page is found.
|
||||
for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(filler);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() {
|
||||
// Stray bytes, then a chunk the reader passes over whose body starts with the letters of a
|
||||
// page chunk, then the page: only the page is read.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut inner = b"page".to_vec();
|
||||
inner.extend(4u32.to_le_bytes());
|
||||
inner.extend([0; 10]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &inner));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canvas_or_a_container_is_reported() {
|
||||
for bit in [8u8, 16] {
|
||||
let mut a = attrs(Some(1), None, false);
|
||||
a[0] |= bit;
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}");
|
||||
assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_color_with_its_name_reads_as_a_spot_color() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
|
||||
children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
match shape(&d.pages[0].layers[0].objects[0]).fill.clone() {
|
||||
Some(Color::Spot { name, tint, look }) => {
|
||||
assert_eq!((name.as_str(), tint), ("Brick 12", 1.0));
|
||||
assert!(look.is_some());
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn never_panics_on_garbage(bytes in prop::collection::vec(any::<u8>(), 0..2048)) {
|
||||
let mut b = b"RIFF\0\0\0\0CMX1".to_vec();
|
||||
b.extend(bytes);
|
||||
let _ = read_cmx(&b, Limits::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::<usize>(), any::<u8>()), 1..24)) {
|
||||
let mut b = sample();
|
||||
let n = b.len();
|
||||
for (at, v) in edits {
|
||||
b[at % n] = v;
|
||||
}
|
||||
let _ = read_cmx(&b, Limits::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Integration tests: one test binary for the crate, one module per area.
|
||||
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod bench;
|
||||
mod cmx;
|
||||
mod provenance;
|
||||
mod read;
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// The ids `R<n>` in `text`.
|
||||
fn ids(text: &str) -> BTreeSet<u32> {
|
||||
let b = text.as_bytes();
|
||||
let mut out = BTreeSet::new();
|
||||
for (i, c) in b.iter().enumerate() {
|
||||
let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric());
|
||||
if !starts {
|
||||
continue;
|
||||
}
|
||||
let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect();
|
||||
let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric());
|
||||
if !digits.is_empty() && ends {
|
||||
out.insert(digits.parse().unwrap());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_cited_layout_has_a_row() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap();
|
||||
let rows: BTreeSet<u32> = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect();
|
||||
let mut cited = BTreeSet::new();
|
||||
for entry in std::fs::read_dir(dir.join("src")).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_some_and(|e| e == "rs") {
|
||||
cited.extend(ids(&std::fs::read_to_string(&path).unwrap()));
|
||||
}
|
||||
}
|
||||
assert!(!cited.is_empty());
|
||||
let missing: Vec<_> = cited.difference(&rows).collect();
|
||||
assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_found_only_as_whole_words() {
|
||||
assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12]));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+43
-2
@@ -74,11 +74,24 @@ pub struct HitOptions {
|
||||
/// its edge. Off for the tools that act on what is drawn (sampling, type, gradients…);
|
||||
/// [`hit_test_visible`] never does it.
|
||||
pub clip_outlines: bool,
|
||||
/// The Type tool: area type is hit anywhere inside its frame, where a click places the caret.
|
||||
/// Off, the empty part of the frame (away from its edge and its lines of type) takes no
|
||||
/// clicks, so they reach the art behind (#7274).
|
||||
pub area_type_interior: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
fn default() -> Self {
|
||||
Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: false, scope: None }
|
||||
Self {
|
||||
tol: 3.0,
|
||||
outline: false,
|
||||
path_only: false,
|
||||
type_path_only: false,
|
||||
skip_guides: false,
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1507,7 +1520,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
hit_painted(n, p, opt, symbols)
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p))?;
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) if !opt.area_type_interior => in_area_type_art(n, t, p, opt.tol).unwrap_or(true).then_some(HitKind::Bounds),
|
||||
_ => Some(HitKind::Bounds),
|
||||
}
|
||||
}
|
||||
// A symbol instance is hit within its bounds, and outside them where its art paints
|
||||
// ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape
|
||||
@@ -1577,6 +1594,30 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
stroke_contains(&path.to_bezpath(), 0.0, tol, p)
|
||||
}
|
||||
|
||||
/// Is `p` on area type `t` (in `n`) where it is drawn: within `tol` of its frame's edge or inside
|
||||
/// its laid-out lines ([`crate::TextObject::cached_bounds`], with the characters' strokes)? The
|
||||
/// rest of the frame is empty and takes no clicks (#7274). `None` when that is not known: other
|
||||
/// type, type in perspective, or area type not laid out yet, which are hit within their bounds.
|
||||
fn in_area_type_art(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> Option<bool> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let crate::TextKind::Area { frame } = &t.kind else { return None };
|
||||
if n.projection().is_some() {
|
||||
return None;
|
||||
}
|
||||
if stroke_contains(&frame.transformed(t.xf).to_bezpath(), 0.0, tol, p) {
|
||||
return Some(true);
|
||||
}
|
||||
let lines = t.cached_bounds?;
|
||||
// No lines (empty type): only the frame's edge.
|
||||
if lines.width() <= 0.0 && lines.height() <= 0.0 {
|
||||
return Some(false);
|
||||
}
|
||||
let mut lines = lines.to_path(0.1);
|
||||
lines.apply_affine(t.xf);
|
||||
let reach = tol + t.char_stroke_outset();
|
||||
Some(fill_contains(&lines, FillRule::NonZero, p) || stroke_contains(&lines, 0.0, reach, p))
|
||||
}
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art
|
||||
/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and
|
||||
/// nothing more is tested once the limit is used up.
|
||||
|
||||
@@ -1455,8 +1455,16 @@ fn masked_square(layer: bool) -> (Document, NodeId, NodeId, NodeId) {
|
||||
}
|
||||
}
|
||||
|
||||
const SELECTING: HitOptions =
|
||||
HitOptions { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: true, scope: None };
|
||||
const SELECTING: HitOptions = HitOptions {
|
||||
tol: 3.0,
|
||||
outline: false,
|
||||
path_only: false,
|
||||
type_path_only: false,
|
||||
skip_guides: false,
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
/// For the selection tools a clip group's clipping path is hit on its outline, within the
|
||||
/// tolerance, before the art it clips and just outside it too; inside, the art is hit.
|
||||
@@ -1750,6 +1758,41 @@ fn type_path_only_picks_type_on_its_path() {
|
||||
assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path");
|
||||
}
|
||||
|
||||
/// Area type is hit on its frame's edge and where its lines are laid out, not in the empty rest of
|
||||
/// its frame: a click there reaches the art behind, in Preview and in Outline mode (#7274). The
|
||||
/// Type tool still finds the type anywhere inside its frame.
|
||||
#[test]
|
||||
fn area_type_passes_clicks_through_its_empty_frame() {
|
||||
use crate::{CharStyle, TextKind, TextObject};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
// A filled square behind the type, its edge at x = 150 inside the frame.
|
||||
let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 150.0, 350.0, 350.0)), Appearance::default_art());
|
||||
let square_id = square.id;
|
||||
d.insert(Some(l), 9, square).unwrap();
|
||||
// Area type at (100, 100): a 200 × 200 frame with one 80 wide line at its top.
|
||||
let mut area = TextObject::point(Point::new(100.0, 100.0), "Area", CharStyle { size: 20.0, ..CharStyle::default() });
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)) };
|
||||
area.cached_bounds = Some(Rect::new(0.0, 0.0, 80.0, 24.0));
|
||||
area.cached_baselines = vec![(Point::new(0.0, 18.0), Point::new(80.0, 18.0))];
|
||||
let area_id = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::new(area_id, NodeKind::Text(Box::new(area)))).unwrap();
|
||||
let outline = HitOptions { outline: true, ..Default::default() };
|
||||
for (opt, mode) in [(HitOptions::default(), "preview"), (outline, "outline")] {
|
||||
let hit = |p: Point| hit_test(&d, p, opt).map(|h| h.leaf);
|
||||
assert_eq!(hit(Point::new(140.0, 110.0)), Some(area_id), "{mode}: on the line of type");
|
||||
assert_eq!(hit(Point::new(200.0, 100.5)), Some(area_id), "{mode}: on the frame's top edge");
|
||||
assert_eq!(hit(Point::new(299.0, 250.0)), Some(area_id), "{mode}: on the frame's right edge");
|
||||
assert_eq!(hit(Point::new(220.0, 130.0)), None, "{mode}: the empty frame, nothing behind");
|
||||
assert_eq!(hit(Point::new(120.0, 250.0)), None, "{mode}: the empty frame, nothing behind");
|
||||
assert_eq!(hit(Point::new(150.0, 250.0)), Some(square_id), "{mode}: the square's edge behind the empty frame");
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(250.0, 250.0), HitOptions::default()).map(|h| h.leaf), Some(square_id), "the square's fill");
|
||||
// The Type tool: anywhere inside the frame.
|
||||
let typing = HitOptions { area_type_interior: true, ..Default::default() };
|
||||
assert_eq!(hit_test(&d, Point::new(250.0, 250.0), typing).map(|h| h.leaf), Some(area_id), "type tool: inside the frame");
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only with the layout's baselines: every line's for point type,
|
||||
/// area type's besides its frame, a vertical column's centre line, and type in perspective
|
||||
/// where it is drawn.
|
||||
|
||||
@@ -10,8 +10,9 @@ use super::{Node, PathData};
|
||||
pub struct NodeExtras {
|
||||
/// Opacity mask (Transparency panel). Its art lives here, outside the layer tree.
|
||||
pub mask: Option<Box<OpacityMask>>,
|
||||
/// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows
|
||||
/// them; `view` is its [`crate::TraceView`] id, absent for the tracing result).
|
||||
/// Image Trace object: `{preset, params, view?, split?}` it was traced with (the Image Trace
|
||||
/// panel shows them; `view` is its [`crate::TraceView`] id, absent for the tracing result, and
|
||||
/// `split` the Split view's divider, [`crate::TraceView::split_of`]).
|
||||
pub trace: Option<Box<serde_json::Value>>,
|
||||
/// Object → Text Wrap: area type below this object (in the same layer) flows around it.
|
||||
pub wrap: Option<crate::text::TextWrap>,
|
||||
|
||||
@@ -157,6 +157,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn },
|
||||
BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures },
|
||||
BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched },
|
||||
BuiltinStyleLibrary { id: "paper-cutouts", name: "Paper Cutouts", make: paper_cutouts },
|
||||
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
|
||||
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
@@ -384,6 +385,25 @@ fn painted_sketched() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Paper Cutouts: original layered paper colors with visible cut edges and crisp cast shadows.
|
||||
fn paper_cutouts() -> Vec<GraphicStyle> {
|
||||
let cutout = |name: &str, face: &str, edge: &str, rim: &str, shadow: &str, x: f64, y: f64| {
|
||||
style(
|
||||
name,
|
||||
vec![F(fill(face)), S(stroke(edge, 7.0)), S(stroke(rim, 2.0))],
|
||||
vec![fx("stylize.dropShadow", json!({"mode": "normal", "opacity": 100.0, "x": x, "y": y, "blur": 0.0, "color": shadow}))],
|
||||
)
|
||||
};
|
||||
vec![
|
||||
cutout("Coral Layers", "#ff6b6b", "#f9c74f", "#fff4e6", "#6d597a", 5.0, 5.0),
|
||||
cutout("Mint Layers", "#80cbc4", "#2a9d8f", "#e9f5db", "#355070", 4.0, 6.0),
|
||||
cutout("Midnight Layers", "#3d5a80", "#ee6c4d", "#e0fbfc", "#1b263b", 6.0, 4.0),
|
||||
cutout("Sunflower Sheet", "#ffbe0b", "#fb5607", "#fff3b0", "#6a4c93", 3.0, 6.0),
|
||||
cutout("Rose Layers", "#f28482", "#84a59d", "#f7ede2", "#4a4e69", 6.0, 3.0),
|
||||
cutout("Monochrome Stack", "#f5f5f5", "#444444", "#ffffff", "#222222", 5.0, 5.0),
|
||||
]
|
||||
}
|
||||
|
||||
/// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and
|
||||
/// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper).
|
||||
fn textures() -> Vec<GraphicStyle> {
|
||||
@@ -702,6 +722,26 @@ mod tests {
|
||||
assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_cutouts_have_layered_edges_and_crisp_shadows() {
|
||||
let lib = builtin_style_library("paper-cutouts").unwrap();
|
||||
assert_eq!(lib.name, "Paper Cutouts");
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Coral Layers", "Mint Layers", "Midnight Layers", "Sunflower Sheet", "Rose Layers", "Monochrome Stack"]);
|
||||
for g in &lib.styles {
|
||||
assert_eq!(g.appearance.items.len(), 3, "{} has a face and two cut edges", g.name);
|
||||
assert!(matches!(g.appearance.items[0], AppearanceItem::Fill(_)));
|
||||
assert!(matches!(g.appearance.items[1], AppearanceItem::Stroke(_)));
|
||||
assert!(matches!(g.appearance.items[2], AppearanceItem::Stroke(_)));
|
||||
assert_eq!(g.appearance.effects.len(), 1);
|
||||
let shadow = &g.appearance.effects[0];
|
||||
assert_eq!(shadow.id, "stylize.dropShadow");
|
||||
assert_eq!(shadow.params["blur"], 0.0);
|
||||
assert_eq!(shadow.params["opacity"], 100.0);
|
||||
}
|
||||
assert_eq!(read(&write(&lib), "Fallback").unwrap(), *lib);
|
||||
}
|
||||
|
||||
/// The built-in styles' Warps draw with the map a new Warp takes.
|
||||
#[test]
|
||||
fn builtin_warp_styles_take_the_nets_map() {
|
||||
|
||||
+54
-6
@@ -20,11 +20,18 @@ pub enum TraceView {
|
||||
OutlinesWithSource,
|
||||
/// Only the source image.
|
||||
Source,
|
||||
/// The source image on the part of the image left of a divider across it, and the traced
|
||||
/// shapes everywhere else ([`TraceView::split_of`]).
|
||||
Split,
|
||||
}
|
||||
|
||||
/// Where the Split view's divider is when the `trace` settings name no valid position: across the
|
||||
/// middle of the source image.
|
||||
pub const DEFAULT_TRACE_SPLIT: f64 = 0.5;
|
||||
|
||||
impl TraceView {
|
||||
/// Panel order.
|
||||
pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source];
|
||||
pub const ALL: [Self; 6] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source, Self::Split];
|
||||
|
||||
/// The id used in command params and in the saved `trace` object.
|
||||
pub fn id(self) -> &'static str {
|
||||
@@ -34,6 +41,7 @@ impl TraceView {
|
||||
Self::Outlines => "outlines",
|
||||
Self::OutlinesWithSource => "outlinesWithSourceImage",
|
||||
Self::Source => "sourceImage",
|
||||
Self::Split => "split",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,14 +56,21 @@ impl TraceView {
|
||||
trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the source image shows.
|
||||
pub fn shows_source(self) -> bool {
|
||||
matches!(self, Self::OutlinesWithSource | Self::Source)
|
||||
/// The Split view's divider in `trace` settings: the fraction of the source image's width, from
|
||||
/// its left edge in its own pixels, that shows the source image ([`DEFAULT_TRACE_SPLIT`] when
|
||||
/// `split` is missing, not a number or outside 0 to 1).
|
||||
pub fn split_of(trace: &serde_json::Value) -> f64 {
|
||||
trace.get("split").and_then(serde_json::Value::as_f64).filter(|f| (0.0..=1.0).contains(f)).unwrap_or(DEFAULT_TRACE_SPLIT)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes show filled.
|
||||
/// Whether the source image shows (in the Split view, on one side of the divider).
|
||||
pub fn shows_source(self) -> bool {
|
||||
matches!(self, Self::OutlinesWithSource | Self::Source | Self::Split)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes show filled (in the Split view, on one side of the divider).
|
||||
pub fn shows_result(self) -> bool {
|
||||
matches!(self, Self::Result | Self::ResultWithOutlines)
|
||||
matches!(self, Self::Result | Self::ResultWithOutlines | Self::Split)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes' outlines show.
|
||||
@@ -69,6 +84,12 @@ impl Node {
|
||||
pub fn trace_view(&self) -> TraceView {
|
||||
self.extras().trace.as_deref().map(TraceView::of).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The Split view's divider of an Image Trace object ([`TraceView::split_of`];
|
||||
/// [`DEFAULT_TRACE_SPLIT`] for anything else).
|
||||
pub fn trace_split(&self) -> f64 {
|
||||
self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -89,6 +110,26 @@ mod tests {
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"})));
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
assert_eq!(g.trace_split(), DEFAULT_TRACE_SPLIT);
|
||||
assert_eq!(TraceView::from_id("Split"), Some(TraceView::Split));
|
||||
assert!(TraceView::Split.shows_source() && TraceView::Split.shows_result() && !TraceView::Split.shows_outlines());
|
||||
for (split, want) in [
|
||||
(serde_json::json!(0.25), 0.25),
|
||||
(serde_json::json!(0), 0.0),
|
||||
(serde_json::json!(1), 1.0),
|
||||
(serde_json::json!(-0.1), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::json!(1.5), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::json!("0.3"), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::Value::Null, DEFAULT_TRACE_SPLIT),
|
||||
] {
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split})));
|
||||
assert_eq!(g.trace_split(), want, "{split}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() {
|
||||
use crate::{Appearance, Document, ImageObject, NodeId, NodeKind};
|
||||
@@ -132,6 +173,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Split view measures the whole image wherever the divider is, so the selection box
|
||||
// stays put while the divider moves.
|
||||
for split in [0.0, 0.01, 1.0] {
|
||||
let want = Rect::new(0.0, 0.0, 200.0, 200.0);
|
||||
group.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split})));
|
||||
assert_eq!((group.geometric_bounds(), group.visual_bounds()), (Some(want), Some(want)), "split {split}");
|
||||
}
|
||||
group.extras_mut().trace = None;
|
||||
assert_eq!(
|
||||
group.geometric_bounds(),
|
||||
|
||||
@@ -832,11 +832,12 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
}
|
||||
let (path, rule) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
|
||||
let mut keep = |out: &mut Vec<crate::SolidMesh>, path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<(), String> {
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
|
||||
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
|
||||
surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0), true)?
|
||||
.into_iter()
|
||||
.try_for_each(|m| crate::solids::keep_mesh(out, total, m, limit))
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
@@ -845,7 +846,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let mut out = vec![];
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?;
|
||||
keep(&mut out, &path, fx, item)?;
|
||||
return Ok(out);
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -855,12 +856,69 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
&& let Some(fx) = item.effects().get(index)
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?;
|
||||
keep(&mut out, &p, fx, item)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The surface Revolve `fx` sweeps from `path` (filled under `rule`) about the axis of `b` with
|
||||
/// `options`, painted `paint` at `opacity` in a group member of opacity `member` (1 for an object
|
||||
/// of its own), as meshes. When `graphics` and `fx` maps graphics onto the side, the side's
|
||||
/// triangles are a mesh of their own with the point of the unrolled side surface each corner shows
|
||||
/// ([`crate::MeshGraphics`]), the points the canvas places the graphics by
|
||||
/// ([`crate::solids::graphics::surface_parts`]), after a mesh of the rest (the end caps and the cut
|
||||
/// sides). As on the canvas, the graphics take `opacity`, and `member` applies to the side and its
|
||||
/// graphics together. Otherwise the surface is one plain mesh.
|
||||
fn surface_meshes(
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
b: Rect,
|
||||
fx: &Effect,
|
||||
options: Revolve,
|
||||
(paint, opacity, member): (&Paint, f32, f32),
|
||||
graphics: bool,
|
||||
) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let color = crate::solids::mesh_color(paint, opacity * member);
|
||||
let list: Vec<crate::MappedGraphic> = if graphics && fx.id == REVOLVE && options.map_surface {
|
||||
crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).into_iter().filter(|g| g.face == crate::PlanarFace::Front).collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Ok(vec![crate::SolidMesh::plain(vectorcraft_three_d::revolve_mesh(path, rule, b, options)?, color)]);
|
||||
}
|
||||
let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?;
|
||||
let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]);
|
||||
for (t, points) in mesh.triangles.iter().zip(&on) {
|
||||
let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied());
|
||||
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
|
||||
let into = match points {
|
||||
Some(points) => {
|
||||
art.extend(points);
|
||||
&mut side
|
||||
}
|
||||
None => &mut rest,
|
||||
};
|
||||
let base = into.positions.len() as u32;
|
||||
for (p, n) in corners {
|
||||
into.positions.push(p);
|
||||
into.normals.push(n);
|
||||
}
|
||||
into.triangles.push([base, base + 1, base + 2]);
|
||||
}
|
||||
let mut out = vec![];
|
||||
if !rest.is_empty() {
|
||||
out.push(crate::SolidMesh::plain(rest, color));
|
||||
}
|
||||
if !side.is_empty() {
|
||||
let graphics =
|
||||
crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) };
|
||||
out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol
|
||||
/// instances, blends and clipping groups already resolved), in document coordinates: with the
|
||||
/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of
|
||||
@@ -954,12 +1012,15 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
// The graphics go on the side of the member with the longest profile, as the canvas draws them.
|
||||
let longest = if options.map_surface { graphics_member(&shapes, b, options) } else { None };
|
||||
let mut out = vec![];
|
||||
for s in &shapes {
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
|
||||
for mesh in surface_meshes(&s.path, s.rule, b, fx, options, (&paint, opacity, s.opacity), longest == Some(k))? {
|
||||
crate::solids::keep_mesh(&mut out, total, mesh, limit)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -2710,8 +2710,8 @@ impl SolidMesh {
|
||||
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
|
||||
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
|
||||
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
|
||||
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
|
||||
/// mesh, stays plain.
|
||||
/// corner ([`MeshGraphics`]), then the rest. Revolve's meshes are split by their side instead
|
||||
/// (`revolve::surface_meshes`), so a Revolve's mesh stays plain here.
|
||||
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
|
||||
let list = graphics::mapped_graphics(p);
|
||||
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
|
||||
|
||||
@@ -41,6 +41,7 @@ vectorcraft-eps = { workspace = true }
|
||||
vectorcraft-metafile = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true }
|
||||
vectorcraft-cdr = { workspace = true }
|
||||
vectorcraft-scriptcheck = { workspace = true }
|
||||
vectorcraft-js = { workspace = true }
|
||||
# The commands' parameter schemas (schemas.rs).
|
||||
@@ -95,6 +96,7 @@ craft-jxl = { workspace = true }
|
||||
hayro-ccitt = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
vectorcraft-cdr = { workspace = true, features = ["synth"] }
|
||||
crc32fast = { workspace = true }
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example appearance_rows_bench` prints the time three Appearance row edits
|
||||
//! take with every path of documents of 2,000, 10,000 and 20,000 squares selected, each square with one fill row and one
|
||||
//! stroke row. For each size it first times the step that keeps the objects whose shown rows the edit wrote, on the same
|
||||
//! ids, two ways: each id looked up in the list of written objects (a list of ids, and a list of ids with the kind of row,
|
||||
//! as the commands held them), and each id looked up in a set built from that list. It checks that both ways keep the
|
||||
//! same ids in the same order. Then it times the whole `appearance.setItem` (`index` 1, `weight` 2),
|
||||
//! `appearance.duplicateItem` (`index` 0) and `stroke.set` (`item` 1, `weight` 2) commands, each on a fresh copy of the
|
||||
//! document made before the clock starts.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere it is wall time, and
|
||||
//! the first line says which. `ITERS` sets the runs per row (default 7); each row is the median in ms. The two lookup
|
||||
//! ways run in alternating order.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` closed 10 pt squares, each with a red fill row and a 1 pt black stroke row, and their ids in paint order.
|
||||
fn document(n: usize) -> (Document, Vec<NodeId>) {
|
||||
let mut doc = Document::new(4000.0, 4000.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let mut ids = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)];
|
||||
let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true));
|
||||
let id = doc.alloc_id();
|
||||
let looks = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0);
|
||||
doc.insert(layer, usize::MAX, Node::path(id, path, looks)).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
(doc, ids)
|
||||
}
|
||||
|
||||
/// The ids among `ids` that `wrote` holds, each looked up in the list: the lookup the row edits made.
|
||||
fn in_list(ids: Vec<NodeId>, wrote: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.into_iter().filter(|id| wrote.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// [`in_list`] with each id looked up in a set built from `wrote`.
|
||||
fn in_set(ids: Vec<NodeId>, wrote: &[NodeId]) -> Vec<NodeId> {
|
||||
let wrote: HashSet<NodeId> = wrote.iter().copied().collect();
|
||||
ids.into_iter().filter(|id| wrote.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// The ids among `ids` that `edited` holds with either kind of row, each looked up in the list, as `appearance.setItem`
|
||||
/// did.
|
||||
fn in_kind_list(ids: Vec<NodeId>, edited: &[(NodeId, bool)]) -> Vec<NodeId> {
|
||||
ids.into_iter().filter(|id| edited.iter().any(|(e, _)| e == id)).collect()
|
||||
}
|
||||
|
||||
/// [`in_kind_list`] with each id looked up in a set built from the ids of `edited`.
|
||||
fn in_kind_set(ids: Vec<NodeId>, edited: &[(NodeId, bool)]) -> Vec<NodeId> {
|
||||
let wrote: HashSet<NodeId> = edited.iter().map(|(id, _)| *id).collect();
|
||||
ids.into_iter().filter(|id| wrote.contains(id)).collect()
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<52} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
/// The medians of `old` and `new` over [`iters`] runs, alternating which goes first; each run filters `ids` `reps` times
|
||||
/// on copies made before the clock starts and gives the time of one.
|
||||
fn time_both<W: ?Sized>(ids: &[NodeId], wrote: &W, old: fn(Vec<NodeId>, &W) -> Vec<NodeId>, new: fn(Vec<NodeId>, &W) -> Vec<NodeId>) -> (f64, f64) {
|
||||
let reps = (200_000 / ids.len()).max(1);
|
||||
let run = |f: fn(Vec<NodeId>, &W) -> Vec<NodeId>| {
|
||||
let mut work: Vec<Vec<NodeId>> = (0..reps).map(|_| ids.to_vec()).collect();
|
||||
ms(|| {
|
||||
for it in &mut work {
|
||||
black_box(f(black_box(std::mem::take(it)), wrote));
|
||||
}
|
||||
}) / reps as f64
|
||||
};
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for i in 0..iters() {
|
||||
if i % 2 == 0 {
|
||||
a.push(run(old));
|
||||
b.push(run(new));
|
||||
} else {
|
||||
b.push(run(new));
|
||||
a.push(run(old));
|
||||
}
|
||||
}
|
||||
(median(a), median(b))
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} squares, all selected");
|
||||
let (doc, ids) = document(n);
|
||||
// Every object's topmost stroke row was written, as when every selected object takes the edit.
|
||||
let edited: Vec<(NodeId, bool)> = ids.iter().map(|id| (*id, false)).collect();
|
||||
// A list missing every other id, so lookups that fail are timed too.
|
||||
let half: Vec<NodeId> = ids.iter().copied().step_by(2).collect();
|
||||
for wrote in [&ids, &half] {
|
||||
assert_eq!(in_list(ids.clone(), wrote), in_set(ids.clone(), wrote), "both ways keep the same ids");
|
||||
}
|
||||
assert_eq!(in_kind_list(ids.clone(), &edited), in_kind_set(ids.clone(), &edited), "both ways keep the same ids");
|
||||
let (old, new) = time_both(&ids, ids.as_slice(), in_list, in_set);
|
||||
row("keep written ids, every id in the list", old);
|
||||
row("keep written ids, every id in a set", new);
|
||||
let (old, new) = time_both(&ids, half.as_slice(), in_list, in_set);
|
||||
row("keep written ids, half the ids in the list", old);
|
||||
row("keep written ids, half the ids in a set", new);
|
||||
let (old, new) = time_both(&ids, edited.as_slice(), in_kind_list, in_kind_set);
|
||||
row("keep written ids, (id, kind) list", old);
|
||||
row("keep written ids, (id, kind) set", new);
|
||||
|
||||
let all: Vec<u64> = ids.iter().map(|id| id.0).collect();
|
||||
let commands: [(&str, Value); 3] = [
|
||||
("appearance.setItem", json!({"ids": all, "index": 1, "weight": 2})),
|
||||
("appearance.duplicateItem", json!({"ids": all, "index": 0})),
|
||||
("stroke.set", json!({"ids": all, "item": 1, "weight": 2})),
|
||||
];
|
||||
for (cmd, p) in &commands {
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc.clone(), None);
|
||||
let t = ms(|| drop(black_box(s.execute(cmd, p).unwrap())));
|
||||
drop(black_box(s));
|
||||
t
|
||||
})
|
||||
.collect();
|
||||
row(&format!("{cmd}, whole command"), median(runs));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -326,6 +326,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(compoundshape::specs());
|
||||
v.extend(typecmd::specs());
|
||||
v.extend(retype::specs());
|
||||
v.extend(retype::fonts::specs());
|
||||
v.extend(menucmds::specs());
|
||||
v.extend(live::specs());
|
||||
v.extend(colorcmds::specs());
|
||||
@@ -850,6 +851,7 @@ pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub(crate) use paint::LIVE_PAINT_BUCKET;
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
|
||||
//! ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add
|
||||
//! Bounding Circle ([`bounding`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
mod bounding;
|
||||
mod bridge;
|
||||
mod corners;
|
||||
#[cfg(test)]
|
||||
@@ -188,6 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(bridge::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v.extend(bounding::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Add Bounding Rectangle and Add Bounding Circle: a live rectangle on the selection's geometric
|
||||
//! bounding box, or the smallest live circle around its outlines. The circle is the geometry crate's
|
||||
//! ([`enclosing_circle`](vectorcraft_geom::shapes::enclosing_circle)).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
use vectorcraft_geom::kurbo::ParamCurveExtrema;
|
||||
use vectorcraft_geom::{Affine, CubicBez, FillRule, ParamCurve, PathSeg, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::edit::{no_symbol_part, selected_roots_to_transform};
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or};
|
||||
use crate::sanity::rect_in_range;
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Add Bounding Rectangle's command.
|
||||
pub(crate) const RECTANGLE: &str = "addon.pathtools.boundingRectangle";
|
||||
/// Add Bounding Circle's command.
|
||||
pub(crate) const CIRCLE: &str = "addon.pathtools.boundingCircle";
|
||||
|
||||
/// How far a curve may stray from the points the circle is fitted to, in points. The circle's
|
||||
/// radius grows by as much, so it holds the curves themselves.
|
||||
const FLATNESS: f64 = 0.01;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.pathtools.boundingRectangle",
|
||||
"Add Bounding Rectangle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out; a path of a compound path selected on its own counts as an object), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them. It is an error when no rectangle is left (\"the shape would have no size\" when a rectangle with no size was left out, else \"nothing to enclose\") and when an edge of a rectangle would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Rectangle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first rectangle, ids, skipped?}",
|
||||
whole_objects,
|
||||
bounding_rectangle
|
||||
),
|
||||
cmd!(
|
||||
"addon.pathtools.boundingCircle",
|
||||
"Add Bounding Circle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out; a path of a compound path selected on its own counts as an object), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them. It is an error when no circle is left (\"the shape would have no size\" when a circle with no size was left out, else \"nothing to enclose\") and when an edge of a circle's bounding box would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Circle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first circle, ids, skipped?}",
|
||||
whole_objects,
|
||||
bounding_circle
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Enabled with a selection that is not an object of a symbol instance's art, which
|
||||
/// [`selected_roots_to_transform`] refuses.
|
||||
fn whole_objects(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
no_symbol_part(s)
|
||||
}
|
||||
|
||||
/// The shape a command draws.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Kind {
|
||||
Rectangle,
|
||||
Circle,
|
||||
}
|
||||
|
||||
fn bounding_rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add(s, p, Kind::Rectangle)
|
||||
}
|
||||
|
||||
fn bounding_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add(s, p, Kind::Circle)
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let (c, label) = match kind {
|
||||
Kind::Rectangle => (RECTANGLE, "Add Bounding Rectangle"),
|
||||
Kind::Circle => (CIRCLE, "Add Bounding Circle"),
|
||||
};
|
||||
let each = switch_or(p, "each", false, c)?;
|
||||
let offset = number_or(p, "offset", 0.0, c)?;
|
||||
if !(offset.is_finite() && offset >= 0.0) {
|
||||
return Err(bad(c, "`offset` must be 0 or more"));
|
||||
}
|
||||
// The objects `object.transform` moves: a path of a compound path selected on its own is one.
|
||||
let roots = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let groups: Vec<Vec<NodeId>> = if each { roots.iter().map(|id| vec![*id]).collect() } else { vec![roots] };
|
||||
let mut made: Vec<LiveShape> = vec![];
|
||||
// Objects that get no shape: no outline, or a shape with no size.
|
||||
let mut skipped = 0;
|
||||
let mut no_size = false;
|
||||
// The shapes share the halvings, so the work stays bounded however many objects are selected.
|
||||
let splits = split_share(groups.len());
|
||||
for ids in &groups {
|
||||
match shape_around(d, &symbols, ids, kind, offset, splits) {
|
||||
Around::Shape(live) => made.push(live),
|
||||
Around::NoOutline => skipped += 1,
|
||||
Around::NoSize => {
|
||||
skipped += 1;
|
||||
no_size = true;
|
||||
}
|
||||
Around::PastCanvas => return Err(bad(c, "the shape would reach past the edge of the canvas")),
|
||||
}
|
||||
}
|
||||
if made.is_empty() {
|
||||
return Err(bad(c, if no_size { "the shape would have no size" } else { "nothing to enclose" }));
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let mut ids = vec![];
|
||||
for live in made {
|
||||
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
|
||||
let mut n = Node::new(d.alloc_id(), kind);
|
||||
look.apply(d, &mut n);
|
||||
ids.push(n.id);
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
let first = ids.first().map_or(0, |id| id.0);
|
||||
let mut out = json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
if skipped > 0 {
|
||||
out["skipped"] = json!(skipped);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`shape_around`] finds.
|
||||
enum Around {
|
||||
Shape(LiveShape),
|
||||
/// The objects have no bounds or no outline.
|
||||
NoOutline,
|
||||
/// The rectangle would have no width or no height, or the circle no radius.
|
||||
NoSize,
|
||||
/// An edge of the shape would lie more than [`MAX_COORD`](crate::MAX_COORD) from the origin
|
||||
/// along either axis.
|
||||
PastCanvas,
|
||||
}
|
||||
|
||||
/// The live rectangle or circle around `ids`, grown by `offset`. A circle halves its curves as
|
||||
/// `splits` allows.
|
||||
fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64, splits: Splits) -> Around {
|
||||
match kind {
|
||||
Kind::Rectangle => {
|
||||
let Some(r) = d.bounds_of_with(ids, false, symbols) else { return Around::NoOutline };
|
||||
let r = r.inflate(offset, offset);
|
||||
if !rect_in_range(r) {
|
||||
return Around::PastCanvas;
|
||||
}
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Around::NoSize;
|
||||
}
|
||||
Around::Shape(LiveShape::Rectangle {
|
||||
w: r.width(),
|
||||
h: r.height(),
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate(r.origin().to_vec2()),
|
||||
})
|
||||
}
|
||||
Kind::Circle => {
|
||||
let mut gathered = Gathered::new();
|
||||
gathered.splits = splits;
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
outline_points(n, symbols, &mut gathered, 0);
|
||||
gathered.compact();
|
||||
}
|
||||
let Some((center, radius)) = shapes::enclosing_circle(&gathered.points) else { return Around::NoOutline };
|
||||
if radius + offset <= 0.0 {
|
||||
return Around::NoSize;
|
||||
}
|
||||
let r = radius + FLATNESS + offset;
|
||||
let b = Rect::new(center.x - r, center.y - r, center.x + r, center.y + r);
|
||||
if !rect_in_range(b) {
|
||||
return Around::PastCanvas;
|
||||
}
|
||||
Around::Shape(LiveShape::Ellipse { w: b.width(), h: b.height(), pie: (0.0, 360.0), xf: Affine::translate(b.origin().to_vec2()) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` points on the outline of `n`, as its geometric bounds measure it: the points of
|
||||
/// its paths ([`curve_points`]); the clipping path of a clip group or of a sublayer that clips its
|
||||
/// contents; the shown contents of a sublayer (a layer that an opened file put inside a group); the
|
||||
/// corners of an image; and the corners of the geometric bounding box of anything else. A group or
|
||||
/// layer `depth` levels below the selected object that is nested deeper than a document holds
|
||||
/// ([`vectorcraft_doc::MAX_DEPTH`]) counts by the corners of its geometric bounding box.
|
||||
fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: usize) {
|
||||
let nests = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. });
|
||||
if nests && depth >= vectorcraft_doc::MAX_DEPTH {
|
||||
out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten());
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
// The anchors count too, so a path of one anchor, which has no segments, is held.
|
||||
for p in path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)) {
|
||||
out.points.push(p);
|
||||
out.compact();
|
||||
}
|
||||
for seg in path.to_bezpath().segments() {
|
||||
match seg {
|
||||
PathSeg::Line(l) => out.points.extend([l.p0, l.p1]),
|
||||
_ => curve_points(seg.to_cubic(), 0, &mut out.points, &mut out.splits),
|
||||
}
|
||||
out.compact();
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
if let Some(c) = children.first() {
|
||||
outline_points(c, symbols, out, depth + 1);
|
||||
}
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
for c in n.editing_children().iter().filter(|c| c.visible || !layer) {
|
||||
outline_points(c, symbols, out, depth + 1);
|
||||
out.compact();
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let r = Rect::new(0.0, 0.0, im.width as f64, im.height as f64);
|
||||
out.points.extend(corners(r).map(|p| im.xf * p));
|
||||
}
|
||||
_ => out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` points whose convex hull, grown by [`FLATNESS`], holds the curve `c`: the ends of
|
||||
/// pieces whose control points lie within [`FLATNESS`] of their chord, and for pieces still curved
|
||||
/// after [`MAX_SPLITS`] halvings, or when `splits` allows no more ([`Splits::take`]), the corners of
|
||||
/// [`held`]. A flat piece that ends where it starts adds its control points too, so a small loop is
|
||||
/// not taken for a single point. A curve with a point that is not finite adds nothing.
|
||||
fn curve_points(c: CubicBez, depth: u32, out: &mut Vec<Point>, splits: &mut Splits) {
|
||||
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let flat = [c.p1, c.p2].iter().all(|p| distance_to_segment(*p, c.p0, c.p3) <= FLATNESS);
|
||||
if flat {
|
||||
out.extend([c.p0, c.p3]);
|
||||
if c.p0 == c.p3 {
|
||||
out.extend([c.p1, c.p2]);
|
||||
}
|
||||
} else if depth >= MAX_SPLITS || !splits.take(depth) {
|
||||
out.extend(held(c));
|
||||
} else {
|
||||
let (a, b) = c.subdivide();
|
||||
curve_points(a, depth + 1, out, splits);
|
||||
curve_points(b, depth + 1, out, splits);
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners of the convex hull of `c`'s control points cut down to `c`'s bounding box. Each of
|
||||
/// the two holds the curve, so the part they share holds it too. When the cut leaves nothing, which
|
||||
/// rounding can cause, it gives the box's corners.
|
||||
fn held(c: CubicBez) -> Vec<Point> {
|
||||
let b = ParamCurveExtrema::bounding_box(&c);
|
||||
let mut poly = shapes::convex_hull(vec![c.p0, c.p1, c.p2, c.p3]);
|
||||
for (x, bound, below) in [(true, b.x0, false), (true, b.x1, true), (false, b.y0, false), (false, b.y1, true)] {
|
||||
poly = clip(&poly, x, bound, below);
|
||||
}
|
||||
if poly.is_empty() { corners(b).to_vec() } else { poly }
|
||||
}
|
||||
|
||||
/// The convex polygon `poly` cut at `bound` on the x axis (`x`) or the y axis: the part at or below
|
||||
/// `bound` when `below`, else at or above it.
|
||||
fn clip(poly: &[Point], x: bool, bound: f64, below: bool) -> Vec<Point> {
|
||||
let v = |p: Point| if x { p.x } else { p.y };
|
||||
let inside = |p: Point| if below { v(p) <= bound } else { v(p) >= bound };
|
||||
let mut out = vec![];
|
||||
for (&a, &b) in poly.iter().zip(poly.iter().cycle().skip(1)) {
|
||||
if inside(a) {
|
||||
out.push(a);
|
||||
}
|
||||
if inside(a) != inside(b) {
|
||||
let mut p = a.lerp(b, (bound - v(a)) / (v(b) - v(a)));
|
||||
if x {
|
||||
p.x = bound;
|
||||
} else {
|
||||
p.y = bound;
|
||||
}
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many halvings [`curve_points`] makes for one command, over every curve it measures, before
|
||||
/// it halves each further curve [`MIN_SPLITS`] times only; with `each`, every shape gets an equal
|
||||
/// share ([`split_share`]).
|
||||
const TOTAL_SPLITS: usize = 1 << 20;
|
||||
|
||||
/// How many more halvings [`curve_points`] makes for one command once [`TOTAL_SPLITS`] is used up,
|
||||
/// each within the first [`MIN_SPLITS`] halvings of a curve; with `each`, shared as
|
||||
/// [`TOTAL_SPLITS`] is. After that, curves count by [`held`] whole.
|
||||
const EARLY_SPLITS: usize = 7 << 20;
|
||||
|
||||
/// How many times [`curve_points`] halves a curve once [`TOTAL_SPLITS`] is used up: 8 pieces, which
|
||||
/// keeps the circle fitted to a circle of four curves less than 0.3% larger than that circle.
|
||||
const MIN_SPLITS: u32 = 3;
|
||||
|
||||
/// The halvings [`curve_points`] may still make.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Splits {
|
||||
/// Halvings at any depth.
|
||||
any: usize,
|
||||
/// Halvings within the first [`MIN_SPLITS`] of a curve, once `any` is used up.
|
||||
early: usize,
|
||||
}
|
||||
|
||||
impl Splits {
|
||||
/// Takes one halving of a piece `depth` halvings into its curve; false when none is left.
|
||||
fn take(&mut self, depth: u32) -> bool {
|
||||
if self.any > 0 {
|
||||
self.any -= 1;
|
||||
} else if depth < MIN_SPLITS && self.early > 0 {
|
||||
self.early -= 1;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The halvings each of `shapes` shapes may make: an equal share of [`TOTAL_SPLITS`] and of
|
||||
/// [`EARLY_SPLITS`].
|
||||
fn split_share(shapes: usize) -> Splits {
|
||||
let n = shapes.max(1);
|
||||
Splits { any: TOTAL_SPLITS / n, early: EARLY_SPLITS / n }
|
||||
}
|
||||
|
||||
/// How many points [`outline_points`] gathers before it keeps only the corners of their convex hull.
|
||||
const COMPACT_AT: usize = 1 << 16;
|
||||
|
||||
/// Points gathered for a circle, kept down to the corners of their convex hull whenever they grow
|
||||
/// past `limit`: only the hull decides the circle. The points held stay within about twice the
|
||||
/// hull's corners, and grow only with the anchors and objects measured and the halvings
|
||||
/// ([`TOTAL_SPLITS`] and [`EARLY_SPLITS`]).
|
||||
struct Gathered {
|
||||
points: Vec<Point>,
|
||||
limit: usize,
|
||||
/// The halvings [`curve_points`] may still make (one shape's whole share at first).
|
||||
splits: Splits,
|
||||
}
|
||||
|
||||
impl Gathered {
|
||||
fn new() -> Self {
|
||||
Self { points: vec![], limit: COMPACT_AT, splits: split_share(1) }
|
||||
}
|
||||
|
||||
/// Keeps only the hull's corners once there are more than `limit` points; the next time waits
|
||||
/// until there are twice as many as the hull has, so each point is sorted a few times at most.
|
||||
fn compact(&mut self) {
|
||||
if self.points.len() > self.limit {
|
||||
self.points = shapes::convex_hull(std::mem::take(&mut self.points));
|
||||
self.limit = (self.points.len() * 2).max(COMPACT_AT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times [`curve_points`] halves a curve at most: up to 1,024 pieces.
|
||||
const MAX_SPLITS: u32 = 10;
|
||||
|
||||
/// The distance from `p` to the segment from `a` to `b`.
|
||||
fn distance_to_segment(p: Point, a: Point, b: Point) -> f64 {
|
||||
let ab = b - a;
|
||||
let len2 = ab.hypot2();
|
||||
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(p - (a + ab * t)).hypot()
|
||||
}
|
||||
|
||||
fn corners(r: Rect) -> [Point; 4] {
|
||||
[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
//! Add Bounding Rectangle and Add Bounding Circle: the box and the smallest circle, the current
|
||||
//! paint and placement on top of the current layer or the isolated group, `each` and `skipped`,
|
||||
//! shapes of no size, clip groups and clipping sublayers, paths of compound paths, huge curves and
|
||||
//! small loops, and the errors that leave the document as it was.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{CubicBez, Point, Rect, Vec2, shapes};
|
||||
|
||||
use super::{CIRCLE, COMPACT_AT, Gathered, RECTANGLE, Splits};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether two rectangles agree to within `tol` on every edge.
|
||||
fn rect_near(b: Rect, want: Rect, tol: f64) -> bool {
|
||||
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < tol)
|
||||
}
|
||||
|
||||
/// The live shape of `id`.
|
||||
fn live(s: &Session, id: NodeId) -> LiveShape {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Path { live: Some(live), .. } => live.as_ref().clone(),
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of `id`.
|
||||
fn bounds(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.bounds_of(&[id], false).unwrap()
|
||||
}
|
||||
|
||||
/// The last child of `parent`, the top of its stacking order.
|
||||
fn top_of(s: &Session, parent: NodeId) -> NodeId {
|
||||
node(s, parent).children().unwrap().last().unwrap().id
|
||||
}
|
||||
|
||||
/// Runs `command` with `p` and checks that it fails and leaves the document as it was.
|
||||
fn refused(s: &mut Session, command: &str, p: Value) -> String {
|
||||
let (undo, objects) = (undo_len(s), object_count(s));
|
||||
let e = s.execute(command, &p).unwrap_err().to_string();
|
||||
assert_eq!((undo_len(s), object_count(s)), (undo, objects), "{p} changed the document");
|
||||
e
|
||||
}
|
||||
|
||||
/// A live rectangle on the selection's geometric bounding box, strokes left out, with the current
|
||||
/// paint, on top of the current layer, selected; one undo removes it.
|
||||
#[test]
|
||||
fn a_bounding_rectangle_is_the_geometric_box_on_top_of_the_layer() {
|
||||
let mut s = session();
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 60, "height": 80})).unwrap());
|
||||
assert_eq!(node(&s, a).appearance.stroke_width(), 10.0, "the strokes reach past the geometric box");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let (before, undo) = (object_count(&s), undo_len(&s));
|
||||
let out = s.execute(RECTANGLE, &json!({})).unwrap();
|
||||
let id = id_of(&out);
|
||||
assert_eq!(ids_of(&out), vec![id]);
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
assert!(matches!(live(&s, id), LiveShape::Rectangle { .. }));
|
||||
assert!(rect_near(bounds(&s, id), Rect::new(10.0, 20.0, 160.0, 130.0), 1e-9), "{:?}", bounds(&s, id));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert_eq!(top_of(&s, layer), id);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert_eq!(object_count(&s), before + 1);
|
||||
// The current paint, as a shape drawn now gets it.
|
||||
let reference = rect(&mut s, 300.0, 300.0, 5.0, 5.0);
|
||||
let (n, r) = (node(&s, id), node(&s, reference));
|
||||
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint()));
|
||||
assert_eq!(n.appearance.stroke_width(), r.appearance.stroke_width());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_count(&s), before);
|
||||
}
|
||||
|
||||
/// A bounding circle around a right triangle stands on its hypotenuse; around a circle it is that
|
||||
/// circle, grown by at most the flattening allowance; `offset` grows the radius, and a rectangle's
|
||||
/// sides, by that much.
|
||||
#[test]
|
||||
fn a_bounding_circle_is_the_smallest_circle_around_the_outlines() {
|
||||
let mut s = session();
|
||||
let tri =
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}], "closed": true})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [tri.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
match live(&s, c) {
|
||||
LiveShape::Ellipse { w, h, pie, .. } => {
|
||||
assert!((w - 100.02).abs() < 1e-9 && (h - 100.02).abs() < 1e-9 && pie == (0.0, 360.0), "{w} {h}");
|
||||
}
|
||||
other => panic!("not a circle: {other:?}"),
|
||||
}
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(-10.01, -20.01, 90.01, 80.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
// A circle of radius 50 and a dot inside it: the bounding circle is the circle itself.
|
||||
let round = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 100, "height": 100})).unwrap());
|
||||
let dot = rect(&mut s, 240.0, 240.0, 2.0, 2.0);
|
||||
s.execute("select.set", &json!({"ids": [round.0, dot.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 5})).unwrap());
|
||||
let got = bounds(&s, c);
|
||||
let want = Rect::new(195.0, 195.0, 305.0, 305.0);
|
||||
assert!(rect_near(got, want, 0.03), "{got:?}");
|
||||
assert!(got.x0 <= want.x0 + 1e-9 && got.x1 >= want.x1 - 1e-9 && got.y0 <= want.y0 + 1e-9 && got.y1 >= want.y1 - 1e-9, "{got:?}");
|
||||
|
||||
s.execute("select.set", &json!({"ids": [tri.0]})).unwrap();
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 4})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(-4.0, -4.0, 84.0, 64.0), 1e-9));
|
||||
}
|
||||
|
||||
/// A shape with no size is not drawn: a straight horizontal line gets no rectangle and a path of
|
||||
/// one anchor no circle, unless `offset` gives them room; with `each` they are counted in
|
||||
/// `skipped`, and alone they are an error.
|
||||
#[test]
|
||||
fn shapes_of_no_size_are_skipped_unless_offset_gives_them_room() {
|
||||
let mut s = session();
|
||||
let line = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 10, "y": 50}, {"x": 90, "y": 50}]})).unwrap());
|
||||
let lone = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 50, "y": 70}]})).unwrap());
|
||||
let box_ = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
assert!(refused(&mut s, RECTANGLE, json!({})).contains("the shape would have no size"));
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 2})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(8.0, 48.0, 92.0, 52.0), 1e-9), "{:?}", bounds(&s, r));
|
||||
// The line has length, so its circle has size.
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(9.99, 9.99, 90.01, 90.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
s.execute("select.set", &json!({"ids": [lone.0]})).unwrap();
|
||||
assert!(refused(&mut s, CIRCLE, json!({})).contains("the shape would have no size"));
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3})).unwrap());
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(46.99, 66.99, 53.01, 73.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap();
|
||||
let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(2)), "{out}");
|
||||
assert!(rect_near(bounds(&s, id_of(&out)), Rect::new(200.0, 200.0, 210.0, 210.0), 1e-9));
|
||||
s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (2, Some(1)), "{out}");
|
||||
}
|
||||
|
||||
/// With `each`, every selected object gets a shape of its own, all in one undo step, on top of the
|
||||
/// layer in the selection's stacking order, and the new shapes are selected.
|
||||
#[test]
|
||||
fn each_draws_one_shape_around_each_object() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 30.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap();
|
||||
let ids = ids_of(&out);
|
||||
assert_eq!(ids.len(), 2);
|
||||
assert!(rect_near(bounds(&s, ids[0]), Rect::new(0.0, 0.0, 10.0, 10.0), 1e-9));
|
||||
assert!(rect_near(bounds(&s, ids[1]), Rect::new(100.0, 0.0, 120.0, 30.0), 1e-9));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
let order: Vec<NodeId> = node(&s, layer).children().unwrap().iter().map(|n| n.id).collect();
|
||||
assert_eq!(order, vec![a, b, ids[0], ids[1]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// An object with no outline (an empty group) gets no shape and the result counts it; with only
|
||||
/// such objects selected the command draws nothing.
|
||||
#[test]
|
||||
fn each_counts_the_objects_without_an_outline() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let empty = s
|
||||
.edit("Group", |d, _| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(d.default_layer(), 0, Node::group(id, vec![]))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(1)), "{out}");
|
||||
s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({})).unwrap();
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
assert!(refused(&mut s, RECTANGLE, json!({"each": true})).contains("nothing to enclose"));
|
||||
}
|
||||
|
||||
/// Curves over a hundred thousand points across are held by their circle: every point along the
|
||||
/// curves is inside the circle, whose radius is the 0.01 pt allowance larger than the circle around
|
||||
/// the flattened points. The farthest point of the lopsided arc lies between two flattened points,
|
||||
/// about 0.001 pt outside the circle around them, so it needs that allowance.
|
||||
#[test]
|
||||
fn the_circle_holds_huge_curves() {
|
||||
let mut s = session();
|
||||
let d = "M 0 0 C 0 -90000 120000 -90000 120000 0 C 60000 40000 30000 70000 0 0 Z";
|
||||
let blob = id_of(&s.execute("path.create", &json!({"d": d})).unwrap());
|
||||
let arc = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 20 400 380 500 400 0"})).unwrap());
|
||||
for big in [blob, arc] {
|
||||
s.execute("select.set", &json!({"ids": [big.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
let (center, r) = (xf * Point::new(w / 2.0, w / 2.0), w / 2.0);
|
||||
let path = node(&s, big).path_data().unwrap().to_bezpath();
|
||||
let mut farthest: f64 = 0.0;
|
||||
for seg in path.segments() {
|
||||
for i in 0..=4000 {
|
||||
let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0);
|
||||
farthest = farthest.max(p.distance(center));
|
||||
}
|
||||
}
|
||||
assert!(farthest <= r + 1e-6, "a point {farthest} from the center is outside the circle of radius {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Clip groups count by their clipping paths; for art inside one, the shape goes on top of the
|
||||
/// current layer, never into the clip group.
|
||||
#[test]
|
||||
fn clip_groups_count_by_their_clipping_paths() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let clip = id_of(&s.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [art.0, clip.0]})).unwrap();
|
||||
let group = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let b = bounds(&s, id);
|
||||
assert!((b.width() / 2.0 - 25.01).abs() < 0.03 && b.center().distance(Point::new(35.0, 35.0)) < 0.03, "{b:?}");
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer));
|
||||
s.execute("select.set", &json!({"ids": [clip.0]})).unwrap();
|
||||
let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer));
|
||||
assert!(rect_near(bounds(&s, id), Rect::new(10.0, 10.0, 60.0, 60.0), 1e-6));
|
||||
}
|
||||
|
||||
/// A sublayer that clips its contents counts by its clipping path, and the hidden objects of a
|
||||
/// sublayer are left out; a sublayer inside a selected group (as an opened file can put one there)
|
||||
/// counts the same way.
|
||||
#[test]
|
||||
fn sublayers_count_by_their_clipping_path_and_shown_art() {
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let hidden = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(sub), "the art is in the sublayer");
|
||||
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (sub_node, symbols) = (d.node(sub).unwrap().clone(), d.symbol_boxes());
|
||||
let mut g = Gathered::new();
|
||||
super::outline_points(&sub_node, &symbols, &mut g, 0);
|
||||
let (center, r) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(Point::new(50.0, 50.0)) < 1e-9 && (r - 50.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}");
|
||||
|
||||
// The top object of the sublayer becomes its clipping path.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let clip = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(clip), Some(sub));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sub_node = d.node(sub).unwrap().clone();
|
||||
let mut g = Gathered::new();
|
||||
super::outline_points(&sub_node, &d.symbol_boxes(), &mut g, 0);
|
||||
let (center, r) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(Point::new(25.0, 25.0)) < 1e-9 && (r - 5.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}");
|
||||
|
||||
let group = s
|
||||
.edit("Group", |d, _| {
|
||||
let layer = d.remove(sub)?;
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(top), usize::MAX, Node::group(id, vec![layer]))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let b = bounds(&s, c);
|
||||
assert!(b.center().distance(Point::new(25.0, 25.0)) < 1e-9 && (b.width() / 2.0 - (5.0 * 2f64.sqrt() + 0.01)).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
/// A path of a compound path selected on its own is an object, as `object.transform` moves it:
|
||||
/// the shape goes around that path only, and with `each` each selected path gets a shape. The
|
||||
/// compound path selected whole is one object.
|
||||
#[test]
|
||||
fn a_path_of_a_compound_path_selected_on_its_own_is_an_object() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 120.0, 100.0, 10.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
let members: Vec<NodeId> = node(&s, compound).children().unwrap().iter().map(|n| n.id).collect();
|
||||
assert_eq!(members.len(), 2);
|
||||
for kind in [RECTANGLE, CIRCLE] {
|
||||
s.execute("select.set", &json!({"ids": [members[0].0]})).unwrap();
|
||||
let id = id_of(&s.execute(kind, &json!({})).unwrap());
|
||||
let (got, want) = (bounds(&s, id), bounds(&s, members[0]));
|
||||
if kind == RECTANGLE {
|
||||
assert!(rect_near(got, want, 1e-9), "{got:?} on {want:?}");
|
||||
} else {
|
||||
let d = want.width().hypot(want.height()) + 0.02;
|
||||
assert!(got.center().distance(want.center()) < 1e-9 && (got.width() - d).abs() < 1e-9, "{got:?} around {want:?}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [members[0].0, members[1].0]})).unwrap();
|
||||
assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 2, "{kind}");
|
||||
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
|
||||
assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 1, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A small closed curve whose handles lie within the 0.01 pt allowance of its one anchor is not a
|
||||
/// single point: it gets a circle.
|
||||
#[test]
|
||||
fn a_small_loop_gets_a_circle() {
|
||||
let mut s = session();
|
||||
let lp = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 0.005 0 0 0.005 0 0"})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [lp.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
assert!(w > 0.02, "{w}");
|
||||
}
|
||||
|
||||
/// Once the command has used up both kinds of halvings, a curve counts by its control points' hull
|
||||
/// cut down to its bounding box: the points stay inside both and reach no farther than the curve
|
||||
/// along either axis, while its handles may.
|
||||
#[test]
|
||||
fn a_curve_past_the_halvings_counts_by_its_hull_inside_its_bounding_box() {
|
||||
// With nothing left, `curve_points` takes no halving, so `none` stays as it is.
|
||||
let mut none = Splits { any: 0, early: 0 };
|
||||
let c = CubicBez::new((0.0, 0.0), (20.0, 400.0), (380.0, 500.0), (400.0, 0.0));
|
||||
let b = vectorcraft_geom::kurbo::ParamCurveExtrema::bounding_box(&c);
|
||||
let mut out = vec![];
|
||||
super::curve_points(c, 0, &mut out, &mut none);
|
||||
assert!(out.len() >= 4 && out.iter().all(|p| b.inflate(1e-9, 1e-9).contains(*p)), "{out:?} in {b:?}");
|
||||
assert!(out.iter().any(|p| (p.y - b.y1).abs() < 1e-9), "the curve's lowest point is reached: {out:?}");
|
||||
let (center, r) = shapes::enclosing_circle(&out).unwrap();
|
||||
for i in 0..=1000 {
|
||||
let p = vectorcraft_geom::ParamCurve::eval(&c, f64::from(i) / 1000.0);
|
||||
assert!(p.distance(center) <= r + 1e-9, "{p:?} outside");
|
||||
}
|
||||
// The handle at x = 4,000,000 stays out: the curve reaches x = 16,000,000 / 9.
|
||||
let reach = CubicBez::new((0.0, 0.0), (4.0e6, 0.0), (0.0, 0.0), (0.0, 0.0));
|
||||
out.clear();
|
||||
super::curve_points(reach, 0, &mut out, &mut none);
|
||||
let far = out.iter().map(|p| p.x).fold(0.0, f64::max);
|
||||
assert!((far - 16.0e6 / 9.0).abs() < 1e-6, "{far}");
|
||||
out.clear();
|
||||
let mut splits = Splits { any: 3, early: 0 };
|
||||
super::curve_points(c, 0, &mut out, &mut splits);
|
||||
assert_eq!(splits, Splits { any: 0, early: 0 });
|
||||
assert!(out.len() > 4, "{out:?}");
|
||||
}
|
||||
|
||||
/// The circle fitted to a circle of four curves: less than 0.3% larger with only the early halvings
|
||||
/// left, and up to about 14% larger by the curves' hulls once those are used up too.
|
||||
#[test]
|
||||
fn a_circle_measured_past_the_halvings_stays_close() {
|
||||
let fitted = |mut splits: Splits| {
|
||||
let circle = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).to_bezpath();
|
||||
let mut out = vec![];
|
||||
for seg in circle.segments() {
|
||||
super::curve_points(seg.to_cubic(), 0, &mut out, &mut splits);
|
||||
}
|
||||
shapes::enclosing_circle(&out).unwrap()
|
||||
};
|
||||
let (center, r) = fitted(Splits { any: 0, early: 1000 });
|
||||
assert!(center.to_vec2().hypot() < 0.1 && (100.0..100.3).contains(&r), "{center:?} {r}");
|
||||
let (_, r) = fitted(Splits { any: 0, early: 0 });
|
||||
assert!((110.0..115.0).contains(&r), "{r}");
|
||||
}
|
||||
|
||||
/// Past the halvings at any depth, only the first [`super::MIN_SPLITS`] halvings of a curve take
|
||||
/// from the early ones; with `each`, every shape gets an equal share of both.
|
||||
#[test]
|
||||
fn early_halvings_are_taken_near_the_start_of_a_curve_and_shared() {
|
||||
let mut s = Splits { any: 1, early: 1 };
|
||||
assert!(s.take(super::MIN_SPLITS + 1));
|
||||
assert!(!s.take(super::MIN_SPLITS));
|
||||
assert!(s.take(0));
|
||||
assert!(!s.take(0));
|
||||
let whole = Splits { any: super::TOTAL_SPLITS, early: super::EARLY_SPLITS };
|
||||
assert_eq!(super::split_share(0), whole);
|
||||
assert_eq!(super::split_share(1), whole);
|
||||
assert_eq!(super::split_share(4), Splits { any: super::TOTAL_SPLITS / 4, early: super::EARLY_SPLITS / 4 });
|
||||
}
|
||||
|
||||
/// In an isolated group the shape goes on top of the group's art; in an isolated compound path it
|
||||
/// goes beside the compound path, never into it.
|
||||
#[test]
|
||||
fn shapes_go_into_an_isolated_group_but_not_an_isolated_compound_path() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": group.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group));
|
||||
assert_eq!(top_of(&s, group), id);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
|
||||
let c = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let e = rect(&mut s, 120.0, 100.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
|
||||
let members: Vec<u64> = node(&s, compound).children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
s.execute("select.set", &json!({"ids": members})).unwrap();
|
||||
let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(id), Some(compound), "the circle does not join the compound path");
|
||||
assert_eq!(d.parent_of(id), d.parent_of(compound));
|
||||
assert_eq!(node(&s, compound).children().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
/// An offset or each that is not one the commands take is an error, and nothing is drawn; with
|
||||
/// nothing selected the commands are not available.
|
||||
#[test]
|
||||
fn bad_params_and_an_empty_selection_draw_nothing() {
|
||||
let mut s = session();
|
||||
assert!(s.execute(RECTANGLE, &json!({})).is_err(), "nothing selected");
|
||||
assert!(s.execute(CIRCLE, &json!({})).is_err(), "nothing selected");
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
for p in [json!({"offset": -1}), json!({"offset": "5"}), json!({"each": "yes"})] {
|
||||
refused(&mut s, command, p);
|
||||
}
|
||||
assert!(refused(&mut s, command, json!({"offset": -1})).contains("`offset` must be 0 or more"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An offset that would put an edge of the shape more than 4,000,000 pt from the origin along
|
||||
/// either axis is an error that names the canvas edge, and nothing is drawn; the largest offsets
|
||||
/// that stay inside are drawn, for the rectangle and for the circle.
|
||||
#[test]
|
||||
fn an_offset_past_the_canvas_edge_draws_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
for offset in [1e308, 4.0e6] {
|
||||
let e = refused(&mut s, command, json!({ "offset": offset }));
|
||||
assert!(e.contains("the shape would reach past the edge of the canvas"), "{command} {offset}: {e}");
|
||||
}
|
||||
}
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 3.99e6})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(-3.99e6, -3.99e6, 3.99e6 + 10.0, 3.99e6 + 10.0), 1e-3));
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3.99e6})).unwrap());
|
||||
// The circle around the square from (0, 0) to (10, 10), 0.01 pt larger, then the offset.
|
||||
let radius = 50.0f64.sqrt() + 0.01 + 3.99e6;
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(5.0 - radius, 5.0 - radius, 5.0 + radius, 5.0 + radius), 1e-3));
|
||||
}
|
||||
|
||||
/// The limit holds along each axis on its own: a shape whose right edge would pass 4,000,000 pt is
|
||||
/// refused although its other edges, and its distance along the other axis, are small.
|
||||
#[test]
|
||||
fn one_edge_past_the_canvas_edge_is_enough_to_refuse() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 3_999_980.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
let e = refused(&mut s, command, json!({"offset": 20}));
|
||||
assert!(e.contains("the shape would reach past the edge of the canvas"), "{command}: {e}");
|
||||
}
|
||||
assert!(s.execute(RECTANGLE, &json!({"offset": 5})).is_ok(), "the right edge at 3,999,995 pt is inside");
|
||||
}
|
||||
|
||||
/// A large circle close to the canvas edge, whose arcs stay curved after the most halvings, gets a
|
||||
/// circle within 0.05 pt of the farthest point of its curves, which stays inside the edge.
|
||||
#[test]
|
||||
fn a_large_circle_near_the_canvas_edge_gets_a_close_circle() {
|
||||
let mut s = session();
|
||||
let e = id_of(&s.execute("shape.ellipse", &json!({"x": 3_799_950.0, "y": 0.0, "width": 200_000.0, "height": 200_000.0})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [e.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
let center = xf * Point::new(w / 2.0, w / 2.0);
|
||||
let mut farthest: f64 = 0.0;
|
||||
for seg in node(&s, e).path_data().unwrap().to_bezpath().segments() {
|
||||
for i in 0..=4000 {
|
||||
farthest = farthest.max(vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0).distance(center));
|
||||
}
|
||||
}
|
||||
assert!(w / 2.0 >= farthest && w / 2.0 < farthest + 0.05, "radius {} for curves reaching {farthest}", w / 2.0);
|
||||
}
|
||||
|
||||
/// The commands are dimmed while an object of a symbol instance's art is selected, which they
|
||||
/// refuse, and available again once it is not.
|
||||
#[test]
|
||||
fn a_selected_symbol_part_dims_the_commands() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let enabled = |s: &Session, id: &str| (crate::find_command(id).unwrap().enabled)(s);
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
assert!(enabled(&s, command).is_ok(), "{command}");
|
||||
}
|
||||
s.doc_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: a, path: vec![0] });
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
assert!(enabled(&s, command).is_err(), "{command} with a symbol part selected");
|
||||
}
|
||||
s.doc_mut().unwrap().selection.symbol_part = None;
|
||||
assert!(enabled(&s, RECTANGLE).is_ok());
|
||||
}
|
||||
|
||||
/// Many points keep only their hull's corners, and the circle around them is the one around all
|
||||
/// of the points.
|
||||
#[test]
|
||||
fn gathered_points_keep_their_hull_and_circle() {
|
||||
let mut g = Gathered::new();
|
||||
let c = Point::new(500.0, 300.0);
|
||||
for i in 0..200_000 {
|
||||
let angle = f64::from(i) * 0.618;
|
||||
let r = if i % 1000 == 0 { 250.0 } else { f64::from(i % 200) };
|
||||
g.points.push(c + Vec2::from_angle(angle) * r);
|
||||
g.compact();
|
||||
}
|
||||
assert!(g.points.len() <= COMPACT_AT + 1, "{} points kept", g.points.len());
|
||||
let (center, radius) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(c) < 1e-6 && (radius - 250.0).abs() < 1e-6, "{center:?} {radius}");
|
||||
}
|
||||
@@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"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. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. 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?}",
|
||||
"{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 at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. 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
|
||||
)]
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveCorners, LiveShape, NodeId};
|
||||
use vectorcraft_geom::shapes::CornerKind;
|
||||
use vectorcraft_geom::{AnchorKind, PathData, Point, SubPath};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
use vectorcraft_tools::{Action, Overlay, PointerEvent, PointerKind};
|
||||
|
||||
use crate::{Session, ViewInfo};
|
||||
|
||||
@@ -1055,6 +1055,37 @@ fn the_slide_tool_previews_and_commits_one_step() {
|
||||
assert_eq!(at(&s), Point::new(200.0, 100.0));
|
||||
}
|
||||
|
||||
/// The Tangent Circle tool's release draws the circle and then tells the tool, which forgets the
|
||||
/// first segment. When the command fails the session does not tell the tool, so the first segment
|
||||
/// stays picked: the circle shows again over the second segment. The second click draws it in one
|
||||
/// undo step.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
|
||||
let mut s = session();
|
||||
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
let at = |s: &mut Session, kind, x, y| s.pointer(&PointerEvent::new(kind, x, y), view);
|
||||
let shown = |s: &mut Session| {
|
||||
at(s, PointerKind::Move, 200.0, 139.0).unwrap();
|
||||
s.overlays(view).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00")))
|
||||
};
|
||||
at(&mut s, PointerKind::Down, 150.0, 101.0).unwrap();
|
||||
at(&mut s, PointerKind::Up, 150.0, 101.0).unwrap();
|
||||
assert!(shown(&mut s), "the first segment is picked");
|
||||
// The tool's release with a command that fails: three points on one line.
|
||||
let n = steps(&s);
|
||||
let failing = Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[0, 0], [10, 0], [20, 0]]}));
|
||||
assert!(s.apply_actions(vec![failing, Action::Notify("tangentCircle.drawn".into())]).is_err());
|
||||
assert_eq!(steps(&s), n, "nothing drawn");
|
||||
assert!(shown(&mut s), "the first segment is still picked");
|
||||
at(&mut s, PointerKind::Down, 200.0, 139.0).unwrap();
|
||||
at(&mut s, PointerKind::Up, 200.0, 139.0).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
@@ -278,6 +278,28 @@ impl ItemTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
|
||||
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
|
||||
/// ([`super::paint::live_paint_parts_skipped`]).
|
||||
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
|
||||
Ok(self.targets_and_skipped(s, p, fill)?.0)
|
||||
}
|
||||
|
||||
/// [`ItemTarget::targets_for`], and whether it left out any object inside a Live Paint group: a
|
||||
/// group with no part of the edited kind was still given or selected, so the edit does not go
|
||||
/// to new art.
|
||||
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
|
||||
let mut ids = self.targets(s, p)?;
|
||||
let mut skipped_any = false;
|
||||
if self == ItemTarget::Top {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
skipped_any = ids.len() != before;
|
||||
}
|
||||
Ok((ids, skipped_any))
|
||||
}
|
||||
|
||||
/// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits
|
||||
/// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted
|
||||
/// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
|
||||
@@ -772,7 +794,7 @@ fn edit_items_writing_then(
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
let mut rows = Vec::new();
|
||||
// The objects where `f` wrote the topmost visible row of its kind.
|
||||
let mut wrote = Vec::new();
|
||||
let mut wrote = HashSet::new();
|
||||
// The row of each object `f` wrote: its index, else the topmost row of the kind.
|
||||
let mut written = Vec::new();
|
||||
for (id, item) in ids.iter().zip(&per) {
|
||||
@@ -785,7 +807,7 @@ fn edit_items_writing_then(
|
||||
rows.push(*id);
|
||||
}
|
||||
if index.is_none_or(|i| is_top_shown(n, i)) {
|
||||
wrote.push(*id);
|
||||
wrote.insert(*id);
|
||||
}
|
||||
written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at)));
|
||||
}
|
||||
@@ -1341,7 +1363,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, written));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id));
|
||||
let wrote: HashSet<NodeId> = edited.iter().map(|(id, _)| *id).collect();
|
||||
let reached = shown_rows_edited(&before, d, reached, |id| wrote.contains(&id));
|
||||
let labels = capture_row_edits(&before, d, &reached);
|
||||
// A graph line keeps what was written to its topmost visible row, also when it already showed it.
|
||||
let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect();
|
||||
@@ -1503,7 +1526,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
let top_copies: Vec<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
let top_copies: HashSet<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id)));
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side (in a group, the side of the member with the longest profile) are a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles; its end caps and cut sides stay plain. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
|
||||
@@ -16,7 +16,7 @@ use vectorcraft_brush::{
|
||||
Variation,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{apply_brush, brush_targets, roots, stroke_paint};
|
||||
@@ -177,11 +177,13 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -571,6 +573,80 @@ fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
|
||||
/// Four original raster stamps. Scatter brushes preserve their image art while placing a copy
|
||||
/// along the path; art brushes bend their art and cannot bend an image. Each 24 px stamp is placed
|
||||
/// 6 pt wide, the size of the Scatter Shapes art, so a 1 pt stroke on a 10 pt line shows a stamp.
|
||||
fn image_brush() -> BrushLibrary {
|
||||
const SIDE: u32 = 24;
|
||||
const PT_PER_PX: f64 = 0.25;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut brushes = Vec::new();
|
||||
for (index, name) in ["Soft Bloom", "Halftone Field", "Solar Grain", "Color Flecks"].into_iter().enumerate() {
|
||||
let mut pixels = Vec::with_capacity((SIDE * SIDE * 4) as usize);
|
||||
for y in 0..SIDE {
|
||||
for x in 0..SIDE {
|
||||
let (dx, dy) = (x as f64 - 11.5, y as f64 - 11.5);
|
||||
let r = dx.hypot(dy);
|
||||
let angle = dy.atan2(dx);
|
||||
let rgba = match index {
|
||||
0 => {
|
||||
let edge = 7.0 + 3.0 * (5.0 * angle).cos();
|
||||
[199, 69, 139, (220.0 * ((edge - r) / 2.5).clamp(0.0, 1.0)) as u8]
|
||||
}
|
||||
1 => {
|
||||
let (gx, gy) = ((x % 6) as f64 - 2.5, (y % 6) as f64 - 2.5);
|
||||
[39, 139, 175, if r < 11.0 && gx.hypot(gy) < 1.9 { 225 } else { 0 }]
|
||||
}
|
||||
2 => {
|
||||
let ray = (9.0 * angle).cos().abs();
|
||||
[234, 144, 40, if r < 3.5 || (r < 10.5 && ray > 0.72) { 235 } else { 0 }]
|
||||
}
|
||||
_ => {
|
||||
let seed = (x * 37 + y * 71 + x * y * 13) % 19;
|
||||
[if seed % 2 == 0 { 67 } else { 114 }, 79, 167, if r < 11.0 && seed < 5 { 210 } else { 0 }]
|
||||
}
|
||||
};
|
||||
pixels.extend_from_slice(&rgba);
|
||||
}
|
||||
}
|
||||
let Ok(image) =
|
||||
craft_image_codecs::Image::from_raw(SIDE, SIDE, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(png) = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else {
|
||||
continue;
|
||||
};
|
||||
let key = format!("image-brush-{index}");
|
||||
doc.images.insert(key.clone(), ImageBlob::png(png));
|
||||
let art = Node::new(
|
||||
NodeId(0),
|
||||
NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: SIDE,
|
||||
height: SIDE,
|
||||
xf: Affine::scale(PT_PER_PX) * Affine::translate((-12.0, -12.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
brushes.push(scatter(
|
||||
name,
|
||||
art,
|
||||
Scatter {
|
||||
size: (90.0, 110.0),
|
||||
spacing: (125.0, 155.0),
|
||||
scatter: (-20.0, 20.0),
|
||||
rotation: (-15.0, 15.0),
|
||||
colorization: Colorization::None,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
}
|
||||
built("Image Brush", doc, brushes)
|
||||
}
|
||||
|
||||
/// Scatter Shapes: scatter brushes of shapes drawn here; Sparkles scatters the library's own
|
||||
/// symbol, Sparkle.
|
||||
fn scatter_shapes() -> BrushLibrary {
|
||||
@@ -627,6 +703,44 @@ fn scatter_shapes() -> BrushLibrary {
|
||||
built("Scatter Shapes", doc, brushes)
|
||||
}
|
||||
|
||||
/// Stipple: original dot-based scatter brushes for fine and broad shading along a path.
|
||||
fn stipple() -> BrushLibrary {
|
||||
let dot = |x: f64, y: f64, r: f64, opacity: f32| {
|
||||
Node::path(
|
||||
NodeId(0),
|
||||
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)),
|
||||
Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer { opacity, ..FillLayer::new(Paint::solid(Color::BLACK)) })],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
};
|
||||
let base = Scatter { colorization: Colorization::Tints, ..Default::default() };
|
||||
let brushes = vec![
|
||||
scatter(
|
||||
"Fine Stipple",
|
||||
dot(0.0, 0.0, 0.8, 1.0),
|
||||
Scatter { size: (70.0, 110.0), spacing: (80.0, 130.0), scatter: (-100.0, 100.0), ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Dense Stipple",
|
||||
group(vec![dot(-1.7, -1.4, 1.0, 1.0), dot(1.5, 0.5, 0.8, 1.0), dot(-0.5, 1.8, 0.65, 1.0)]),
|
||||
Scatter { size: (80.0, 120.0), spacing: (55.0, 90.0), scatter: (-70.0, 70.0), ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Soft Stipple",
|
||||
group(vec![dot(-1.2, -0.8, 1.0, 0.45), dot(1.2, 1.1, 0.7, 0.35)]),
|
||||
Scatter { size: (55.0, 135.0), spacing: (80.0, 140.0), scatter: (-140.0, 140.0), ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Bold Stipple",
|
||||
group(vec![dot(-1.5, -1.0, 1.8, 1.0), dot(1.6, 1.3, 1.4, 1.0)]),
|
||||
Scatter { size: (80.0, 125.0), spacing: (75.0, 115.0), scatter: (-95.0, 95.0), ..base },
|
||||
),
|
||||
];
|
||||
built("Stipple", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art).
|
||||
fn game_trails() -> BrushLibrary {
|
||||
let speed = {
|
||||
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult; the Split view keeps the traced object's divider, else 0.5, and imageTrace.setView sets it), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -181,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Image Trace View",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}",
|
||||
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"|\"split\" (the source image on the part of the image left of a divider across it, and the tracing result everywhere else), split?: 0-1 (the divider: the fraction of the source image's width, from its left edge, that shows the image; kept as it was when omitted, 0.5 for a new one)} how they draw on screen; exports, printing and Expand keep the tracing result, and tracing again keeps the view and the divider → {ids, view, split (view split: the first object's divider)}",
|
||||
has_selection_or_ids,
|
||||
trace_set_view
|
||||
),
|
||||
|
||||
@@ -37,7 +37,7 @@ fn check_live_paint_takes(d: &Document, roots: &[NodeId]) -> Result<()> {
|
||||
fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> {
|
||||
check_live_paint_takes(d, roots)?;
|
||||
if roots.iter().any(|r| d.node(*r).is_some_and(is_live_paint)) {
|
||||
return merge_live(d, sel, roots);
|
||||
return merge_live(d, sel, roots, false);
|
||||
}
|
||||
let mut sources = vec![];
|
||||
for r in roots {
|
||||
@@ -178,8 +178,10 @@ impl Carried {
|
||||
|
||||
/// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its
|
||||
/// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which
|
||||
/// are merged; returns (group, faces, edges).
|
||||
fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> {
|
||||
/// are merged; returns (group, faces, edges). When the groups and paths hold no path outline
|
||||
/// between them, `keep_empty` leaves the group with its paths in its sources group and no faces or
|
||||
/// edges; without it, that is an error.
|
||||
fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId], keep_empty: bool) -> Result<(NodeId, usize, usize)> {
|
||||
let target = roots
|
||||
.iter()
|
||||
.copied()
|
||||
@@ -212,7 +214,14 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
|
||||
let groups: Vec<GapOptions> = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect();
|
||||
let options = merged_gap_options(&groups);
|
||||
let (children, nf, ne) = build_children(d, sources, options.max_gap())?;
|
||||
let (children, nf, ne) = if keep_empty && source_shapes(&sources).0.is_empty() {
|
||||
let mut src = Node::group(d.alloc_id(), sources);
|
||||
src.name = Some(SOURCES_NAME.into());
|
||||
src.visible = false;
|
||||
(vec![Arc::new(src)], 0, 0)
|
||||
} else {
|
||||
build_children(d, sources, options.max_gap())?
|
||||
};
|
||||
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
|
||||
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
|
||||
let mut g = old;
|
||||
@@ -266,7 +275,7 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(reply) = lone_live_group(s, &roots)? {
|
||||
return Ok(reply);
|
||||
}
|
||||
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
|
||||
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots, false))?;
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
@@ -301,7 +310,7 @@ pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<boo
|
||||
return Ok(false);
|
||||
}
|
||||
let roots: Vec<NodeId> = std::iter::once(g).chain(drawn).collect();
|
||||
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
|
||||
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots, false))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -346,12 +355,31 @@ fn enclosing_live_paints(d: &Document, g: NodeId) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a shown row whose parent is `parent`, among Live Paint group `g`'s paths, gives `g` faces
|
||||
/// and edges: every group between it and `g`'s sources group is shown.
|
||||
fn shown_in_sources(d: &Document, parent: Option<NodeId>, g: NodeId) -> bool {
|
||||
let src = d.node(g).and_then(b::sources).map(|s| s.id);
|
||||
let mut at = parent;
|
||||
while let Some(x) = at {
|
||||
if Some(x) == src {
|
||||
return true;
|
||||
}
|
||||
if !d.node(x).is_some_and(|n| n.visible) {
|
||||
return false;
|
||||
}
|
||||
at = d.parent_of(x);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// What moving rows in the Layers panel (`layer.move`, `node.move`) does to Live Paint groups.
|
||||
/// Rows that go into a Live Paint group from elsewhere are added to it as `livePaint.merge` adds
|
||||
/// paths. Rows that go into or leave a group's paths (its sources group) change those paths, and
|
||||
/// the group's faces and edges are made again from them, keeping the paint of the faces and edges
|
||||
/// that stay, and so are those of every Live Paint group that holds a changed group among its
|
||||
/// paths. Rows moved within one group's paths, or among a group's own children, change no faces.
|
||||
/// paths. Rows moved within one group's paths change no faces unless a shown row goes into or out
|
||||
/// of a hidden group there; rows moved among a group's own children change no faces. A group's
|
||||
/// sources group itself stays in the group.
|
||||
pub(crate) struct LivePaintMove {
|
||||
/// The Live Paint group the rows go into, and for each row whether it joins the group's paths.
|
||||
join: Option<(NodeId, Vec<bool>)>,
|
||||
@@ -365,16 +393,29 @@ pub(crate) struct LivePaintMove {
|
||||
impl LivePaintMove {
|
||||
/// Plan moving `rows` (with `copy`, copies of them) into `parent`, before anything changes.
|
||||
/// Refuses rows Live Paint can't take ([`b::live_paint_takes`]) that would go among a group's
|
||||
/// paths, with the message Make and Merge give.
|
||||
/// paths, with the message Make and Merge give, and a group's sources group moved out of the
|
||||
/// group.
|
||||
pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option<NodeId>, copy: bool) -> Result<Self> {
|
||||
if !copy {
|
||||
for r in rows {
|
||||
if let Some(g) = d.parent_of(*r)
|
||||
&& parent != Some(g)
|
||||
&& d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == *r)
|
||||
{
|
||||
return Err(EngineError::Other("a Live Paint group's sources group stays in the group: move the paths in it instead".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let to = spot_in(d, parent);
|
||||
let from: Vec<Spot> = rows.iter().map(|r| if copy { Spot::Outside } else { spot_in(d, d.parent_of(*r)) }).collect();
|
||||
let mut rebuild = vec![];
|
||||
for f in &from {
|
||||
if let Spot::Source(g) = *f
|
||||
&& *f != to
|
||||
&& !rebuild.contains(&g)
|
||||
{
|
||||
for (r, f) in rows.iter().zip(&from) {
|
||||
let Spot::Source(g) = *f else { continue };
|
||||
// A shown row that goes into or out of a hidden group among the same paths starts or
|
||||
// stops giving the group faces and edges.
|
||||
let shown_changes =
|
||||
*f == to && d.node(*r).is_some_and(|n| n.visible) && shown_in_sources(d, d.parent_of(*r), g) != shown_in_sources(d, parent, g);
|
||||
if (*f != to || shown_changes) && !rebuild.contains(&g) {
|
||||
rebuild.push(g);
|
||||
}
|
||||
}
|
||||
@@ -444,7 +485,9 @@ impl LivePaintMove {
|
||||
for g in groups {
|
||||
if Some(g) == join_group {
|
||||
let roots: Vec<NodeId> = std::iter::once(g).chain(joined.iter().copied()).collect();
|
||||
merge_live(d, sel, &roots)?;
|
||||
// Rows that join a group with no path outline among them keep the move: the group
|
||||
// is left with no faces or edges, as when its last path leaves it.
|
||||
merge_live(d, sel, &roots, true)?;
|
||||
} else if d.node(g).is_some() {
|
||||
rebuild_paths(d, g)?;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,12 @@ fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given.
|
||||
fn split_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
|
||||
let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
|
||||
}
|
||||
|
||||
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1026,9 +1032,14 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for.
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
// view's divider.
|
||||
let view = view.unwrap_or_else(|| src.trace_view());
|
||||
g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() })));
|
||||
let mut t = json!({ "preset": preset_label, "params": params_json, "view": view.id() });
|
||||
if let Some(split) = src.extras().trace.as_deref().and_then(|t| t.get("split")).filter(|v| !v.is_null()) {
|
||||
t["split"] = split.clone();
|
||||
}
|
||||
g.extras_mut().trace = Some(Box::new(t));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
@@ -1127,23 +1138,37 @@ fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.setView";
|
||||
let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?;
|
||||
let split = split_param(C, p)?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) {
|
||||
return Ok(json!({ "ids": ids_json(&targets), "view": view.id() }));
|
||||
let result = |d: &vectorcraft_doc::Document| {
|
||||
let mut r = json!({ "ids": ids_json(&targets), "view": view.id() });
|
||||
if view == TraceView::Split
|
||||
&& let Some(n) = targets.first().and_then(|g| d.node(*g))
|
||||
{
|
||||
r["split"] = json!(split.unwrap_or_else(|| n.trace_split()));
|
||||
}
|
||||
r
|
||||
};
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view && split.is_none_or(|f| n.trace_split() == f))) {
|
||||
return Ok(result(d));
|
||||
}
|
||||
s.edit("Image Trace View", |d, _| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
if n.extras_if_any().and_then(|e| e.trace.as_deref()).is_none_or(|t| !t.is_object()) {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom" })));
|
||||
}
|
||||
if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) {
|
||||
t.insert("view".into(), json!(view.id()));
|
||||
} else {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() })));
|
||||
if let Some(f) = split {
|
||||
t.insert("split".into(), json!(f));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "view": view.id() }))
|
||||
Ok(result(&s.doc()?.doc))
|
||||
}
|
||||
|
||||
pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
//! Creating art: shapes, paths, text.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, LiveShape, Node, NodeKind, TextObject};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, LiveShape, MAX_COORD, Node, NodeKind, TextObject};
|
||||
use vectorcraft_geom::curvature::{self, NoCircle};
|
||||
use vectorcraft_geom::{Affine, Anchor, AnchorKind, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::newart::NewArt;
|
||||
use super::{
|
||||
CommandSpec, NodeId, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers, has_doc,
|
||||
number_or, str_param, switch_or,
|
||||
index_opt, number_or, object_param, str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -75,6 +77,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
cmd!(
|
||||
"shape.curvatureCircle",
|
||||
"Curvature Circle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
|
||||
has_doc,
|
||||
curvature_circle
|
||||
),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
|
||||
cmd!(
|
||||
"shape.spiral",
|
||||
@@ -485,6 +496,51 @@ fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
|
||||
Ok(matches!(points.len(), 2 | 3).then_some(points))
|
||||
}
|
||||
|
||||
/// A live ellipse that touches a path at a point with the path's curvature there
|
||||
/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.curvatureCircle";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = index_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let seg = index_opt(p, "segment", C)?.ok_or_else(|| bad(C, "missing segment"))?;
|
||||
let t = f64_req(p, "t", C)?;
|
||||
if !(0.0..=1.0).contains(&t) {
|
||||
return Err(bad(C, "`t` must be from 0 to 1"));
|
||||
}
|
||||
let convex = switch_or(p, "convex", false, C)?;
|
||||
let found = {
|
||||
let st = s.doc()?;
|
||||
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if node.is_guide() {
|
||||
return Err(bad(C, "a guide has no curvature circle"));
|
||||
}
|
||||
let path = node.path_data().ok_or_else(|| bad(C, format!("object {id} is not a path")))?;
|
||||
let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(bad(C, "no such segment"));
|
||||
}
|
||||
curvature::curvature_circle_on(sp, seg, t, convex)
|
||||
};
|
||||
let circle = found.map_err(|e| match e {
|
||||
NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"),
|
||||
NoCircle::Cusp => bad(C, "the path has a cusp there, so it has no single curvature"),
|
||||
NoCircle::Corner => bad(C, "the path has a corner there, so it has no single curvature"),
|
||||
})?;
|
||||
let (center, radius) = (circle.center, circle.radius);
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) {
|
||||
return Err(bad(C, "the circle that matches the path there would reach past the canvas"));
|
||||
}
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays on the path.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
out["nominal"] = json!(circle.nominal);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
|
||||
@@ -28,6 +28,7 @@ mod commands;
|
||||
mod common;
|
||||
mod cut;
|
||||
mod freehand;
|
||||
mod quickpen;
|
||||
mod smooth;
|
||||
|
||||
pub use commands::specs;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment};
|
||||
use super::cut::{erase_region, erase_segments, knife, split};
|
||||
use super::freehand::{blob, freehand};
|
||||
use super::quickpen::quick_pen;
|
||||
use super::smooth::{join_scrub, smooth_region};
|
||||
use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection};
|
||||
|
||||
@@ -33,6 +34,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
curvature_edit
|
||||
),
|
||||
cmd!(
|
||||
"path.quickPen",
|
||||
"Quick Pen",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x, y] (a new path starts there), id? (or: draw on this path), subpath?: index (0), keep?: count (default: all its points; the points after the first `keep` are replaced), pieces?: [{x, y, action?: \"line\" (default)|\"continuousArc\"|\"sharpArc\", turn?: 1..359 degrees (180), flip?: bool}] (at most 10000), closed?: bool} draw a path of straight lines and circular arcs as the Quick Pen tool does, each piece from the path's last point to x, y: a line; a continuous arc, which leaves its start in the direction the path arrives in (with no direction, the first piece of a path, it is drawn as a sharp-corner arc; with its end straight ahead or straight behind, as a line); a sharp-corner arc, which turns through `turn` degrees and bulges to the left of the direction drawn (with flip, to the right). A piece that ends where the path does adds nothing. closed: a last piece that ends on the first point joins it, otherwise a straight segment closes the path. A new path takes the current paint (a black stroke when it has neither fill nor stroke); the path is selected, as one undo step → {id}. Without id, `start` must be given; with id, the subpath must be open and `start` is refused",
|
||||
has_doc,
|
||||
quick_pen
|
||||
),
|
||||
cmd!(
|
||||
"path.removeAnchor",
|
||||
"Delete Anchor Point",
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs.
|
||||
|
||||
use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke};
|
||||
|
||||
use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound};
|
||||
use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or};
|
||||
|
||||
const C: &str = "path.quickPen";
|
||||
/// The most pieces one request takes.
|
||||
const MAX_PIECES: usize = 10_000;
|
||||
|
||||
/// The `pieces` param.
|
||||
fn pieces(p: &Value) -> Result<Vec<Piece>> {
|
||||
let list = match p.get("pieces") {
|
||||
None | Some(Value::Null) => return Ok(vec![]),
|
||||
Some(Value::Array(list)) if list.len() <= MAX_PIECES => list,
|
||||
Some(_) => return Err(bad(C, "`pieces` must be a list of at most 10000 pieces")),
|
||||
};
|
||||
list.iter()
|
||||
.map(|v| {
|
||||
let to = point_entry(v, C)?;
|
||||
if !within_input_bound(to) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
let stroke = match v.get("action") {
|
||||
None | Some(Value::Null) => Stroke::Line,
|
||||
Some(a) => a.as_str().and_then(Stroke::parse).ok_or_else(|| {
|
||||
let key = "action";
|
||||
bad(C, format!("`{key}` must be one of {}", Stroke::ALL.map(Stroke::name).join(", ")))
|
||||
})?,
|
||||
};
|
||||
let turn = number_or(v, "turn", qp::DEFAULT_TURN, C)?;
|
||||
if !(qp::MIN_TURN..=qp::MAX_TURN).contains(&turn) {
|
||||
let (key, min, max) = ("turn", qp::MIN_TURN, qp::MAX_TURN);
|
||||
return Err(bad(C, format!("{key} must be a number from {min} to {max}")));
|
||||
}
|
||||
let flip = switch_or(v, "flip", false, C)?;
|
||||
Ok(Piece { to, stroke, turn, flip })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pieces = pieces(p)?;
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let start_given = p.get("start").is_some_and(|v| !v.is_null());
|
||||
let either = "give either `start` for a new path or `id`, not both";
|
||||
let Some(id) = object_param(p, "id", C)? else {
|
||||
let start = match p.get("start") {
|
||||
Some(v) if start_given => point_entry(v, C)?,
|
||||
_ => return Err(bad(C, either)),
|
||||
};
|
||||
if !within_input_bound(start) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
if ["subpath", "keep"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad(C, "`subpath` and `keep` need `id`"));
|
||||
}
|
||||
let sp = qp::build(&SubPath::new(vec![vectorcraft_geom::Anchor::corner(start)], false), &pieces, closed);
|
||||
let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ap = &mut look.appearance;
|
||||
if ap.stroke_paint().is_none() && ap.fill_paint().is_none() {
|
||||
ap.set_stroke(Paint::solid(Color::BLACK));
|
||||
}
|
||||
return add_look(s, "Quick Pen", path_kind(PathData::single(sp)), look, None);
|
||||
};
|
||||
if start_given {
|
||||
return Err(bad(C, either));
|
||||
}
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let d = &s.doc()?.doc;
|
||||
if !d.is_editable(id) {
|
||||
return Err(bad(C, "the path is locked or hidden"));
|
||||
}
|
||||
let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?;
|
||||
let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?;
|
||||
if sp.closed {
|
||||
return Err(bad(C, "the subpath is closed"));
|
||||
}
|
||||
let n = sp.anchors.len();
|
||||
let keep = usize_opt(p, "keep", C)?.unwrap_or(n);
|
||||
if keep == 0 || keep > n {
|
||||
let (key, min, max) = ("keep", 1, n);
|
||||
return Err(bad(C, format!("{key} must be a number from {min} to {max}")));
|
||||
}
|
||||
let base = SubPath::new(sp.anchors.get_range(..keep).unwrap_or_default(), false);
|
||||
let out = qp::build(&base, &pieces, closed);
|
||||
let top = super::super::path::compound_or_self(d, id);
|
||||
s.edit("Quick Pen", |d, sel| {
|
||||
let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?;
|
||||
*slot = out;
|
||||
sel.set([top]);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
@@ -28,6 +30,7 @@
|
||||
mod action_batch;
|
||||
mod affinity;
|
||||
mod batch;
|
||||
mod cdr;
|
||||
pub mod dxf;
|
||||
pub mod dxfimport;
|
||||
mod encode;
|
||||
@@ -175,6 +178,10 @@ mod tests_affinity;
|
||||
#[cfg(test)]
|
||||
mod tests_artboard_fill;
|
||||
#[cfg(test)]
|
||||
mod tests_cdr;
|
||||
#[cfg(test)]
|
||||
mod tests_cmx;
|
||||
#[cfg(test)]
|
||||
mod tests_pdf;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfcolor;
|
||||
|
||||
@@ -68,6 +68,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("commands".into(), Value::Array(cmds));
|
||||
}
|
||||
if !s.previewing {
|
||||
s.note_shape_drawn("command.batch", &entry);
|
||||
s.journal.push(("command.batch".into(), entry));
|
||||
}
|
||||
Ok(json!({ "results": results }))
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the pages, layers,
|
||||
//! guidelines, groups, curves, rectangles, ellipses, arcs and polygons with uniform fills and
|
||||
//! outlines, their hidden and locked states, fill rules and uniform transparency that
|
||||
//! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become
|
||||
//! artboards side by side; layers of the same name on different pages become one layer where the
|
||||
//! pages stack them in the same order. What the
|
||||
//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). `.cmx` exchange
|
||||
//! files with 32-bit coordinates are mapped the same way, with their own warnings ([`cmx_note`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Affine, Rect};
|
||||
use vectorcraft_cdr::model::{self as cd, LayerKind};
|
||||
use vectorcraft_cdr::{Limits, Warning};
|
||||
use vectorcraft_doc::{Artboard, ColorMode, Document, Guide, LayerColor, Node, NodeKind};
|
||||
|
||||
use super::load::err;
|
||||
use crate::Result;
|
||||
|
||||
mod shapes;
|
||||
|
||||
const UNSUPPORTED_OBJECTS: &str = "CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out";
|
||||
const UNSUPPORTED_FILLS: &str = "CDR fountain, pattern, texture and PostScript fills were left out";
|
||||
const UNKNOWN_COLORS: &str = "colors in CDR color models VectorCraft doesn't read were opened as black";
|
||||
const SPOT_LOOKS: &str = "CDR library colors that the drawing stores only by number were opened as black spot colors";
|
||||
const ARROWHEADS: &str = "CDR outline arrowheads were left out";
|
||||
const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under them keep their outlines";
|
||||
const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque";
|
||||
const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out";
|
||||
const DAMAGED: &str = "damaged parts of the drawing were left out";
|
||||
const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard";
|
||||
|
||||
const CMX_UNSUPPORTED_OBJECTS: &str =
|
||||
"CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out";
|
||||
const CMX_UNSUPPORTED_FILLS: &str = "CMX fills other than uniform colors were left out";
|
||||
const CMX_UNKNOWN_COLORS: &str = "colors in CMX color models VectorCraft doesn't read were opened as black";
|
||||
const CMX_SPOT_LOOKS: &str = "CMX library colors that the file stores only by number were opened as black spot colors";
|
||||
const CMX_ARROWHEADS: &str = "CMX outline arrowheads were left out";
|
||||
const CMX_LENSES: &str = "CMX lenses were not applied";
|
||||
const CMX_PAGES_CUT: &str = "CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard";
|
||||
|
||||
/// What reading a drawing left out or changed, for each kind the reader reports.
|
||||
fn note(w: Warning) -> &'static str {
|
||||
match w {
|
||||
Warning::UnsupportedObjects => UNSUPPORTED_OBJECTS,
|
||||
Warning::UnsupportedFills => UNSUPPORTED_FILLS,
|
||||
Warning::UnknownColors => UNKNOWN_COLORS,
|
||||
Warning::SpotLooks => SPOT_LOOKS,
|
||||
Warning::Arrowheads => ARROWHEADS,
|
||||
Warning::Envelopes => ENVELOPES,
|
||||
Warning::Lenses => LENSES,
|
||||
Warning::TooDeep => TOO_DEEP,
|
||||
Warning::Damaged => DAMAGED,
|
||||
}
|
||||
}
|
||||
|
||||
/// What reading a `.cmx` file left out or changed. The reader reports no envelopes in one.
|
||||
fn cmx_note(w: Warning) -> &'static str {
|
||||
match w {
|
||||
Warning::UnsupportedObjects | Warning::Envelopes => CMX_UNSUPPORTED_OBJECTS,
|
||||
Warning::UnsupportedFills => CMX_UNSUPPORTED_FILLS,
|
||||
Warning::UnknownColors => CMX_UNKNOWN_COLORS,
|
||||
Warning::SpotLooks => CMX_SPOT_LOOKS,
|
||||
Warning::Arrowheads => CMX_ARROWHEADS,
|
||||
Warning::Lenses => CMX_LENSES,
|
||||
Warning::TooDeep => TOO_DEEP,
|
||||
Warning::Damaged => DAMAGED,
|
||||
}
|
||||
}
|
||||
|
||||
/// The page size used when neither the page nor the document settings give one: US Letter,
|
||||
/// VectorCraft's own choice.
|
||||
const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0);
|
||||
/// The layer that holds guidelines at angles other than horizontal and vertical, as guide paths.
|
||||
const GUIDES_LAYER: &str = "Guides";
|
||||
/// The hidden layer that holds hidden guidelines.
|
||||
const HIDDEN_GUIDES_LAYER: &str = "Hidden guides";
|
||||
/// The most pages read, as artboards: the most a new document may have.
|
||||
const MAX_PAGES: usize = crate::cmd::newdoc::MAX_ARTBOARDS as usize;
|
||||
/// The longest page side, in points: the longest artboard side a new document may have.
|
||||
const MAX_PAGE_SIDE: f64 = 16383.0 * 10.0;
|
||||
/// The gap between pages laid side by side, in points.
|
||||
const PAGE_GAP: f64 = 36.0;
|
||||
/// The most objects, subpaths and path segments copied from master layers onto pages, all pages
|
||||
/// together: the `.af` importer's budget for its master pages (`affinity/master_copies.rs`).
|
||||
const MAX_MASTER_COPIES: usize = 1 << 23;
|
||||
/// The most guides and guide paths made, the master page's copied onto every page included.
|
||||
const MAX_GUIDES: usize = 100_000;
|
||||
/// The most layers made from the master page's and the pages' layers: VectorCraft's own limit.
|
||||
const MAX_LAYERS: usize = 10_000;
|
||||
|
||||
/// Is `bytes` a `.cdr` drawing this importer reads?
|
||||
pub(super) fn is_cdr(bytes: &[u8]) -> bool {
|
||||
vectorcraft_cdr::is_cdr(bytes)
|
||||
}
|
||||
|
||||
pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let d = vectorcraft_cdr::read(bytes, Limits::default()).map_err(|e| match e {
|
||||
vectorcraft_cdr::Error::Version(v) => {
|
||||
let version = v / 100;
|
||||
err(format!("CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27"))
|
||||
}
|
||||
why => err(format!("this CDR drawing can't be read ({why})")),
|
||||
})?;
|
||||
Ok(build(&d, note, PAGES_CUT))
|
||||
}
|
||||
|
||||
/// Is `bytes` a `.cmx` file, of any byte order or coordinate size?
|
||||
pub(super) fn is_cmx(bytes: &[u8]) -> bool {
|
||||
vectorcraft_cdr::is_cmx(bytes)
|
||||
}
|
||||
|
||||
/// A `.cmx` file with 32-bit coordinates: its pages, layers, groups and curves with uniform fills
|
||||
/// and outlines, mapped as a `.cdr` drawing's are.
|
||||
pub(super) fn import_cmx(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let d = vectorcraft_cdr::read_cmx(bytes, Limits::default()).map_err(|why| err(format!("this CMX file can't be read ({why})")))?;
|
||||
Ok(build(&d, cmx_note, CMX_PAGES_CUT))
|
||||
}
|
||||
|
||||
/// The document of `d`, and one warning for each kind of content left out or changed.
|
||||
fn build(d: &cd::Drawing, note: fn(Warning) -> &'static str, pages_cut: &str) -> (Document, Vec<String>) {
|
||||
let mut b = shapes::Builder::new();
|
||||
let mut doc = b.document(d);
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
for w in d.warnings.iter().chain(&b.notes) {
|
||||
if !warnings.iter().any(|x| x == note(*w)) {
|
||||
warnings.push(note(*w).to_string());
|
||||
}
|
||||
}
|
||||
if b.pages_cut {
|
||||
warnings.push(pages_cut.to_string());
|
||||
}
|
||||
doc.limit_depth_noting(&mut warnings);
|
||||
(doc, warnings)
|
||||
}
|
||||
|
||||
/// Where each page lies in the document: its artboard, and the map from its own space (points
|
||||
/// from its centre, y up) into the document.
|
||||
struct Placed {
|
||||
rect: Rect,
|
||||
to_doc: Affine,
|
||||
}
|
||||
|
||||
/// Pages laid out by [`place_pages`].
|
||||
struct Layout {
|
||||
placed: Vec<Placed>,
|
||||
/// Pages past [`MAX_PAGES`] or past the document's range were left out.
|
||||
left_out: bool,
|
||||
/// A page side longer than [`MAX_PAGE_SIDE`] was cut to it.
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
/// The pages' artboards side by side, each side held to 1 to [`MAX_PAGE_SIDE`] points.
|
||||
fn place_pages(d: &cd::Drawing) -> Layout {
|
||||
let mut x = 0.0;
|
||||
let size = |p: &cd::Page| p.size.or(d.page_size).unwrap_or(FALLBACK_PAGE);
|
||||
let sizes: Vec<(f64, f64)> =
|
||||
if d.pages.is_empty() { vec![d.page_size.unwrap_or(FALLBACK_PAGE)] } else { d.pages.iter().take(MAX_PAGES).map(size).collect() };
|
||||
let mut placed = Vec::with_capacity(sizes.len());
|
||||
let mut cut = false;
|
||||
for (w, h) in sizes {
|
||||
let long = w > MAX_PAGE_SIDE || h > MAX_PAGE_SIDE;
|
||||
let (w, h) = (w.clamp(1.0, MAX_PAGE_SIDE), h.clamp(1.0, MAX_PAGE_SIDE));
|
||||
if x + w > crate::MAX_COORD {
|
||||
break;
|
||||
}
|
||||
cut |= long;
|
||||
let rect = Rect::new(x, 0.0, x + w, h);
|
||||
placed.push(Placed { rect, to_doc: Affine::translate((x + w / 2.0, h / 2.0)) * Affine::FLIP_Y });
|
||||
x += w + PAGE_GAP;
|
||||
}
|
||||
let left_out = placed.len() < d.pages.len();
|
||||
Layout { placed, left_out, cut }
|
||||
}
|
||||
|
||||
impl shapes::Builder {
|
||||
fn document(&mut self, d: &cd::Drawing) -> Document {
|
||||
self.learn_spots(d);
|
||||
let Layout { placed, left_out, cut } = place_pages(d);
|
||||
if left_out {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
}
|
||||
self.pages_cut = cut;
|
||||
let (w, h) = placed.first().map_or(FALLBACK_PAGE, |p| (p.rect.width(), p.rect.height()));
|
||||
let mut doc = Document::new(w, h);
|
||||
doc.artboards = placed
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| Artboard {
|
||||
id: i as u32 + 1,
|
||||
name: format!("Page {}", i + 1),
|
||||
rect: p.rect,
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
})
|
||||
.collect();
|
||||
self.doc = doc;
|
||||
self.name_spots();
|
||||
// Bottom to top: the master page's layers, then the pages' in the order first seen.
|
||||
let mut layers: Vec<LayerOut> = Vec::new();
|
||||
// A layer is known by its name and how many layers of that name the page has below it, so
|
||||
// two layers of one name on a page stay two layers. Each key keeps every layer made for
|
||||
// it, bottom to top.
|
||||
let mut by_name: HashMap<(String, usize), Vec<usize>> = HashMap::new();
|
||||
self.master_layers(d, &placed, &mut layers);
|
||||
// The pages' layers go above the master page's.
|
||||
let pages_from = layers.len();
|
||||
for (i, (page, p)) in d.pages.iter().zip(&placed).enumerate() {
|
||||
let artboard = Some(i as u32 + 1);
|
||||
let mut seen: HashMap<&str, usize> = HashMap::new();
|
||||
// The layer this page's last layer went to: the next one goes above it.
|
||||
let mut below: Option<usize> = None;
|
||||
// The file lists layers front to back.
|
||||
for (j, l) in page.layers.iter().rev().enumerate() {
|
||||
self.guides(&l.guides, p, artboard);
|
||||
if l.kind != LayerKind::Drawing && l.kind != LayerKind::Desktop {
|
||||
continue;
|
||||
}
|
||||
let art = self.objects(&l.objects, p.to_doc);
|
||||
let n = seen.entry(l.name.as_str()).or_insert(0);
|
||||
let key = (l.name.clone(), *n);
|
||||
*n += 1;
|
||||
// A layer an earlier page stacked below this page's last one would put this page's
|
||||
// art in the wrong order, so the page gets a new layer of that name instead, just
|
||||
// above its last one. Of the layers of that name above the last one, the lowest
|
||||
// takes the art.
|
||||
match by_name.get(&key).and_then(|is| is.iter().copied().find(|&i| below.is_none_or(|b| i > b))) {
|
||||
Some(i) => {
|
||||
if let Some(out) = layers.get_mut(i) {
|
||||
out.add(art, l.flags);
|
||||
}
|
||||
below = Some(i);
|
||||
}
|
||||
None if layers.len() >= MAX_LAYERS => self.notes.push(Warning::TooDeep),
|
||||
None => {
|
||||
// The page's bottom layer goes below the lowest layer that the rest of the
|
||||
// page shares with earlier pages, so the page keeps its own order. When the
|
||||
// page shares none, it goes on top, in the order the layers were first seen.
|
||||
let at = match below {
|
||||
Some(b) => b + 1,
|
||||
None => {
|
||||
let mut counts = seen.clone();
|
||||
page.layers
|
||||
.iter()
|
||||
.rev()
|
||||
.skip(j + 1)
|
||||
.filter(|l| l.kind == LayerKind::Drawing || l.kind == LayerKind::Desktop)
|
||||
.filter_map(|l| {
|
||||
let n = counts.entry(l.name.as_str()).or_insert(0);
|
||||
let key = (l.name.clone(), *n);
|
||||
*n += 1;
|
||||
by_name.get(&key).and_then(|is| is.first().copied())
|
||||
})
|
||||
.min()
|
||||
.unwrap_or(layers.len())
|
||||
.max(pages_from)
|
||||
}
|
||||
};
|
||||
if at < layers.len() {
|
||||
for i in by_name.values_mut().flatten().filter(|i| **i >= at) {
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
let is = by_name.entry(key).or_default();
|
||||
is.insert(is.partition_point(|&i| i < at), at);
|
||||
let mut out = LayerOut::new(l.name.clone());
|
||||
out.add(art, l.flags);
|
||||
layers.insert(at, out);
|
||||
below = Some(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Guidelines every page shows, on each page's artboard.
|
||||
for (i, p) in placed.iter().enumerate() {
|
||||
self.guides(&d.guides, p, Some(i as u32 + 1));
|
||||
}
|
||||
if !self.guide_paths.is_empty() {
|
||||
let paths = std::mem::take(&mut self.guide_paths);
|
||||
// At the layer limit the guide paths go on the top shown layer instead of a layer of
|
||||
// their own; when every layer is hidden they go on the top one, with the limit warning.
|
||||
let full = layers.len() >= MAX_LAYERS;
|
||||
let top = layers.iter().rposition(|l| !l.hidden()).unwrap_or(layers.len().saturating_sub(1));
|
||||
match layers.get_mut(top) {
|
||||
Some(out) if full => {
|
||||
if out.hidden() {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
}
|
||||
out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default())));
|
||||
}
|
||||
_ => {
|
||||
let mut out = LayerOut::new(GUIDES_LAYER.to_string());
|
||||
out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default())));
|
||||
layers.push(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Hidden guidelines go on a hidden layer of their own on top; past the layer limit they
|
||||
// are left out.
|
||||
if !self.hidden_guides.is_empty() || !self.hidden_paths.is_empty() {
|
||||
if layers.len() >= MAX_LAYERS {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
} else {
|
||||
let mut art = std::mem::take(&mut self.hidden_paths);
|
||||
for g in std::mem::take(&mut self.hidden_guides) {
|
||||
let kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard };
|
||||
art.push(Arc::new(Node::new(self.doc.alloc_id(), kind)));
|
||||
}
|
||||
let mut out = LayerOut::new(HIDDEN_GUIDES_LAYER.to_string());
|
||||
out.add(art, cd::Flags { hidden: true, locked: false });
|
||||
layers.push(out);
|
||||
}
|
||||
}
|
||||
let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0));
|
||||
doc.layers = layers.into_iter().enumerate().map(|(i, out)| out.finish(&mut doc, i)).collect();
|
||||
if doc.layers.is_empty() {
|
||||
let l = layer(&mut doc, "Layer 1", 0, Vec::new(), cd::Flags::default());
|
||||
doc.layers.push(l);
|
||||
}
|
||||
// Ruler guides go at the top of the top shown layer, in the order they were read. When
|
||||
// every layer is hidden they go on a layer of their own on top; past the layer limit they
|
||||
// go on the hidden top layer, with the limit warning.
|
||||
let guides: Vec<Arc<Node>> = std::mem::take(&mut self.guide_list)
|
||||
.into_iter()
|
||||
.map(|g| Arc::new(Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard })))
|
||||
.collect();
|
||||
if !guides.is_empty() && !doc.layers.iter().any(|l| l.visible) && doc.layers.len() < MAX_LAYERS {
|
||||
let i = doc.layers.len();
|
||||
let l = layer(&mut doc, GUIDES_LAYER, i, Vec::new(), cd::Flags::default());
|
||||
doc.layers.push(l);
|
||||
}
|
||||
let top = doc.layers.iter().rposition(|l| l.visible).unwrap_or(doc.layers.len().saturating_sub(1));
|
||||
if !guides.is_empty() && doc.layers.get(top).is_some_and(|l| !l.visible) {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
}
|
||||
if let Some(kids) = doc.layers.get_mut(top).and_then(|l| Arc::make_mut(l).children_mut()) {
|
||||
kids.extend(guides);
|
||||
}
|
||||
self.finish_swatches(&mut doc);
|
||||
if self.cmyk > self.rgb {
|
||||
doc.color_mode = ColorMode::Cmyk;
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// The master page's layers: the desktop's objects once, on the first page's space; other
|
||||
/// layers' objects on every page, as many copies as [`MAX_MASTER_COPIES`] allows.
|
||||
fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec<LayerOut>) {
|
||||
for l in d.master.iter().rev() {
|
||||
if layers.len() >= MAX_LAYERS {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
break;
|
||||
}
|
||||
let frames: Vec<&Placed> = if l.kind == LayerKind::Desktop { placed.iter().take(1).collect() } else { placed.iter().collect() };
|
||||
let mut art = Vec::new();
|
||||
let count = copy_cost(&l.objects);
|
||||
for p in frames {
|
||||
if count > self.copies_left {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
break;
|
||||
}
|
||||
self.copies_left -= count;
|
||||
art.extend(self.objects(&l.objects, p.to_doc));
|
||||
}
|
||||
let name = if l.name.is_empty() { "Master".to_string() } else { l.name.clone() };
|
||||
let mut out = LayerOut::new(name);
|
||||
out.add(art, l.flags);
|
||||
layers.push(out);
|
||||
}
|
||||
}
|
||||
|
||||
/// `guides` of a page placed by `p`: horizontal and vertical ones as guides of the page's
|
||||
/// artboard, others as guide paths.
|
||||
fn guides(&mut self, guides: &[cd::Guideline], p: &Placed, artboard: Option<u32>) {
|
||||
for g in guides {
|
||||
if self.guide_list.len() + self.guide_paths.len() + self.hidden_guides.len() + self.hidden_paths.len() >= MAX_GUIDES {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
return;
|
||||
}
|
||||
let at = p.to_doc * kurbo::Point::new(g.at.x, g.at.y);
|
||||
let turn = g.angle.rem_euclid(180.0);
|
||||
if !(at.x.is_finite() && at.y.is_finite() && at.x.abs() <= crate::MAX_COORD && at.y.abs() <= crate::MAX_COORD) {
|
||||
self.notes.push(Warning::TooDeep);
|
||||
continue;
|
||||
}
|
||||
let list = if g.hidden { &mut self.hidden_guides } else { &mut self.guide_list };
|
||||
if turn.abs() < 1e-9 {
|
||||
list.push(Guide { artboard, ..Guide::new(false, at.y) });
|
||||
} else if (turn - 90.0).abs() < 1e-9 {
|
||||
list.push(Guide { artboard, ..Guide::new(true, at.x) });
|
||||
} else {
|
||||
self.angled_guide(at, g.angle, p.rect, g.hidden);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What one copy of `objects` takes: each object, each subpath and segment of its path, and each
|
||||
/// dash of its outline, since every copy builds its own path and dash pattern.
|
||||
fn copy_cost(objects: &[cd::Object]) -> usize {
|
||||
let mut n: usize = 0;
|
||||
let mut stack: Vec<&cd::Object> = objects.iter().collect();
|
||||
while let Some(o) = stack.pop() {
|
||||
n = n.saturating_add(1);
|
||||
match o {
|
||||
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
|
||||
cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)),
|
||||
cd::Object::Clip { container, objects } => {
|
||||
// A container whose outline is behind its fill is built twice, as that outline
|
||||
// and as the clipping path, inside a group of their own.
|
||||
n = n.saturating_add(shape_cost(container));
|
||||
// The second path, without the dashes, which only the outline shape has, and the
|
||||
// group around the two.
|
||||
if container.outline.as_ref().is_some_and(|o| o.behind_fill) {
|
||||
n = n.saturating_add(2 + path_cost(container));
|
||||
}
|
||||
stack.extend(objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// What one copy of shape `s` takes past the object itself: its path's subpaths and segments and
|
||||
/// its outline's dashes.
|
||||
fn shape_cost(s: &cd::Shape) -> usize {
|
||||
path_cost(s).saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len()))
|
||||
}
|
||||
|
||||
/// The subpaths and segments of shape `s`'s path.
|
||||
fn path_cost(s: &cd::Shape) -> usize {
|
||||
match &s.geometry {
|
||||
cd::Geometry::Path(p) => p.subpaths.iter().fold(0usize, |n, sp| n.saturating_add(1 + sp.segments.len())),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A document layer being made from the drawing's layers of one name: its art bottom to top, each
|
||||
/// part with the flags of the layer it came from, and those flags for every layer merged into it.
|
||||
struct LayerOut {
|
||||
name: String,
|
||||
kids: Vec<(Arc<Node>, cd::Flags)>,
|
||||
merged: Vec<cd::Flags>,
|
||||
}
|
||||
|
||||
impl LayerOut {
|
||||
fn new(name: String) -> Self {
|
||||
LayerOut { name, kids: Vec::new(), merged: Vec::new() }
|
||||
}
|
||||
|
||||
/// Whether the layer node will be hidden: every drawing layer merged into it is.
|
||||
fn hidden(&self) -> bool {
|
||||
!self.merged.is_empty() && self.merged.iter().all(|f| f.hidden)
|
||||
}
|
||||
|
||||
/// Adds the art of a drawing layer with flags `flags`.
|
||||
fn add(&mut self, art: Vec<Arc<Node>>, flags: cd::Flags) {
|
||||
self.kids.extend(art.into_iter().map(|n| (n, flags)));
|
||||
self.merged.push(flags);
|
||||
}
|
||||
|
||||
/// The layer node, as the `i`th layer from the bottom. It is hidden or locked when every
|
||||
/// drawing layer merged into it is; otherwise the art of a hidden or locked drawing layer is
|
||||
/// hidden or locked object by object.
|
||||
fn finish(self, doc: &mut Document, i: usize) -> Arc<Node> {
|
||||
let all = |f: fn(&cd::Flags) -> bool| !self.merged.is_empty() && self.merged.iter().all(f);
|
||||
let own = cd::Flags { hidden: all(|f| f.hidden), locked: all(|f| f.locked) };
|
||||
let kids = self
|
||||
.kids
|
||||
.into_iter()
|
||||
.map(|(n, f)| shapes::with_flags(n, cd::Flags { hidden: f.hidden && !own.hidden, locked: f.locked && !own.locked }))
|
||||
.collect();
|
||||
layer(doc, &self.name, i, kids, own)
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer of the document named `name` holding `kids` (bottom to top), hidden or locked as
|
||||
/// `flags` say.
|
||||
fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec<Arc<Node>>, flags: cd::Flags) -> Arc<Node> {
|
||||
let name = if name.is_empty() { format!("Layer {}", i + 1) } else { name.to_string() };
|
||||
let mut n = Node::layer(doc.alloc_id(), &name, LayerColor::Preset((i % 9) as u8));
|
||||
n.visible = !flags.hidden;
|
||||
n.locked = flags.locked;
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = kids;
|
||||
}
|
||||
Arc::new(n)
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
//! A drawing's objects as VectorCraft art: paths, live rectangles and ellipses, groups, solid
|
||||
//! fills and strokes, and the spot colors they use as swatches.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Affine, BezPath, Point, Rect};
|
||||
use vectorcraft_cdr::Warning;
|
||||
use vectorcraft_cdr::model::{self as cd, Geometry};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{BlendMode, Color, Paint, Swatch};
|
||||
use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::geom::{FillRule, PathData};
|
||||
use vectorcraft_doc::{Document, Guide, Knockout, LiveShape, Node, NodeKind};
|
||||
|
||||
/// The most nested groups mapped; the reader holds nesting well below it.
|
||||
const MAX_DEPTH: usize = 256;
|
||||
/// The width, in points, of a stroke made from an outline of width 0: the width PDF import gives a
|
||||
/// line width of 0 (`crates/pdf/src/import/state.rs`).
|
||||
const HAIRLINE: f64 = 0.25;
|
||||
|
||||
pub(super) struct Builder {
|
||||
pub(super) doc: Document,
|
||||
/// What mapping left out, as the reader's warning kinds.
|
||||
pub(super) notes: Vec<Warning>,
|
||||
/// A page side was cut to the longest artboard side.
|
||||
pub(super) pages_cut: bool,
|
||||
/// What copies of master art onto the pages may still take ([`super::MAX_MASTER_COPIES`] at
|
||||
/// the start).
|
||||
pub(super) copies_left: usize,
|
||||
/// Horizontal and vertical guidelines, as guides of the pages' artboards.
|
||||
pub(super) guide_list: Vec<Guide>,
|
||||
/// Guidelines at other angles, as guide paths.
|
||||
pub(super) guide_paths: Vec<Arc<Node>>,
|
||||
/// Hidden guidelines, as guides and guide paths of a hidden layer of their own.
|
||||
pub(super) hidden_guides: Vec<Guide>,
|
||||
pub(super) hidden_paths: Vec<Arc<Node>>,
|
||||
/// Colors read in each model, which picks the document's color mode.
|
||||
pub(super) cmyk: usize,
|
||||
pub(super) rgb: usize,
|
||||
/// The spot colors used, in the order first seen, with their full-strength color and the tint
|
||||
/// of the use it was worked out from (`None`: the file stores no color for it).
|
||||
spots: Vec<(String, Color, Option<f32>)>,
|
||||
spot_index: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
pub(super) fn new() -> Self {
|
||||
Builder {
|
||||
doc: Document::new(1.0, 1.0),
|
||||
notes: Vec::new(),
|
||||
pages_cut: false,
|
||||
copies_left: super::MAX_MASTER_COPIES,
|
||||
guide_list: Vec::new(),
|
||||
guide_paths: Vec::new(),
|
||||
hidden_guides: Vec::new(),
|
||||
hidden_paths: Vec::new(),
|
||||
cmyk: 0,
|
||||
rgb: 0,
|
||||
spots: Vec::new(),
|
||||
spot_index: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every spot color `d` uses, with its full-strength color taken from its use at the highest
|
||||
/// tint: a use at a low tint keeps little of the color, and one at 0% keeps none.
|
||||
pub(super) fn learn_spots(&mut self, d: &cd::Drawing) {
|
||||
let layers = d.pages.iter().flat_map(|p| &p.layers).chain(&d.master);
|
||||
let mut stack: Vec<&cd::Object> = layers.flat_map(|l| &l.objects).collect();
|
||||
while let Some(o) = stack.pop() {
|
||||
match o {
|
||||
cd::Object::Shape(s) => {
|
||||
for c in s.fill.iter().chain(s.outline.iter().map(|o| &o.color)) {
|
||||
self.learn_spot(c);
|
||||
}
|
||||
}
|
||||
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
|
||||
cd::Object::Clip { container, objects } => {
|
||||
for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) {
|
||||
self.learn_spot(c);
|
||||
}
|
||||
stack.extend(objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Note spot color `c`, keeping the full-strength color of its use at the highest tint.
|
||||
fn learn_spot(&mut self, c: &cd::Color) -> Option<Color> {
|
||||
let cd::Color::Spot { name, tint, look } = c else { return None };
|
||||
let seen = look.map(|_| *tint);
|
||||
let base = look.map_or(Color::BLACK, |[r, g, b]| Color::rgb(r, g, b));
|
||||
let Some(&i) = self.spot_index.get(name) else {
|
||||
self.spot_index.insert(name.clone(), self.spots.len());
|
||||
self.spots.push((name.clone(), base, seen));
|
||||
return Some(base);
|
||||
};
|
||||
let slot = self.spots.get_mut(i)?;
|
||||
if seen.is_some() && seen > slot.2 {
|
||||
slot.1 = base;
|
||||
slot.2 = seen;
|
||||
}
|
||||
Some(slot.1)
|
||||
}
|
||||
|
||||
fn note(&mut self, w: Warning) {
|
||||
if !self.notes.contains(&w) {
|
||||
self.notes.push(w);
|
||||
}
|
||||
}
|
||||
|
||||
/// `objects` (front to back, as the file lists them) bottom to top, mapped by `to_doc`.
|
||||
pub(super) fn objects(&mut self, objects: &[cd::Object], to_doc: Affine) -> Vec<Arc<Node>> {
|
||||
self.objects_at(objects, to_doc, 0)
|
||||
}
|
||||
|
||||
fn objects_at(&mut self, objects: &[cd::Object], to_doc: Affine, depth: usize) -> Vec<Arc<Node>> {
|
||||
if depth > MAX_DEPTH {
|
||||
self.note(Warning::TooDeep);
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::with_capacity(objects.len());
|
||||
for o in objects.iter().rev() {
|
||||
match o {
|
||||
cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))),
|
||||
cd::Object::Group { objects: kids, flags } => {
|
||||
let children = self.objects_at(kids, to_doc, depth + 1);
|
||||
if !children.is_empty() {
|
||||
let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }));
|
||||
out.push(with_flags(group, *flags));
|
||||
}
|
||||
}
|
||||
// A clipping group whose clipping path keeps the container's paint: its fill
|
||||
// behind the clipped objects and its outline over them.
|
||||
cd::Object::Clip { container, objects } => {
|
||||
// A clipping path's stroke paints over the clipped objects, so an outline
|
||||
// behind the fill becomes a shape of its own below the clipping group, the
|
||||
// two in a group of their own.
|
||||
let behind = container.outline.as_ref().is_some_and(|o| o.behind_fill);
|
||||
let (outline, clip) = if behind {
|
||||
let outline = self.shape(&cd::Shape { fill: None, ..(**container).clone() }, to_doc, false);
|
||||
(outline, self.shape(&cd::Shape { outline: None, ..(**container).clone() }, to_doc, true))
|
||||
} else {
|
||||
(None, self.shape(container, to_doc, true))
|
||||
};
|
||||
let Some(clip) = clip else { continue };
|
||||
let mut children = vec![clip];
|
||||
children.extend(self.objects_at(objects, to_doc, depth + 1));
|
||||
let mut group = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true });
|
||||
// A see-through container's fill knocks out the outline behind it, so the two
|
||||
// parts do not add up their transparency where they overlap; the clipped
|
||||
// objects inside still combine as usual.
|
||||
let knock = outline.is_some() && (container.opacity < 1.0 || container.blend != cd::Blend::Normal);
|
||||
if knock {
|
||||
group.knockout = Knockout::Off;
|
||||
}
|
||||
let group = Arc::new(group);
|
||||
// The container's flags hide or lock the whole clipping group.
|
||||
let whole = match outline {
|
||||
Some(outline) => {
|
||||
let children = vec![outline, group];
|
||||
let mut pair = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false });
|
||||
if knock {
|
||||
pair.knockout = Knockout::On;
|
||||
}
|
||||
Arc::new(pair)
|
||||
}
|
||||
None => group,
|
||||
};
|
||||
out.push(with_flags(whole, container.flags));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Shape `s` placed by `to_doc`; as a clipping path when `clipping`.
|
||||
fn shape(&mut self, s: &cd::Shape, to_doc: Affine, clipping: bool) -> Option<Arc<Node>> {
|
||||
let m = to_doc * affine(&s.matrix);
|
||||
let (path, live) = match &s.geometry {
|
||||
Geometry::Path(p) => (PathData::from_bezpath(&(m * bez(p))), None),
|
||||
Geometry::Rect { w, h, radii } => live_rect(*w, *h, *radii, m)?,
|
||||
Geometry::Ellipse { w, h } => {
|
||||
let (x0, y0) = (w.min(0.0), h.min(0.0));
|
||||
let live = LiveShape::Ellipse { w: w.abs(), h: h.abs(), pie: (0.0, 360.0), xf: m * Affine::translate((x0, y0)) };
|
||||
(live.to_path(), Some(live))
|
||||
}
|
||||
};
|
||||
if path.is_empty() || !in_range(&path) {
|
||||
self.note(Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
// In paint order: an outline behind the fill comes first.
|
||||
let mut items = Vec::new();
|
||||
if let Some(o) = s.outline.as_ref().filter(|o| o.behind_fill) {
|
||||
items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix)));
|
||||
}
|
||||
if let Some(c) = &s.fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(self.paint(c))));
|
||||
}
|
||||
if let Some(o) = s.outline.as_ref().filter(|o| !o.behind_fill) {
|
||||
items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix)));
|
||||
}
|
||||
// Without the winding flag, a curve of several subpaths is filled with holes where they
|
||||
// overlap: VectorCraft's own choice of rule for it.
|
||||
let rule = if s.nonzero { FillRule::NonZero } else { FillRule::EvenOdd };
|
||||
let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping, guide: false });
|
||||
n.appearance = Appearance { items, ..Appearance::default() }.into();
|
||||
n.opacity = if s.opacity.is_finite() { s.opacity.clamp(0.0, 1.0) } else { 1.0 };
|
||||
n.blend = blend(s.blend);
|
||||
Some(Arc::new(n))
|
||||
}
|
||||
|
||||
/// The stroke of outline `o` on a shape placed by `matrix`.
|
||||
fn stroke(&mut self, o: &cd::Outline, matrix: &cd::Matrix) -> StrokeLayer {
|
||||
// The width of an outline scaled with the shape is multiplied by the square root of the
|
||||
// matrix's area factor (R50). For a matrix that scales x and y differently, that width is
|
||||
// VectorCraft's own value.
|
||||
let width = if o.scale_with {
|
||||
let [a, b, c, d, _, _] = matrix.0;
|
||||
o.width * (a * d - b * c).abs().sqrt()
|
||||
} else {
|
||||
o.width
|
||||
};
|
||||
// A drawn outline of width 0 shows as a hairline, as a PDF line width of 0 does.
|
||||
let width = if width.is_finite() && width > 0.0 { width.min(1000.0) } else { HAIRLINE };
|
||||
let mut l = StrokeLayer::new(self.paint(&o.color), width);
|
||||
l.cap = match o.cap {
|
||||
cd::Cap::Butt => LineCap::Butt,
|
||||
cd::Cap::Round => LineCap::Round,
|
||||
cd::Cap::Square => LineCap::Square,
|
||||
};
|
||||
l.join = match o.join {
|
||||
cd::Join::Miter => LineJoin::Miter,
|
||||
cd::Join::Round => LineJoin::Round,
|
||||
cd::Join::Bevel => LineJoin::Bevel,
|
||||
};
|
||||
// Dashes are stored in multiples of the outline's width.
|
||||
if !o.dashes.is_empty() && width > 0.0 {
|
||||
let pattern: Vec<f64> = o.dashes.iter().map(|d| d * width).collect();
|
||||
l.dash = Some(Dash { pattern, offset: 0.0, align_corners: false });
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn paint(&mut self, c: &cd::Color) -> Paint {
|
||||
match c {
|
||||
cd::Color::Rgb([r, g, b]) => {
|
||||
self.rgb += 1;
|
||||
Paint::solid(Color::rgb(*r, *g, *b))
|
||||
}
|
||||
cd::Color::Cmyk([c, m, y, k]) => {
|
||||
self.cmyk += 1;
|
||||
Paint::solid(Color::cmyk(*c, *m, *y, *k))
|
||||
}
|
||||
cd::Color::Gray(k) => Paint::solid(Color::Gray { k: *k }),
|
||||
cd::Color::Registration => Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(REGISTRATION.into()), tint: 1.0 },
|
||||
cd::Color::Spot { name, tint, .. } => {
|
||||
let base = self.learn_spot(c).unwrap_or(Color::BLACK);
|
||||
let tint = tint.clamp(0.0, 1.0);
|
||||
let swatch = self.spot_index.get(name).and_then(|&i| self.spots.get(i)).map_or_else(|| name.clone(), |s| s.0.clone());
|
||||
Paint::Solid { color: base.tinted(tint), swatch: Some(swatch), tint }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives each spot color a swatch name of its own in the new document: a name its swatches,
|
||||
/// color groups or Registration already use becomes the first free "name 2", "name 3"…, so
|
||||
/// the ink stays a spot color. The drawing's other spot names are kept as they are. Call it
|
||||
/// once the document is made and before any paint.
|
||||
pub(super) fn name_spots(&mut self) {
|
||||
let mut free = self.doc.free_swatch_names();
|
||||
let clashes: Vec<bool> = self.spots.iter().map(|s| s.0 == REGISTRATION || self.doc.swatch_name_taken(&s.0)).collect();
|
||||
for (s, _) in self.spots.iter().zip(&clashes).filter(|(_, c)| !**c) {
|
||||
free.take(&s.0);
|
||||
}
|
||||
for (s, _) in self.spots.iter_mut().zip(&clashes).filter(|(_, c)| **c) {
|
||||
s.0 = free.take(&s.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The spot colors the drawing used, as global spot swatches; a swatch of the same name the
|
||||
/// document already has is kept as it is.
|
||||
pub(super) fn finish_swatches(&mut self, doc: &mut Document) {
|
||||
self.spot_index.clear();
|
||||
for (name, color, _) in std::mem::take(&mut self.spots) {
|
||||
if !doc.swatches.iter().any(|s| s.name == name) {
|
||||
doc.swatches.push(Swatch { name, paint: Paint::solid(color), global: true, spot: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A guideline through `at` (document space) at `angle` degrees counterclockwise, as a guide
|
||||
/// path from edge to edge of the page `rect`, so it moves with the page's artboard. A
|
||||
/// guideline that misses the page runs through `at` for the page's diagonal each way. A
|
||||
/// `hidden` one goes with the hidden guides.
|
||||
pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect, hidden: bool) {
|
||||
let (s, c) = angle.to_radians().sin_cos();
|
||||
// The document's y axis points down.
|
||||
let dir = kurbo::Vec2::new(c, -s);
|
||||
let (a, b) = match chord(at, dir, rect) {
|
||||
Some((t0, t1)) => (at + dir * t0, at + dir * t1),
|
||||
None => {
|
||||
let d = dir * rect.width().hypot(rect.height()).max(1.0);
|
||||
(at - d, at + d)
|
||||
}
|
||||
};
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(a);
|
||||
bp.line_to(b);
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
if !in_range(&path) {
|
||||
self.note(Warning::TooDeep);
|
||||
return;
|
||||
}
|
||||
let n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true });
|
||||
if hidden { self.hidden_paths.push(Arc::new(n)) } else { self.guide_paths.push(Arc::new(n)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the line through `at` along the unit vector `dir` crosses `rect`: the distances along
|
||||
/// it to the two edges it meets, the nearer first. None when it misses `rect` or only touches it
|
||||
/// at a point.
|
||||
fn chord(at: Point, dir: kurbo::Vec2, rect: Rect) -> Option<(f64, f64)> {
|
||||
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
for (p, d, min, max) in [(at.x, dir.x, rect.x0, rect.x1), (at.y, dir.y, rect.y0, rect.y1)] {
|
||||
if d.abs() < 1e-12 {
|
||||
if p < min || p > max {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
let (t0, t1) = ((min - p) / d, (max - p) / d);
|
||||
lo = lo.max(t0.min(t1));
|
||||
hi = hi.min(t0.max(t1));
|
||||
}
|
||||
}
|
||||
(lo.is_finite() && hi.is_finite() && hi - lo > 1e-9).then_some((lo, hi))
|
||||
}
|
||||
|
||||
fn affine(m: &cd::Matrix) -> Affine {
|
||||
Affine::new(m.0)
|
||||
}
|
||||
|
||||
fn blend(b: cd::Blend) -> BlendMode {
|
||||
match b {
|
||||
cd::Blend::Normal => BlendMode::Normal,
|
||||
cd::Blend::Multiply => BlendMode::Multiply,
|
||||
cd::Blend::Screen => BlendMode::Screen,
|
||||
cd::Blend::Overlay => BlendMode::Overlay,
|
||||
cd::Blend::SoftLight => BlendMode::SoftLight,
|
||||
cd::Blend::HardLight => BlendMode::HardLight,
|
||||
cd::Blend::ColorDodge => BlendMode::ColorDodge,
|
||||
cd::Blend::ColorBurn => BlendMode::ColorBurn,
|
||||
cd::Blend::Darken => BlendMode::Darken,
|
||||
cd::Blend::Lighten => BlendMode::Lighten,
|
||||
cd::Blend::Difference => BlendMode::Difference,
|
||||
cd::Blend::Exclusion => BlendMode::Exclusion,
|
||||
cd::Blend::Hue => BlendMode::Hue,
|
||||
cd::Blend::Saturation => BlendMode::Saturation,
|
||||
cd::Blend::Color => BlendMode::Color,
|
||||
cd::Blend::Luminosity => BlendMode::Luminosity,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` hidden or locked as `flags` say; left as it is when they say neither.
|
||||
pub(super) fn with_flags(mut n: Arc<Node>, flags: cd::Flags) -> Arc<Node> {
|
||||
if flags.hidden || flags.locked {
|
||||
let m = Arc::make_mut(&mut n);
|
||||
m.visible &= !flags.hidden;
|
||||
m.locked |= flags.locked;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn bez(p: &cd::Path) -> BezPath {
|
||||
let pt = |q: cd::Pt| Point::new(q.x, q.y);
|
||||
let mut bp = BezPath::new();
|
||||
for s in &p.subpaths {
|
||||
bp.move_to(pt(s.start));
|
||||
for seg in &s.segments {
|
||||
match *seg {
|
||||
cd::Segment::Line(e) => bp.line_to(pt(e)),
|
||||
cd::Segment::Cubic(a, b, e) => bp.curve_to(pt(a), pt(b), pt(e)),
|
||||
}
|
||||
}
|
||||
if s.closed {
|
||||
bp.close_path();
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// A rectangle from the origin to (`w`, `h`) with `radii` counterclockwise from its corner at
|
||||
/// (`w`, 0), placed by `m`, as a live rectangle: each radius stays on the corner it belongs to,
|
||||
/// whichever way `w` and `h` point.
|
||||
fn live_rect(w: f64, h: f64, radii: [f64; 4], m: Affine) -> Option<(PathData, Option<LiveShape>)> {
|
||||
if !(w.is_finite() && h.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (x0, y1, ww, hh) = (w.min(0.0), h.max(0.0), w.abs(), h.abs());
|
||||
// The live shape's own space has its origin at the top-left and y pointing down.
|
||||
let to_file = Affine::translate((x0, y1)) * Affine::FLIP_Y;
|
||||
let corners = [(w, 0.0), (w, h), (0.0, h), (0.0, 0.0)];
|
||||
let mut live_radii = [0.0; 4];
|
||||
for ((px, py), r) in corners.into_iter().zip(radii) {
|
||||
let (lx, ly) = (px - x0, y1 - py);
|
||||
let right = lx > ww / 2.0;
|
||||
let bottom = ly > hh / 2.0;
|
||||
let i = match (right, bottom) {
|
||||
(false, false) => 0,
|
||||
(true, false) => 1,
|
||||
(true, true) => 2,
|
||||
(false, true) => 3,
|
||||
};
|
||||
if let Some(slot) = live_radii.get_mut(i) {
|
||||
*slot = if r.is_finite() { r.max(0.0) } else { 0.0 };
|
||||
}
|
||||
}
|
||||
let mut live = LiveShape::Rectangle { w: ww, h: hh, radii: live_radii, kinds: Default::default(), radii_relative: false, xf: m * to_file };
|
||||
live.fold_scale();
|
||||
Some((live.to_path(), Some(live)))
|
||||
}
|
||||
|
||||
/// Whether every control point of `path` is finite and within `MAX_COORD` of the origin.
|
||||
fn in_range(path: &PathData) -> bool {
|
||||
path.control_bounds().is_some_and(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A named spot color takes its full-strength color from its use at the highest tint, wherever
|
||||
/// that use comes in the drawing: a use at 0% stores only white.
|
||||
#[test]
|
||||
fn a_spot_color_keeps_its_color_from_its_strongest_use() {
|
||||
let red = [1.0, 0.0, 0.0];
|
||||
let shape = |tint: f32, look: [f32; 3]| {
|
||||
cd::Object::Shape(Box::new(cd::Shape::new(
|
||||
Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
|
||||
cd::Matrix::IDENTITY,
|
||||
Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }),
|
||||
None,
|
||||
)))
|
||||
};
|
||||
for objects in [vec![shape(0.0, [1.0; 3]), shape(1.0, red)], vec![shape(1.0, red), shape(0.0, [1.0; 3])]] {
|
||||
let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects, guides: vec![] };
|
||||
let d = cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: vec![cd::Page { size: None, layers: vec![layer] }],
|
||||
master: vec![],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
};
|
||||
let doc = Builder::new().document(&d);
|
||||
let swatch = doc.swatches.iter().find(|s| s.name == "Red ink").unwrap();
|
||||
assert_eq!(swatch.paint, Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let layer = doc.layers.first().unwrap().children().unwrap();
|
||||
let full = layer.iter().find_map(|n| match n.appearance.items.first() {
|
||||
Some(AppearanceItem::Fill(f)) => match &f.paint {
|
||||
Paint::Solid { color, tint, .. } if *tint == 1.0 => Some(*color),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(full, Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
/// A spot color named like one of a new document's process swatches gets a numbered name that
|
||||
/// no other spot color of the drawing uses, and its paint names that spot swatch.
|
||||
#[test]
|
||||
fn a_spot_color_named_like_a_default_swatch_stays_a_spot_color() {
|
||||
let shape = |name: &str| {
|
||||
cd::Object::Shape(Box::new(cd::Shape::new(
|
||||
Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
|
||||
cd::Matrix::IDENTITY,
|
||||
Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }),
|
||||
None,
|
||||
)))
|
||||
};
|
||||
let layer = cd::Layer {
|
||||
name: "L".into(),
|
||||
kind: cd::LayerKind::Drawing,
|
||||
flags: cd::Flags::default(),
|
||||
objects: vec![shape("Black"), shape("Black 2")],
|
||||
guides: vec![],
|
||||
};
|
||||
let d = cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: vec![cd::Page { size: None, layers: vec![layer] }],
|
||||
master: vec![],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
};
|
||||
assert!(Document::new(612.0, 792.0).swatches.iter().any(|s| s.name == "Black" && !s.spot));
|
||||
let doc = Builder::new().document(&d);
|
||||
let layer = doc.layers.first().unwrap().children().unwrap();
|
||||
let mut names: Vec<String> = layer
|
||||
.iter()
|
||||
.filter_map(|n| match n.appearance.items.first() {
|
||||
Some(AppearanceItem::Fill(f)) => match &f.paint {
|
||||
Paint::Solid { swatch: Some(name), .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["Black 2", "Black 3"]);
|
||||
for name in &names {
|
||||
let swatch = doc.swatches.iter().find(|s| &s.name == name).unwrap();
|
||||
assert!(swatch.spot && swatch.global, "{name}: {swatch:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies of master art onto the pages take from the budget by their objects, subpaths and
|
||||
/// segments: a curve of 300 segments costs 302 each time it is copied.
|
||||
#[test]
|
||||
fn master_copies_count_their_path_segments() {
|
||||
let segments = (1..=300).map(|i| cd::Segment::Line(cd::Pt { x: f64::from(i), y: 0.0 })).collect();
|
||||
let curve = cd::Object::Shape(Box::new(cd::Shape::new(
|
||||
Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }),
|
||||
cd::Matrix::IDENTITY,
|
||||
None,
|
||||
None,
|
||||
)));
|
||||
let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![curve], guides: vec![] };
|
||||
let d = cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: (0..10).map(|_| cd::Page { size: None, layers: vec![] }).collect(),
|
||||
master: vec![master],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
};
|
||||
let mut b = Builder::new();
|
||||
b.copies_left = 1000;
|
||||
let doc = b.document(&d);
|
||||
let copies = doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len());
|
||||
assert_eq!(copies, 3, "1,000 holds three copies of 302");
|
||||
assert!(b.notes.contains(&Warning::TooDeep));
|
||||
}
|
||||
|
||||
/// Copies of master art take from the budget by the dashes of their outlines too: a rectangle
|
||||
/// whose outline has 299 dashes costs 300 each time it is copied.
|
||||
#[test]
|
||||
fn master_copies_count_their_dashes() {
|
||||
let outline = cd::Outline {
|
||||
width: 1.0,
|
||||
color: cd::Color::Gray(1.0),
|
||||
cap: cd::Cap::Butt,
|
||||
join: cd::Join::Miter,
|
||||
dashes: vec![1.0; 299],
|
||||
behind_fill: false,
|
||||
scale_with: false,
|
||||
};
|
||||
let rect = cd::Object::Shape(Box::new(cd::Shape::new(
|
||||
Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
|
||||
cd::Matrix::IDENTITY,
|
||||
None,
|
||||
Some(outline),
|
||||
)));
|
||||
let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![rect], guides: vec![] };
|
||||
let d = cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: (0..10).map(|_| cd::Page { size: None, layers: vec![] }).collect(),
|
||||
master: vec![master],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
};
|
||||
let mut b = Builder::new();
|
||||
b.copies_left = 1000;
|
||||
let doc = b.document(&d);
|
||||
let copies = doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len());
|
||||
assert_eq!(copies, 3, "1,000 holds three copies of 300");
|
||||
assert!(b.notes.contains(&Warning::TooDeep));
|
||||
}
|
||||
|
||||
/// An outline scaled with the shape takes the square root of the matrix's area factor on its
|
||||
/// width and dashes; another outline keeps its stored width under the same matrix.
|
||||
#[test]
|
||||
fn outlines_scaled_with_the_shape_scale_their_width_and_dashes() {
|
||||
// A matrix that scales by 2 and 8 and skews: area factor 2 * 8 - 3 * 0 = 16, mean scale 4.
|
||||
let matrix = cd::Matrix([2.0, 0.0, 3.0, 8.0, 5.0, 5.0]);
|
||||
for (scale_with, width, dashes) in [(true, 6.0, [12.0, 6.0]), (false, 1.5, [3.0, 1.5])] {
|
||||
let outline = cd::Outline {
|
||||
width: 1.5,
|
||||
color: cd::Color::Gray(1.0),
|
||||
cap: cd::Cap::Butt,
|
||||
join: cd::Join::Miter,
|
||||
dashes: vec![2.0, 1.0],
|
||||
behind_fill: false,
|
||||
scale_with,
|
||||
};
|
||||
let rect = cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, None, Some(outline));
|
||||
let mut b = Builder::new();
|
||||
let Some(node) = b.shape(&rect, Affine::IDENTITY, false) else { panic!("{scale_with}: no shape") };
|
||||
let [AppearanceItem::Stroke(s)] = node.appearance.items.as_slice() else { panic!("{scale_with}: {:?}", node.appearance.items) };
|
||||
assert!((s.width - width).abs() < 1e-9, "{scale_with}: {}", s.width);
|
||||
let pattern = s.dash.as_ref().map(|d| d.pattern.clone());
|
||||
assert_eq!(pattern, Some(dashes.to_vec()), "{scale_with}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape's opacity, blend mode and fill rule reach its path; a shape without them is opaque,
|
||||
/// normal and filled even-odd.
|
||||
#[test]
|
||||
fn opacity_blend_and_fill_rule_reach_the_path() {
|
||||
let square = Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] };
|
||||
let plain = cd::Shape::new(square.clone(), cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None);
|
||||
let seen = cd::Shape { nonzero: true, opacity: 0.25, blend: cd::Blend::Multiply, ..plain.clone() };
|
||||
let mut b = Builder::new();
|
||||
for (s, opacity, blend, nonzero) in [(&plain, 1.0, BlendMode::Normal, false), (&seen, 0.25, BlendMode::Multiply, true)] {
|
||||
let Some(n) = b.shape(s, Affine::IDENTITY, false) else { panic!("no shape") };
|
||||
let NodeKind::Path { rule, .. } = &n.kind else { panic!("{:?}", n.kind) };
|
||||
assert_eq!((n.opacity, n.blend, *rule == FillRule::NonZero), (opacity, blend, nonzero));
|
||||
}
|
||||
let wild = cd::Shape { opacity: f32::NAN, ..plain };
|
||||
assert_eq!(b.shape(&wild, Affine::IDENTITY, false).map(|n| n.opacity), Some(1.0));
|
||||
}
|
||||
|
||||
/// Ruler guides go on the top shown layer, or on a layer of their own when every layer is
|
||||
/// hidden; hidden guidelines go on a hidden layer of their own.
|
||||
#[test]
|
||||
fn ruler_guides_stay_off_hidden_layers() {
|
||||
let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, None, None);
|
||||
let hidden = cd::Flags { hidden: true, locked: false };
|
||||
let layer = |name: &str, flags: cd::Flags| cd::Layer {
|
||||
name: name.into(),
|
||||
kind: cd::LayerKind::Drawing,
|
||||
flags,
|
||||
objects: vec![cd::Object::Shape(Box::new(square()))],
|
||||
guides: vec![],
|
||||
};
|
||||
let guides_of = |layers: Vec<cd::Layer>, hidden: bool| {
|
||||
let d = cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: vec![cd::Page { size: None, layers }],
|
||||
master: vec![],
|
||||
guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden }],
|
||||
warnings: vec![],
|
||||
};
|
||||
let doc = Builder::new().document(&d);
|
||||
doc.layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let n = l.children().map_or(0, |k| k.iter().filter(|n| matches!(n.kind, NodeKind::RulerGuide { .. })).count());
|
||||
(l.name.clone().unwrap_or_default(), l.visible, n)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// Front to back: "Top" hidden over "Base" shown.
|
||||
let got = guides_of(vec![layer("Top", hidden), layer("Base", cd::Flags::default())], false);
|
||||
assert_eq!(got, [("Base".to_string(), true, 1), ("Top".to_string(), false, 0)]);
|
||||
let got = guides_of(vec![layer("Only", hidden)], false);
|
||||
assert_eq!(got, [("Only".to_string(), false, 0), ("Guides".to_string(), true, 1)]);
|
||||
let got = guides_of(vec![layer("Base", cd::Flags::default())], true);
|
||||
assert_eq!(got, [("Base".to_string(), true, 0), ("Hidden guides".to_string(), false, 1)]);
|
||||
// At the layer limit an angled guideline's path goes on the top shown layer.
|
||||
let mut layers: Vec<cd::Layer> = (0..super::super::MAX_LAYERS).map(|i| layer(&format!("L{i}"), cd::Flags::default())).collect();
|
||||
layers[0].flags = hidden;
|
||||
let d = cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: vec![cd::Page { size: None, layers }],
|
||||
master: vec![],
|
||||
guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 45.0, hidden: false }],
|
||||
warnings: vec![],
|
||||
};
|
||||
let mut b = Builder::new();
|
||||
let doc = b.document(&d);
|
||||
let with_path: Vec<(bool, bool)> = doc
|
||||
.layers
|
||||
.iter()
|
||||
.rev()
|
||||
.take(2)
|
||||
.map(|l| (l.visible, l.children().is_some_and(|k| k.iter().any(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))))
|
||||
.collect();
|
||||
assert_eq!(with_path, [(false, false), (true, true)]);
|
||||
assert!(!b.notes.contains(&Warning::TooDeep));
|
||||
// With every layer hidden as well, the guides go on the top layer with the limit warning.
|
||||
let mut d = d;
|
||||
for l in &mut d.pages[0].layers {
|
||||
l.flags = hidden;
|
||||
}
|
||||
d.guides.push(cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden: false });
|
||||
let mut b = Builder::new();
|
||||
let doc = b.document(&d);
|
||||
assert!(doc.layers.iter().all(|l| !l.visible));
|
||||
assert!(b.notes.contains(&Warning::TooDeep), "{:?}", b.notes);
|
||||
}
|
||||
|
||||
/// A see-through container whose outline is behind its fill knocks the outline out under its
|
||||
/// fill, and its clipping group keeps its own objects combining as usual; an opaque one leaves
|
||||
/// the pair a plain group.
|
||||
#[test]
|
||||
fn a_see_through_container_with_its_outline_behind_knocks_it_out() {
|
||||
let outline = cd::Outline {
|
||||
width: 4.0,
|
||||
color: cd::Color::Gray(1.0),
|
||||
cap: cd::Cap::Butt,
|
||||
join: cd::Join::Miter,
|
||||
dashes: vec![],
|
||||
behind_fill: true,
|
||||
scale_with: false,
|
||||
};
|
||||
let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(0.5)), None);
|
||||
for (opacity, knockout, inner) in [(1.0, Knockout::Neutral, Knockout::Neutral), (0.5, Knockout::On, Knockout::Off)] {
|
||||
let container = Box::new(cd::Shape { opacity, outline: Some(outline.clone()), ..square() });
|
||||
let clip = cd::Object::Clip { container, objects: vec![cd::Object::Shape(Box::new(square()))] };
|
||||
let nodes = Builder::new().objects(&[clip], Affine::IDENTITY);
|
||||
let [pair] = nodes.as_slice() else { panic!("{nodes:?}") };
|
||||
let NodeKind::Group { children, clip: false } = &pair.kind else { panic!("{:?}", pair.kind) };
|
||||
assert_eq!(pair.knockout, knockout, "{opacity}");
|
||||
let clipping = children.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. }));
|
||||
assert_eq!(clipping.map(|n| n.knockout), Some(inner), "{opacity}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A hidden or locked shape, group or clipping container gives its node those states. A layer
|
||||
/// is hidden or locked when every drawing layer merged into it is; otherwise only the art of
|
||||
/// the hidden or locked drawing layer is.
|
||||
#[test]
|
||||
fn hidden_and_locked_flags_reach_the_nodes() {
|
||||
let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None);
|
||||
let hidden = cd::Flags { hidden: true, locked: false };
|
||||
let locked = cd::Flags { hidden: false, locked: true };
|
||||
let objects = vec![
|
||||
cd::Object::Shape(Box::new(cd::Shape { flags: hidden, ..square() })),
|
||||
cd::Object::Group { objects: vec![cd::Object::Shape(Box::new(square()))], flags: locked },
|
||||
cd::Object::Clip { container: Box::new(cd::Shape { flags: hidden, ..square() }), objects: vec![cd::Object::Shape(Box::new(square()))] },
|
||||
];
|
||||
let layer =
|
||||
|flags: cd::Flags, objects: Vec<cd::Object>| cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags, objects, guides: vec![] };
|
||||
let drawing = |pages: Vec<Vec<cd::Layer>>| cd::Drawing {
|
||||
version: 1300,
|
||||
page_size: None,
|
||||
pages: pages.into_iter().map(|layers| cd::Page { size: None, layers }).collect(),
|
||||
master: vec![],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
};
|
||||
let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags::default(), objects)]]));
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
// Bottom to top: the clipping group, the group, the shape.
|
||||
let states: Vec<(bool, bool)> = kids.iter().map(|n| (n.visible, n.locked)).collect();
|
||||
assert_eq!(states, [(false, false), (true, true), (false, false)]);
|
||||
assert!(doc.layers[0].visible && !doc.layers[0].locked);
|
||||
// One name on two pages: hidden on the first only, then on both.
|
||||
let one = || vec![cd::Object::Shape(Box::new(square()))];
|
||||
let doc = Builder::new().document(&drawing(vec![vec![layer(hidden, one())], vec![layer(cd::Flags::default(), one())]]));
|
||||
assert_eq!(doc.layers.len(), 1);
|
||||
assert!(doc.layers[0].visible);
|
||||
let states: Vec<bool> = doc.layers[0].children().unwrap().iter().map(|n| n.visible).collect();
|
||||
assert_eq!(states, [false, true]);
|
||||
let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags { hidden: true, locked: true }, one())], vec![layer(hidden, one())]]));
|
||||
assert!(!doc.layers[0].visible && !doc.layers[0].locked);
|
||||
let states: Vec<(bool, bool)> = doc.layers[0].children().unwrap().iter().map(|n| (n.visible, n.locked)).collect();
|
||||
assert_eq!(states, [(true, true), (true, false)]);
|
||||
}
|
||||
|
||||
/// A corner rounded in the file stays on the same corner of the page, however the rectangle's
|
||||
/// size points.
|
||||
#[test]
|
||||
fn rectangle_radii_stay_on_their_corners() {
|
||||
// Only the corner at (w, 0) rounded; the page flips y as the document does.
|
||||
for (w, h) in [(100.0, 50.0), (-100.0, 50.0), (100.0, -50.0), (-100.0, -50.0)] {
|
||||
let (path, _) = live_rect(w, h, [10.0, 0.0, 0.0, 0.0], Affine::FLIP_Y).unwrap();
|
||||
let rounded = Point::new(w, -0.0);
|
||||
let bp = path.to_bezpath();
|
||||
// No anchor sits on the rounded corner itself; the other three corners are anchors.
|
||||
let anchors: Vec<Point> = bp.elements().iter().filter_map(|e| e.end_point()).collect();
|
||||
assert!(!anchors.iter().any(|p| (*p - rounded).hypot() < 1e-6), "{w} {h}: {anchors:?}");
|
||||
for c in [Point::new(w, -h), Point::new(0.0, -h), Point::new(0.0, 0.0)] {
|
||||
assert!(anchors.iter().any(|p| (*p - c).hypot() < 1e-6), "{w} {h}: {c:?} not in {anchors:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -532,6 +532,14 @@ pub const FORMATS: &[Format] = &[
|
||||
reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true),
|
||||
// jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it.
|
||||
reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true),
|
||||
// `.cdr` drawings of versions 1 to 27 (`WL` files, RIFF files from version 3, and the ZIP packages of 14 on), read by
|
||||
// `vectorcraft-cdr`; a `.cdt` template opens as a new untitled document. Exports don't write
|
||||
// them.
|
||||
reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
// `.cmx` exchange files with 32-bit coordinates, read by `vectorcraft-cdr`; exports don't write
|
||||
// them.
|
||||
reader("cmx", "CMX", &["cmx"], "image/x-cmx", false),
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
];
|
||||
@@ -591,17 +599,20 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"af",
|
||||
"afdesign",
|
||||
"afpub",
|
||||
"cdr",
|
||||
"cdt",
|
||||
"cmx",
|
||||
];
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
/// The packaging declares no type for HP-GL plot files or PICT pictures either.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -688,6 +699,9 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"af",
|
||||
"afdesign",
|
||||
"afpub",
|
||||
"cdr",
|
||||
"cdt",
|
||||
"cmx",
|
||||
"txt",
|
||||
"rtf",
|
||||
"docx",
|
||||
|
||||
@@ -92,6 +92,13 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if vectorcraft_affinity::is_affinity(bytes) {
|
||||
return format("affinity");
|
||||
}
|
||||
if super::cdr::is_cdr(bytes) {
|
||||
// A template keeps its meaning from the extension.
|
||||
return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr"));
|
||||
}
|
||||
if super::cdr::is_cmx(bytes) {
|
||||
return format("cmx");
|
||||
}
|
||||
if vectorcraft_format::sniff(bytes) {
|
||||
// A template keeps its meaning from the extension, like .ait.
|
||||
return by_name.filter(|f| f.id == "template").or_else(|| format("vectorcraft"));
|
||||
@@ -541,6 +548,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
preview_only = i.preview_only;
|
||||
(i.doc, i.warnings, false)
|
||||
}
|
||||
"cdr" | "cdt" => {
|
||||
let (doc, warnings) = super::cdr::import(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"cmx" => {
|
||||
let (doc, warnings) = super::cdr::import_cmx(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
|
||||
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
|
||||
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
|
||||
@@ -930,11 +945,13 @@ fn open_loaded(
|
||||
let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } =
|
||||
loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
|
||||
// EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing
|
||||
// fallbacks must ask before overwriting the richer source they could not fully read.
|
||||
// fallbacks must ask before overwriting the richer source they could not fully read. Every
|
||||
// warning of a `.cdr` drawing or a `.cmx` file names content the import left out or changed.
|
||||
let losses: Vec<String> = warnings
|
||||
.iter()
|
||||
.filter(|w| {
|
||||
is_loss(w)
|
||||
|| matches!(format.id, "cdr" | "cdt" | "cmx")
|
||||
|| (format.id == "eps"
|
||||
&& (matches!(w.as_str(), EDITING_DAMAGED | EDITING_STALE)
|
||||
|| w.starts_with("this file's PostScript couldn't be read")
|
||||
@@ -943,9 +960,9 @@ fn open_loaded(
|
||||
.cloned()
|
||||
.collect();
|
||||
let source_path = path.clone().filter(|_| !losses.is_empty());
|
||||
// A template (saved by Save as Template, or an .ait/.vctemplate file) opens as a new untitled
|
||||
// document.
|
||||
let template = as_template || doc.template || matches!(format.id, "ait" | "template");
|
||||
// A template (saved by Save as Template, or an .ait, .vctemplate or .cdt file) opens as a new
|
||||
// untitled document.
|
||||
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt");
|
||||
if template {
|
||||
doc.template = false;
|
||||
doc.title = s.next_untitled();
|
||||
|
||||
@@ -636,8 +636,8 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
|
||||
/// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3,
|
||||
/// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener`
|
||||
/// options over it; images with see-through pixels and colorized images, including those in
|
||||
/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and
|
||||
/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
|
||||
/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions and keep no
|
||||
/// alpha, and discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
|
||||
/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is)
|
||||
/// and whether its transparency was flattened.
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, Option<FlattenOptions>)> {
|
||||
@@ -655,8 +655,9 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
|
||||
o.preserve_overprints &= set.advanced.overprint == Overprint::Preserve;
|
||||
o.no_transparency = Some(see_through_images(doc));
|
||||
// Without soft masks a rasterized area can't be a rectangle with see-through pixels around
|
||||
// its art: it is clipped to its regions (opaque inside them).
|
||||
// its art: it is clipped to its regions (opaque inside them). Rasters keep no alpha either.
|
||||
o.clip_complex_regions = true;
|
||||
o.preserve_alpha = false;
|
||||
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
|
||||
Some(flat) => (Some(flat), Some(o)),
|
||||
None => (shown, None),
|
||||
|
||||
@@ -0,0 +1,618 @@
|
||||
//! `.cdr` drawings: Open, Place and New from Template, by extension and by content, mapped to
|
||||
//! artboards, layers, guides, live shapes, solid paint and strokes.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use vectorcraft_cdr::synth::{self, V, chunk, list};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeKind};
|
||||
|
||||
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<Node>) {
|
||||
for n in nodes {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => walk(children, out),
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
_ => out.push((**n).clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paths(doc: &vectorcraft_doc::Document) -> Vec<Node> {
|
||||
let mut out = Vec::new();
|
||||
walk(&doc.layers, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_version_opens_as_editable_art() {
|
||||
// Versions 14 on are ZIP packages.
|
||||
for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 2000, 2700] {
|
||||
let mut s = Session::new();
|
||||
let r = open_bytes(&mut s, "drawing.cdr", &synth::sample_file(version, version >= 700), None).unwrap();
|
||||
assert_eq!(r["format"], "cdr", "{version}");
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect();
|
||||
assert!(w.iter().any(|w| w.contains("text, bitmaps")), "{version}: {w:?}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards.len(), 1);
|
||||
assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0));
|
||||
// The page's layer "Art", above the master page's desktop layer.
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names.last().map(String::as_str), Some("Art"), "{version}: {names:?}");
|
||||
let p = paths(doc);
|
||||
// Five shapes on the page and one on the desktop.
|
||||
assert_eq!(p.len(), 6, "{version}");
|
||||
let rect = p.iter().find(
|
||||
|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Rectangle { w, .. } if (w - 100.0).abs() < 0.1)),
|
||||
);
|
||||
let rect = rect.unwrap_or_else(|| panic!("{version}: no live rectangle"));
|
||||
let NodeKind::Path { live: Some(live), .. } = &rect.kind else { unreachable_in_test() };
|
||||
let LiveShape::Rectangle { radii, .. } = **live else { unreachable_in_test() };
|
||||
assert!(radii.iter().all(|r| (r - 5.0).abs() < 0.1), "{version}: {radii:?}");
|
||||
assert!(p.iter().any(|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Ellipse { .. }))));
|
||||
// The rectangle is filled red and stroked 2 pt with round caps.
|
||||
let a = &rect.appearance;
|
||||
assert_eq!(a.items.len(), 2, "{version}");
|
||||
// The master page's vertical guideline at 36 pt right of the page centre, a ruler guide
|
||||
// on the top layer.
|
||||
if version >= 600 {
|
||||
let guides = doc.ruler_guides();
|
||||
let top = doc.layers.last().map(|l| l.id);
|
||||
assert!(
|
||||
guides.iter().any(|g| g.vertical && (g.pos - (306.0 + 36.0)).abs() < 0.05 && g.artboard == Some(1) && g.layer == top),
|
||||
"{version}: {guides:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unreachable_in_test() -> ! {
|
||||
panic!("the match above already checked the shape")
|
||||
}
|
||||
|
||||
/// The live rectangle of `doc` that is 100 pt wide, with its node.
|
||||
fn sample_rect(doc: &vectorcraft_doc::Document) -> Node {
|
||||
paths(doc)
|
||||
.into_iter()
|
||||
.find(|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Rectangle { w, .. } if (w - 100.0).abs() < 0.1)))
|
||||
.unwrap_or_else(|| panic!("no live rectangle"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_3_and_4_open_and_place_as_editable_art() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, LineCap, LineJoin};
|
||||
for version in [300, 400] {
|
||||
let bytes = synth::sample(version, false);
|
||||
let mut s = Session::new();
|
||||
// By its name, and by its content under another name.
|
||||
for name in ["drawing.cdr", "renamed.bin"] {
|
||||
let r = open_bytes(&mut s, name, &bytes, None).unwrap();
|
||||
assert_eq!(r["format"], "cdr", "{version} {name}");
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect();
|
||||
assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}");
|
||||
}
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}");
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names.last().map(String::as_str), Some("Art"), "{version}: {names:?}");
|
||||
assert_eq!(paths(doc).len(), 6, "{version}");
|
||||
let rect = sample_rect(doc);
|
||||
let NodeKind::Path { live: Some(live), path, .. } = &rect.kind else { unreachable_in_test() };
|
||||
let LiveShape::Rectangle { radii, .. } = **live else { unreachable_in_test() };
|
||||
assert!(radii.iter().all(|r| (r - 5.0).abs() < 0.1), "{version}: {radii:?}");
|
||||
// 100 pt left of and above the page centre, y pointing down in the document.
|
||||
let b = path.bounds().unwrap();
|
||||
assert!((b.x0 - 206.0).abs() < 0.2 && (b.y1 - 296.0).abs() < 0.2, "{version}: {b:?}");
|
||||
let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = rect.appearance.items.as_slice() else {
|
||||
panic!("{version}: {:?}", rect.appearance.items)
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), "{version}");
|
||||
assert!((stroke.width - 2.0).abs() < 0.05, "{version}: {}", stroke.width);
|
||||
assert_eq!((stroke.cap, stroke.join), (LineCap::Round, LineJoin::Round), "{version}");
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()), "{version}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_1_and_2_open_and_place_as_editable_art() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::AppearanceItem;
|
||||
for marker in *b"elm" {
|
||||
let bytes = synth::wl_sample(marker);
|
||||
let mut s = Session::new();
|
||||
for name in ["drawing.cdr", "renamed.bin"] {
|
||||
let r = open_bytes(&mut s, name, &bytes, None).unwrap();
|
||||
assert_eq!(r["format"], "cdr", "{name}");
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect();
|
||||
assert!(w.len() == 1 && w[0].contains("text, bitmaps"), "{w:?}");
|
||||
}
|
||||
assert_eq!(detect("drawing.cdt", &bytes).map(|f| f.id), Some("cdt"));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards.len(), 1);
|
||||
assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0));
|
||||
assert_eq!(doc.layers.len(), 1);
|
||||
// Bottom first in the document: the curve, the ellipse, then the rectangle in front.
|
||||
let p = paths(doc);
|
||||
assert_eq!(p.len(), 3);
|
||||
assert!(matches!(&p[1].kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Ellipse { .. })));
|
||||
let rect = sample_rect(doc);
|
||||
assert_eq!(rect.id, p[2].id);
|
||||
let NodeKind::Path { path, .. } = &rect.kind else { unreachable_in_test() };
|
||||
let b = path.bounds().unwrap();
|
||||
assert!((b.x0 - 206.0).abs() < 0.2 && (b.y1 - 296.0).abs() < 0.2 && (b.height() - 50.0).abs() < 0.2, "{b:?}");
|
||||
let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = rect.appearance.items.as_slice() else {
|
||||
panic!("{:?}", rect.appearance.items)
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)));
|
||||
assert_eq!(stroke.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
assert!((stroke.width - 2.0).abs() < 0.05, "{}", stroke.width);
|
||||
// The curve is drawn at twice its size by its matrix: 100 pt wide.
|
||||
let NodeKind::Path { path, .. } = &p[0].kind else { panic!("{:?}", p[0].kind) };
|
||||
assert!((path.bounds().unwrap().width() - 100.0).abs() < 0.2);
|
||||
assert_eq!(doc.color_mode, vectorcraft_doc::ColorMode::Cmyk);
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
}
|
||||
// The two letters alone are not taken for a drawing.
|
||||
assert_eq!(detect("notes.bin", b"WLAN settings, exported as plain text for the help desk").map(|f| f.id), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_keep_the_file_order_front_to_back() {
|
||||
let v = V(1100);
|
||||
let rect =
|
||||
|w: f64| synth::object(v, 1, &[(30, [v.coord(w), v.coord(10.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None);
|
||||
// The first object listed is the front-most.
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(30.0), rect(20.0)])]);
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page]);
|
||||
let (doc, _) = super::cdr::import(&file).unwrap();
|
||||
let p = paths(&doc);
|
||||
let widths: Vec<f64> = p
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.bounds(),
|
||||
_ => None,
|
||||
})
|
||||
.map(|b| b.width().round())
|
||||
.collect();
|
||||
assert_eq!(widths, vec![20.0, 30.0], "bottom first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_colors_become_spot_swatches_and_cmyk_drawings_open_in_cmyk() {
|
||||
let v = V(1100);
|
||||
let spot = synth::color(25, [7, 0, 40, 0]);
|
||||
let cmyk = synth::color(2, [0, 100, 0, 0]);
|
||||
let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fild", v.fill(1, &spot)), chunk(b"fild", v.fill(2, &cmyk))])]);
|
||||
let obj = |fill: u32| {
|
||||
synth::object(
|
||||
v,
|
||||
1,
|
||||
&[
|
||||
(20, fill.to_le_bytes().to_vec()),
|
||||
(30, [v.coord(10.0), v.coord(10.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat()),
|
||||
],
|
||||
None,
|
||||
)
|
||||
};
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj(1), obj(2), obj(2)])]);
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page]);
|
||||
let (doc, warnings) = super::cdr::import(&file).unwrap();
|
||||
let s = doc.swatches.iter().find(|s| s.name == "Spot 0:7").unwrap();
|
||||
assert!(s.spot && s.global);
|
||||
assert!(warnings.iter().any(|w| w.contains("library colors")), "{warnings:?}");
|
||||
let filled_with_spot = paths(&doc).iter().any(|n| {
|
||||
n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(&f.paint, vectorcraft_color::Paint::Solid { swatch: Some(name), tint, .. } if name == "Spot 0:7" && (*tint - 0.4).abs() < 1e-6)))
|
||||
});
|
||||
assert!(filled_with_spot);
|
||||
assert_eq!(doc.color_mode, vectorcraft_doc::ColorMode::Cmyk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_by_content_place_and_template() {
|
||||
let bytes = synth::sample(1100, true);
|
||||
let mut s = Session::new();
|
||||
// A renamed drawing is found by its content.
|
||||
assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cdr");
|
||||
assert_eq!(detect("drawing.cdt", &bytes).map(|f| f.id), Some("cdt"));
|
||||
assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cdr"));
|
||||
// So is a package of version 14 or later, and other ZIP archives are not taken for one.
|
||||
for version in [1400, 2700] {
|
||||
let package = synth::sample_file(version, true);
|
||||
assert_eq!(open_bytes(&mut s, "renamed.zip", &package, None).unwrap()["format"], "cdr", "{version}");
|
||||
assert_eq!(detect("drawing.cdt", &package).map(|f| f.id), Some("cdt"));
|
||||
}
|
||||
let other = synth::zip(&[synth::Member { name: "content/other.dat".into(), data: vec![1, 2, 3], deflate: false }], b"");
|
||||
assert_eq!(detect("archive.zip", &other).map(|f| f.id), None);
|
||||
let r = open_bytes(&mut s, "letter.cdt", &bytes, Some("/t/letter.cdt".into())).unwrap();
|
||||
assert_eq!(r["format"], "cdt");
|
||||
assert!(s.doc().unwrap().path.is_none(), "a template opens untitled");
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
// Packages place too.
|
||||
for version in [1400, 2700] {
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
let package = synth::sample_file(version, true);
|
||||
s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&package)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()), "{version}");
|
||||
}
|
||||
for ext in ["cdr", "cdt"] {
|
||||
let f = format(ext).unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}");
|
||||
assert!(!SAVE_FORMATS.contains(&ext));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_of_one_name_on_a_page_stay_apart_and_pages_share_them() {
|
||||
let v = V(1100);
|
||||
let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None);
|
||||
let layer = |name: &str| synth::layer(v, [0, 0, 0, 0x98], name, vec![rect()]);
|
||||
// Front to back: A, B, A on each of two pages.
|
||||
let page = || synth::page(false, vec![layer("A"), layer("B"), layer("A")]);
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(), page()]);
|
||||
let (doc, _) = super::cdr::import(&file).unwrap();
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["A", "B", "A"]);
|
||||
assert!(doc.layers.iter().all(|l| l.children().unwrap().len() == 2), "one object from each page");
|
||||
}
|
||||
|
||||
/// Pages that stack layers of the same names in another order keep their own order: the later
|
||||
/// page gets a new layer rather than art under a layer it stacks above. A layer a later page adds
|
||||
/// below the shared ones goes below them, and a page that shares no layer puts its layers on top.
|
||||
#[test]
|
||||
fn each_page_keeps_its_own_layer_order() {
|
||||
let v = V(1100);
|
||||
let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None);
|
||||
let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect());
|
||||
// Front to back on each page.
|
||||
for (second, want, counts) in [
|
||||
(&["A", "B"][..], vec!["A", "B", "A"], vec![1, 2, 1]),
|
||||
(&["B", "A", "C"][..], vec!["C", "A", "B"], vec![1, 2, 2]),
|
||||
(&["D", "C"][..], vec!["A", "B", "C", "D"], vec![1, 1, 1, 1]),
|
||||
] {
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(&["B", "A"]), page(second)]);
|
||||
let (doc, _) = super::cdr::import(&file).unwrap();
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, want, "bottom to top, second page {second:?}");
|
||||
let got: Vec<usize> = doc.layers.iter().map(|l| l.children().unwrap().len()).collect();
|
||||
assert_eq!(got, counts, "second page {second:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pages that alternate between two orders of the same layers reuse the layers made for each
|
||||
/// order instead of adding layers page after page.
|
||||
#[test]
|
||||
fn pages_in_alternating_layer_orders_reuse_their_layers() {
|
||||
let v = V(1100);
|
||||
let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None);
|
||||
let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect());
|
||||
// Front to back on each page.
|
||||
let mut kids = vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec())];
|
||||
kids.extend((0..6).map(|i| if i % 2 == 0 { page(&["B", "A"]) } else { page(&["A", "B"]) }));
|
||||
let (doc, _) = super::cdr::import(&synth::riff(1100, &kids)).unwrap();
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["A", "B", "A"], "bottom to top");
|
||||
let got: Vec<usize> = doc.layers.iter().map(|l| l.children().unwrap().len()).collect();
|
||||
assert_eq!(got, [3, 6, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_and_the_guides_copied_onto_them_are_bounded() {
|
||||
let v = V(1100);
|
||||
let guide = |x: f64| {
|
||||
let mut g = vec![0; 12];
|
||||
g.extend(90_000_000i32.to_le_bytes());
|
||||
g.extend([v.coord(x), v.coord(0.0), v.coord(x), v.coord(10.0), v.coord(x), v.coord(0.0)].concat());
|
||||
synth::object(v, 0x16, &[(16000, g)], None)
|
||||
};
|
||||
let guides: Vec<_> = (0..200).map(|i| guide(f64::from(i))).collect();
|
||||
let mut kids = vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::page(true, vec![synth::layer(v, [0x0a, 0, 1, 0x98], "G", guides)])];
|
||||
kids.extend((0..1100).map(|_| synth::page(false, vec![])));
|
||||
let (doc, warnings) = super::cdr::import(&synth::riff(1100, &kids)).unwrap();
|
||||
assert_eq!(doc.artboards.len(), 1000);
|
||||
let guides = doc.ruler_guides().len();
|
||||
assert!(guides <= 100_000, "{guides}");
|
||||
assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Layers are held to 10,000, the master page's and the pages' together; at the limit, guide
|
||||
/// paths of angled guidelines go on the top layer.
|
||||
#[test]
|
||||
fn layers_are_bounded() {
|
||||
let v = V(1100);
|
||||
let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None);
|
||||
let mut angled = vec![0; 12];
|
||||
angled.extend(45_000_000i32.to_le_bytes());
|
||||
angled.extend([v.coord(0.0), v.coord(0.0)].concat());
|
||||
let angled = synth::object(v, 0x16, &[(16000, angled)], None);
|
||||
let page_layers =
|
||||
(0..10_050).map(|i| synth::layer(v, [0, 0, 0, 0x98], &format!("L{i}"), if i == 0 { vec![angled.clone()] } else { vec![] })).collect();
|
||||
let master_layers = (0..10_050).map(|i| synth::layer(v, [0, 0, 1, 0x98], &format!("M{i}"), vec![rect()])).collect();
|
||||
for (page, guide_paths) in [(synth::page(false, page_layers), 1), (synth::page(true, master_layers), 0)] {
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page, synth::page(false, vec![])]);
|
||||
let (doc, warnings) = super::cdr::import(&file).unwrap();
|
||||
assert_eq!(doc.layers.len(), 10_000);
|
||||
assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}");
|
||||
let guides = paths(&doc).iter().filter(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })).count();
|
||||
assert_eq!(guides, guide_paths);
|
||||
}
|
||||
}
|
||||
|
||||
/// A guide path of an angled guideline runs from edge to edge of its page, so it moves with that
|
||||
/// page's artboard and not with the page beside it.
|
||||
#[test]
|
||||
fn angled_guides_move_with_their_page() {
|
||||
let v = V(1100);
|
||||
let angled = |deg: i32, x: f64, y: f64| {
|
||||
let mut g = vec![0; 12];
|
||||
g.extend((deg * 1_000_000).to_le_bytes());
|
||||
g.extend([v.coord(x), v.coord(y)].concat());
|
||||
synth::object(v, 0x16, &[(16000, g)], None)
|
||||
};
|
||||
let page = |g| synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "G", vec![g])]);
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(angled(45, 0.0, 0.0)), page(angled(30, 50.0, -40.0))]);
|
||||
let (doc, _) = super::cdr::import(&file).unwrap();
|
||||
assert_eq!(doc.artboards.len(), 2);
|
||||
let guide = |id: &vectorcraft_doc::NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }));
|
||||
let moving: Vec<Vec<_>> = (0..2).map(|i| doc.art_moving_with(i, false).into_iter().filter(guide).collect()).collect();
|
||||
assert_eq!(moving[0].len(), 1, "{moving:?}");
|
||||
assert_eq!(moving[1].len(), 1, "{moving:?}");
|
||||
assert_ne!(moving[0], moving[1]);
|
||||
}
|
||||
|
||||
/// A page longer than the longest artboard opens at that length, and the warnings say so.
|
||||
#[test]
|
||||
fn pages_past_the_longest_artboard_are_cut_with_a_warning() {
|
||||
let v = V(1100);
|
||||
for (w, cut) in [(200_000.0, true), (100_000.0, false)] {
|
||||
let doc = list(b"doc ", vec![synth::mcfg(v, w, 792.0)]);
|
||||
let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, synth::page(false, vec![])]);
|
||||
let (doc, warnings) = super::cdr::import(&file).unwrap();
|
||||
assert_eq!(doc.artboards[0].rect.width().round(), if cut { 163_830.0 } else { w }, "{w}");
|
||||
assert_eq!(warnings.iter().any(|x| x.contains("longer than 163,830 pt")), cut, "{w}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, LineCap, LineJoin};
|
||||
let v = V(1300);
|
||||
let red = synth::color(5, [0, 0, 255, 0]);
|
||||
let black = synth::color(2, [0, 0, 0, 100]);
|
||||
// Line type 4: a dashed outline.
|
||||
let pen = synth::Pen { line_type: 4, width: 2.0, cap: 1, join: 2 };
|
||||
let args = vec![
|
||||
(20, 1u32.to_le_bytes().to_vec()),
|
||||
(10, 2u32.to_le_bytes().to_vec()),
|
||||
(30, v.points(&[(0.0, 0.0, 0x08), (10.0, 0.0, 0x40), (10.0, 10.0, 0x48)])),
|
||||
];
|
||||
let styles = list(
|
||||
b"doc ",
|
||||
vec![list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), list(b"otlt", vec![chunk(b"outl", v.outline(2, pen, &black, &[3, 1]))])],
|
||||
);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &args, None)])]);
|
||||
let (doc, _) = super::cdr::import(&synth::riff(1300, &[chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), styles, page])).unwrap();
|
||||
let p = paths(&doc);
|
||||
let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = p[0].appearance.items.as_slice() else {
|
||||
panic!("{:?}", p[0].appearance.items)
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert_eq!(stroke.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
assert!((stroke.width - 2.0).abs() < 0.01, "{}", stroke.width);
|
||||
assert_eq!((stroke.cap, stroke.join), (LineCap::Round, LineJoin::Bevel));
|
||||
// Dashes are stored in multiples of the width.
|
||||
let dash = stroke.dash.as_ref().unwrap();
|
||||
assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 6.0).abs() < 0.01 && (dash.pattern[1] - 2.0).abs() < 0.01, "{:?}", dash.pattern);
|
||||
}
|
||||
|
||||
/// An outline of width 0 opens as a hairline stroke, which draws; a thin outline keeps its width.
|
||||
#[test]
|
||||
fn outlines_of_width_0_open_as_hairlines() {
|
||||
use vectorcraft_doc::appearance::AppearanceItem;
|
||||
let v = V(1100);
|
||||
let black = synth::color(2, [0, 0, 0, 100]);
|
||||
let doc = list(
|
||||
b"doc ",
|
||||
vec![list(
|
||||
b"otlt",
|
||||
vec![
|
||||
chunk(b"outl", v.outline(2, synth::Pen { line_type: 2, width: 0.0, cap: 0, join: 0 }, &black, &[])),
|
||||
chunk(b"outl", v.outline(3, synth::Pen { line_type: 2, width: 0.1, cap: 0, join: 0 }, &black, &[])),
|
||||
],
|
||||
)],
|
||||
);
|
||||
let rect = |outline: u32| synth::object(v, 1, &[(10, outline.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(2), rect(3)])]);
|
||||
let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap();
|
||||
let widths: Vec<f64> = paths(&doc)
|
||||
.iter()
|
||||
.map(|n| match n.appearance.items.as_slice() {
|
||||
[AppearanceItem::Stroke(s)] => s.width,
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
// Bottom to top: the file lists the 0.1 pt outline last.
|
||||
assert!(widths.len() == 2 && (widths[0] - 0.1).abs() < 0.01 && (widths[1] - 0.25).abs() < 1e-9, "{widths:?}");
|
||||
}
|
||||
|
||||
/// An outline behind the fill becomes a stroke painted before the fill.
|
||||
#[test]
|
||||
fn outlines_behind_the_fill_paint_first() {
|
||||
use vectorcraft_doc::appearance::AppearanceItem;
|
||||
let v = V(1100);
|
||||
let black = synth::color(2, [0, 0, 0, 100]);
|
||||
let doc = list(
|
||||
b"doc ",
|
||||
vec![
|
||||
list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]),
|
||||
list(
|
||||
b"otlt",
|
||||
vec![
|
||||
chunk(b"outl", v.outline(2, synth::Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])),
|
||||
chunk(b"outl", v.outline(3, synth::Pen { line_type: 0x02, width: 4.0, cap: 0, join: 0 }, &black, &[])),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
let rect = |outline: u32| {
|
||||
let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))];
|
||||
synth::object(v, 1, &args, None)
|
||||
};
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(2), rect(3)])]);
|
||||
let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap();
|
||||
let p = paths(&doc);
|
||||
assert_eq!(p.len(), 2);
|
||||
// The file lists objects front to back; the document stacks them bottom to top.
|
||||
let (behind, over) = (&p[1].appearance.items, &p[0].appearance.items);
|
||||
assert!(matches!(behind.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]), "{behind:?}");
|
||||
assert!(matches!(over.as_slice(), [AppearanceItem::Fill(_), AppearanceItem::Stroke(_)]), "{over:?}");
|
||||
}
|
||||
|
||||
/// A container whose outline is behind its fill opens as a group of that outline below a clipping
|
||||
/// group whose clipping path keeps only the fill.
|
||||
#[test]
|
||||
fn a_container_outline_behind_the_fill_stays_below_its_contents() {
|
||||
use vectorcraft_doc::appearance::AppearanceItem;
|
||||
let v = V(1100);
|
||||
let black = synth::color(2, [0, 0, 0, 100]);
|
||||
let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| {
|
||||
let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))];
|
||||
args.extend(extra);
|
||||
synth::object(v, 1, &args, None)
|
||||
};
|
||||
let doc = list(
|
||||
b"doc ",
|
||||
vec![
|
||||
list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]),
|
||||
list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[]))]),
|
||||
synth::clpt(vec![(5, vec![rect(10.0, vec![])])]),
|
||||
],
|
||||
);
|
||||
let container = rect(40.0, vec![synth::container(5), (10, 2u32.to_le_bytes().to_vec())]);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![container])]);
|
||||
let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap();
|
||||
let layer = doc.layers.last().and_then(|l| l.children()).unwrap();
|
||||
let [both] = layer.as_slice() else { panic!("{layer:?}") };
|
||||
let NodeKind::Group { children: both, clip: false } = &both.kind else { panic!("{:?}", both.kind) };
|
||||
let [outline, group] = both.as_slice() else { panic!("{both:?}") };
|
||||
assert!(matches!(outline.appearance.items.as_slice(), [AppearanceItem::Stroke(_)]), "{:?}", outline.appearance.items);
|
||||
let NodeKind::Group { children, clip: true } = &group.kind else { panic!("{:?}", group.kind) };
|
||||
assert!(matches!(children[0].appearance.items.as_slice(), [AppearanceItem::Fill(_)]), "{:?}", children[0].appearance.items);
|
||||
}
|
||||
|
||||
/// A container and the group it clips open as a clipping group: the container's shape first, as
|
||||
/// the clipping path keeping its fill, then the clipped shapes.
|
||||
#[test]
|
||||
fn containers_open_as_clipping_groups() {
|
||||
let v = V(1100);
|
||||
let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| {
|
||||
let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))];
|
||||
args.extend(extra);
|
||||
synth::object(v, 1, &args, None)
|
||||
};
|
||||
let doc = list(
|
||||
b"doc ",
|
||||
vec![
|
||||
list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]),
|
||||
synth::clpt(vec![(5, vec![rect(10.0, vec![]), rect(20.0, vec![])])]),
|
||||
],
|
||||
);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]);
|
||||
let (doc, warnings) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap();
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let layer = doc.layers.last().and_then(|l| l.children()).unwrap();
|
||||
let [group] = layer.as_slice() else { panic!("{layer:?}") };
|
||||
let NodeKind::Group { children, clip: true } = &group.kind else { panic!("{:?}", group.kind) };
|
||||
assert_eq!(children.len(), 3);
|
||||
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert_eq!(children[0].appearance.items.len(), 1, "the container keeps its fill");
|
||||
assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })));
|
||||
}
|
||||
|
||||
/// An object with a lens or transparency opens opaque, and the warnings say so.
|
||||
#[test]
|
||||
fn lenses_and_transparency_are_named_in_the_warnings() {
|
||||
let v = V(1200);
|
||||
let args = vec![(30, v.rect(10.0, 10.0, 0.0)), (8000, vec![5, 0, 0, 0])];
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])]);
|
||||
let (doc, warnings) = super::cdr::import(&synth::riff(1200, &[chunk(b"vrsn", 1200u16.to_le_bytes().to_vec()), page])).unwrap();
|
||||
assert_eq!(paths(&doc).len(), 1);
|
||||
assert_eq!(warnings, ["CDR lenses and object transparency were not applied, and the objects they are on show opaque"]);
|
||||
}
|
||||
|
||||
/// A uniform transparency, a winding flag and hidden and locked flags of a drawing of version 16
|
||||
/// open as the object's opacity, blend mode and fill rule and as hidden and locked nodes, without
|
||||
/// a warning.
|
||||
#[test]
|
||||
fn transparency_winding_and_flags_open_on_the_art() {
|
||||
let v = V(1600);
|
||||
let args = vec![(30, v.rect(10.0, 10.0, 0.0)), synth::transparency(40.0, 29), (14001, vec![1, 0, 0, 0])];
|
||||
let object = synth::flagged(synth::object(v, 1, &args, None), [0x10, 0, 0, 8]);
|
||||
let layers = vec![
|
||||
synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![object]),
|
||||
synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![synth::object(v, 1, &args[..1], None)]),
|
||||
];
|
||||
let file = synth::file_of(1600, vec![synth::page(false, layers)]);
|
||||
let (doc, warnings) = super::cdr::import(&file).unwrap();
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
// Bottom to top: "Hidden", then "Shown".
|
||||
let states: Vec<(String, bool)> = doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect();
|
||||
assert_eq!(states, [("Hidden".to_string(), false), ("Shown".to_string(), true)]);
|
||||
let shown = doc.layers[1].children().unwrap();
|
||||
let [n] = shown.as_slice() else { panic!("{shown:?}") };
|
||||
assert!(matches!(n.kind, NodeKind::Path { rule: vectorcraft_doc::geom::FillRule::NonZero, .. }), "{:?}", n.kind);
|
||||
assert!((n.opacity - 0.6).abs() < 1e-6 && n.blend == vectorcraft_color::BlendMode::Overlay, "{} {:?}", n.opacity, n.blend);
|
||||
assert!(n.locked && n.visible);
|
||||
}
|
||||
|
||||
/// A drawing whose open left things out is not written over unasked: the file stays as it was
|
||||
/// until the write says `acknowledgeLoss`.
|
||||
#[test]
|
||||
fn a_drawing_the_open_left_things_out_of_is_not_written_over_unasked() {
|
||||
let d = std::env::temp_dir().join(format!("vc-cdr-lossy-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let src = d.join("drawing.cdr");
|
||||
let original = synth::sample_file(1300, true);
|
||||
std::fs::write(&src, &original).unwrap();
|
||||
let mut s = Session::new();
|
||||
let opened = s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap();
|
||||
assert!(opened["warnings"].to_string().contains("text, bitmaps"), "{opened}");
|
||||
let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string();
|
||||
assert!(e.contains("acknowledgeLoss"), "{e}");
|
||||
assert_eq!(std::fs::read(&src).unwrap(), original);
|
||||
s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg", "acknowledgeLoss": true })).unwrap();
|
||||
assert_ne!(std::fs::read(&src).unwrap(), original);
|
||||
std::fs::remove_dir_all(d).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_versions_and_damaged_drawings_say_why() {
|
||||
let mut s = Session::new();
|
||||
// A RIFF file that names version 2: files of versions 1 and 2 are not RIFF files.
|
||||
let e = open_bytes(&mut s, "old.cdr", &synth::riff(200, &[]), None).unwrap_err().to_string();
|
||||
assert!(e.contains("can't be read (RIFF files of versions before 3 are not read)"), "{e}");
|
||||
let e = open_bytes(&mut s, "new.cdr", &synth::riff(2800, &[]), None).unwrap_err().to_string();
|
||||
assert!(e.contains("CDR 28 drawings can't be opened: VectorCraft reads versions 1 to 27"), "{e}");
|
||||
// A file that starts like one of version 1 or 2 but whose offsets don't fit it.
|
||||
let e = open_bytes(&mut s, "odd.cdr", b"WLe\0 and no more", None).unwrap_err().to_string();
|
||||
assert!(e.contains("can't be read (not a CDR drawing)"), "{e}");
|
||||
// A package cut short, and one whose drawing is encrypted (flag bit 0 of its directory entry).
|
||||
let package = synth::sample_file(1400, false);
|
||||
let e = open_bytes(&mut s, "cut.cdr", &package[..package.len() / 2], None).unwrap_err().to_string();
|
||||
assert!(e.contains("can't be read (damaged package directory)"), "{e}");
|
||||
let mut encrypted = package.clone();
|
||||
let dir = package.windows(4).position(|w| w == b"PK\x01\x02").unwrap();
|
||||
encrypted[dir + 8] |= 1;
|
||||
let e = open_bytes(&mut s, "locked.cdr", &encrypted, None).unwrap_err().to_string();
|
||||
assert!(e.contains("can't be read (encrypted packages are not read)"), "{e}");
|
||||
let mut big = synth::riff(1100, &[]);
|
||||
big[4..8].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
// A declared size past the end keeps what the file holds.
|
||||
assert!(open_bytes(&mut s, "cut.cdr", &big, None).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups,
|
||||
//! paths, solid paint and strokes, with their warnings and refusals.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use vectorcraft_cdr::synth_cmx::*;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
fn paths(nodes: &[std::sync::Arc<Node>], out: &mut Vec<Node>) {
|
||||
for n in nodes {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => paths(children, out),
|
||||
_ => out.push((**n).clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn warnings(r: &serde_json::Value) -> Vec<String> {
|
||||
r["warnings"].as_array().map(|w| w.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmx_file_opens_as_editable_art() {
|
||||
let mut s = Session::new();
|
||||
let r = open_bytes(&mut s, "drawing.cmx", &sample(), None).unwrap();
|
||||
assert_eq!(r["format"], "cmx");
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
// One 210 x 297 mm page.
|
||||
assert_eq!(doc.artboards.len(), 1);
|
||||
let ab = doc.artboards[0].rect;
|
||||
assert_eq!((ab.width().round(), ab.height().round()), (595.0, 842.0));
|
||||
// Bottom to top: the layer drawn first is at the bottom.
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Art", "Top"]);
|
||||
let art = doc.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), 2);
|
||||
assert!(matches!(art[1].kind, NodeKind::Group { .. }), "the group drawn after the red square is above it");
|
||||
let mut all = Vec::new();
|
||||
paths(&doc.layers, &mut all);
|
||||
assert_eq!(all.len(), 4);
|
||||
// The red square: 100 mm on a side, centered on the page, with a fill and a stroke.
|
||||
let red = &all[0];
|
||||
let b = doc.bounds_of(&[red.id], false).unwrap();
|
||||
let mm = 72.0 / 25.4;
|
||||
assert!((b.width() - 100.0 * mm).abs() < 0.01 && (b.center().x - ab.center().x).abs() < 0.01, "{b:?}");
|
||||
assert_eq!(red.appearance.items.len(), 2);
|
||||
// The square whose line type draws no outline has a fill only.
|
||||
assert_eq!(all[1].appearance.items.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_by_content_and_place() {
|
||||
let bytes = sample();
|
||||
let mut s = Session::new();
|
||||
// A renamed file is found by its content, and a .cmx extension alone reads it as one.
|
||||
assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cmx");
|
||||
assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cmx"));
|
||||
assert_eq!(detect("drawing.cmx", b"").map(|f| f.id), Some("cmx"));
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
let f = format("cmx").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx"));
|
||||
assert!(!SAVE_FORMATS.contains(&"cmx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_left_out_is_named_in_the_warnings() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
instr(66, &fields(&[field(1, &[0; 8])])),
|
||||
square(&attrs_fill_type(2), 0, 0, 1000),
|
||||
square(&attrs(Some(1), Some(1), true), 0, 0, 1000),
|
||||
]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
|
||||
children.push(arrowheads(&[(1, 0)]));
|
||||
let mut s = Session::new();
|
||||
let w = warnings(&open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap());
|
||||
assert_eq!(
|
||||
w,
|
||||
[
|
||||
"CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out",
|
||||
"CMX fills other than uniform colors were left out",
|
||||
"CMX outline arrowheads were left out",
|
||||
"CMX lenses were not applied",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_the_open_left_things_out_of_is_not_written_over_unasked() {
|
||||
let d = std::env::temp_dir().join(format!("vc-cmx-loss-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let src = d.join("drawing.cmx");
|
||||
let mut children = vec![cont(b'4', 1e-7), page(&[begin_page(None), square(&attrs_fill_type(2), 0, 0, 1000)])];
|
||||
children.extend(tables());
|
||||
let original = riff(&children);
|
||||
std::fs::write(&src, &original).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap();
|
||||
let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string();
|
||||
assert!(e.contains("acknowledgeLoss"), "{e}");
|
||||
assert_eq!(std::fs::read(&src).unwrap(), original);
|
||||
std::fs::remove_dir_all(d).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_read_say_why() {
|
||||
let mut s = Session::new();
|
||||
let mut rifx = sample();
|
||||
rifx[..4].copy_from_slice(b"RIFX");
|
||||
let e = open_bytes(&mut s, "a.cmx", &rifx, None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (big-endian CMX files are not read)"), "{e}");
|
||||
let e = open_bytes(&mut s, "b.cmx", &riff(&[cont(b'2', 1e-3)]), None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (CMX files with 16-bit coordinates are not read)"), "{e}");
|
||||
let e = open_bytes(&mut s, "c.cmx", &riff(&[]), None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (damaged CMX header)"), "{e}");
|
||||
let e = open_bytes(&mut s, "d.cmx", b"not a cmx file", None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_without_a_name_is_named_by_its_place() {
|
||||
// An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed,
|
||||
// and the importer numbers it by its place among the layers it keeps, as for a `.cdr` drawing.
|
||||
let p = page(&[
|
||||
begin_page(None),
|
||||
begin_layer("Grid", None),
|
||||
end_layer(),
|
||||
begin_layer(" ", None),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 1000),
|
||||
end_layer(),
|
||||
]);
|
||||
let mut children = vec![cont(b'4', 1e-7), p];
|
||||
children.extend(tables());
|
||||
let mut s = Session::new();
|
||||
let r = open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap();
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let names: Vec<String> = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Layer 1"]);
|
||||
}
|
||||
@@ -166,6 +166,14 @@ fn the_flattener_preset_and_options_apply() {
|
||||
assert!(!transparency(&kept).is_empty() && !warnings.iter().any(|w| w.contains("flattened")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_1_3_files_flatten_without_alpha_whatever_the_options() {
|
||||
let mut s = session();
|
||||
let p = json!({"compatibility": "1.3", "preserveEditing": false, "flattener": {"balance": 0, "preserveAlpha": true}});
|
||||
let (pdf, _) = export(&mut s, p);
|
||||
assert!(pdf.starts_with(b"%PDF-1.3") && transparency(&pdf).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
has_doc,
|
||||
delete_point
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
has_doc,
|
||||
add_line
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
has_doc,
|
||||
split_line
|
||||
),
|
||||
@@ -182,8 +182,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
let item = item_target(s, p, cmd)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
// The art of a graph design in a series keeps the design's gradient.
|
||||
let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets(s, p)?, cmd)?;
|
||||
// The art of a graph design in a series keeps the design's gradient; a Live Paint group's fill is on its faces and its
|
||||
// stroke on its edges.
|
||||
let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets_for(s, p, !stroke)?, cmd)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select an object with a freeform gradient"));
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Vector",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label; without item, a Live Paint group's faces take a fill edit and its edges take a stroke edit",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Gradient Stop",
|
||||
[],
|
||||
None,
|
||||
"{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected → {index}",
|
||||
"{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the Live Paint Bucket is the active tool → {index}",
|
||||
always,
|
||||
select_stop
|
||||
),
|
||||
@@ -61,7 +61,9 @@ pub(crate) fn active_gradient(s: &Session) -> Option<GradientPaint> {
|
||||
fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "gradient.selectStop";
|
||||
// No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`.
|
||||
if s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
// While the Live Paint Bucket is active the proxies show the default paint, whose stops can be
|
||||
// selected with a part picked.
|
||||
if s.tool_id() != super::paint::LIVE_PAINT_BUCKET && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
let index = match p.get("index") {
|
||||
@@ -82,15 +84,21 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Whose gradient a selected stop belongs to: the active document, its first selected object
|
||||
/// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in
|
||||
/// front and the Appearance panel's active item. Selecting other art, picking a part of the
|
||||
/// instance, toggling the proxy or picking another item leaves no stop selected.
|
||||
/// front, the Appearance panel's active item and whether the Live Paint Bucket is the active tool
|
||||
/// (its proxies show the default paint). Selecting other art, picking a part of the instance,
|
||||
/// toggling the proxy, picking another item or choosing the bucket or leaving it leaves no stop
|
||||
/// selected.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct StopOwner {
|
||||
doc: Option<usize>,
|
||||
object: Option<NodeId>,
|
||||
/// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
|
||||
/// first in the selection shows the next object's.
|
||||
source: Option<NodeId>,
|
||||
part: bool,
|
||||
fill: bool,
|
||||
item: Option<usize>,
|
||||
bucket: bool,
|
||||
}
|
||||
|
||||
impl StopOwner {
|
||||
@@ -99,9 +107,11 @@ impl StopOwner {
|
||||
Self {
|
||||
doc: s.active,
|
||||
object: st.and_then(|d| d.selection.objects.first().copied()),
|
||||
source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
|
||||
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
|
||||
fill: s.fill_active,
|
||||
item: s.appearance_item(),
|
||||
bucket: s.tool_id() == super::paint::LIVE_PAINT_BUCKET,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -525,15 +535,18 @@ fn apply_gradient_edit_in_model(
|
||||
|
||||
fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.editGradient";
|
||||
// While the Live Paint Bucket is active, the gradient it paints with changes; the selection keeps its own.
|
||||
let bucket = super::paint::bucket_color_params(s, p, C)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let item = item_target(s, p, C)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, C)?;
|
||||
check_switches(p, &["reverse", "dither"], C)?;
|
||||
check_numbers(p, &["angle"], C)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let ids = item.targets(s, p)?;
|
||||
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
|
||||
// not one for new art.
|
||||
let selected = !ids.is_empty();
|
||||
let (ids, skipped) = item.targets_and_skipped(s, p, !stroke)?;
|
||||
// Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts
|
||||
// of the other kind left out above: the stroke mode is then not one for new art.
|
||||
let selected = !ids.is_empty() || skipped;
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
|
||||
// How the gradient lies on a stroke (the panel's Stroke buttons).
|
||||
let mode = match str_param(p, "strokeMode") {
|
||||
@@ -619,7 +632,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
if let Some(m) = mode
|
||||
&& !selected
|
||||
&& p.get("ids").is_none()
|
||||
&& (bucket.is_some() || p.get("ids").is_none())
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
st.gradient_mode = m;
|
||||
@@ -769,7 +782,10 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let targets = match item {
|
||||
ItemTarget::Top => {
|
||||
leaf_targets(s, &super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)?
|
||||
let roots = super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?;
|
||||
// A Live Paint group's fill gradient is on its faces and its stroke gradient on its edges.
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
|
||||
leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
|
||||
}
|
||||
_ => item.targets(s, p)?,
|
||||
};
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Gradient Preset",
|
||||
[],
|
||||
None,
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}",
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -207,6 +207,10 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "gradient.presets.apply";
|
||||
let name = name_param(p, C)?;
|
||||
let preset = s.gradient_preset(name).ok_or_else(|| bad(C, format!("no gradient preset `{name}` (see gradient.presets.list)")))?;
|
||||
// While the Live Paint Bucket is active, the gradient it paints with changes, chosen by the
|
||||
// active proxy rather than the selection's Appearance row (as paint.editGradient chooses).
|
||||
let bucket = super::paint::bucket_color_params(s, p, C)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let stroke = edits_stroke(s, p, item_target(s, p, C)?, !s.fill_active, C)?;
|
||||
let g = &preset.gradient;
|
||||
let mut edit = p.clone();
|
||||
|
||||
@@ -7406,6 +7406,81 @@ fn the_last_label_of_a_kind_edited_together_sets_what_it_keeps() {
|
||||
assert_eq!(kept(&s), "#ff0000");
|
||||
}
|
||||
|
||||
/// A column graph, a 10 pt square with one red fill row, and the category labels Q1, Q2 and Q3: Q1 and Q3 have one red
|
||||
/// fill row, Q2 a hidden red fill row under a green one, and Q1's row is then painted blue, which the kind keeps.
|
||||
/// Returns the graph, the square and the three labels.
|
||||
fn labels_with_hidden_and_shown_rows(s: &mut Session) -> (NodeId, NodeId, [NodeId; 3]) {
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer};
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(s, "column");
|
||||
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
let labels = ["Q1", "Q2", "Q3"].map(|t| text_id(s, id, "Axes", t));
|
||||
let fill = |hex: &str, visible: bool| {
|
||||
AppearanceItem::Fill(FillLayer { visible, ..FillLayer::new(Paint::solid(vectorcraft_color::Color::from_hex(hex).unwrap())) })
|
||||
};
|
||||
s.edit("Rows", |d, _| {
|
||||
for (l, items) in [
|
||||
(square, vec![fill("#ff0000", true)]),
|
||||
(labels[0], vec![fill("#ff0000", true)]),
|
||||
(labels[1], vec![fill("#ff0000", false), fill("#00ff00", true)]),
|
||||
(labels[2], vec![fill("#ff0000", true)]),
|
||||
] {
|
||||
d.node_mut(l).unwrap().appearance.items = items;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [labels[0].0], "index": 0, "color": "#0000ff"})).unwrap();
|
||||
assert_eq!(kept_category_fill(s, id), Some("#0000ff".into()));
|
||||
(id, square, labels)
|
||||
}
|
||||
|
||||
/// The fill of the category label rows graph `id` keeps, as a hex color.
|
||||
fn kept_category_fill(s: &Session, id: NodeId) -> Option<String> {
|
||||
spec(s, id).label_styles.categories_rows.and_then(|r| r.paint.fill).and_then(|p| p.color()).map(|c| c.to_hex())
|
||||
}
|
||||
|
||||
/// Row edits on several labels at once, with a plain object among them, keep for the kind what the last label whose shown
|
||||
/// row the edit wrote shows, also when that row comes out as it was; a label whose hidden row the edit wrote is left out.
|
||||
/// One undo takes it back. Covers `appearance.setItem`, `appearance.duplicateItem` and `paint.setFill` with `item`.
|
||||
#[test]
|
||||
fn row_edits_on_several_labels_keep_the_last_written_shown_row() {
|
||||
let edits = [
|
||||
("appearance.setItem", json!({"index": 0, "color": "#ff0000"})),
|
||||
("appearance.duplicateItem", json!({"index": 0})),
|
||||
("paint.setFill", json!({"item": 0, "color": "#ff0000"})),
|
||||
];
|
||||
for (cmd, mut p) in edits {
|
||||
let mut s = Session::new();
|
||||
let (id, square, [_, q2, q3]) = labels_with_hidden_and_shown_rows(&mut s);
|
||||
// Q3 shows red before and after the edit; Q2 shows green over the hidden row the edit writes.
|
||||
p["ids"] = json!([q3.0, square.0, q2.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}: redo");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Only the hidden row of a label: the kind keeps blue.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
p["ids"] = json!([square.0, q2.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: hidden row only");
|
||||
while s.doc().unwrap().history.undo.len() > steps {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// Q2's shown green row, written as it was: the kind keeps green.
|
||||
p["ids"] = json!([q2.0]);
|
||||
p[if cmd == "paint.setFill" { "item" } else { "index" }] = json!(1);
|
||||
if cmd != "appearance.duplicateItem" {
|
||||
p["color"] = json!("#00ff00");
|
||||
}
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(kept_category_fill(&s, id), Some("#00ff00".into()), "{cmd}: the shown row written as it was");
|
||||
}
|
||||
}
|
||||
|
||||
/// A label's object opacity and blend mode set without a row (`transparency.set` without `item`) are kept for its kind.
|
||||
#[test]
|
||||
fn a_labels_object_opacity_and_blend_mode_are_kept_for_its_kind() {
|
||||
|
||||
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Locate Object",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
|
||||
"{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it, and scrolls to its row when the row is in the list, also when the row was already highlighted (Show Layers Only, a search, the filter, or editing an opacity mask on another layer can leave the row out) → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
|
||||
has_doc,
|
||||
locate
|
||||
),
|
||||
|
||||
@@ -206,9 +206,10 @@ impl Session {
|
||||
}
|
||||
|
||||
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
|
||||
/// the first selected object (so the last selection's once nothing is selected).
|
||||
/// the first selected object (so the last selection's once nothing is selected). Not while the
|
||||
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
|
||||
pub(crate) fn inherit_new_art(&mut self) {
|
||||
if self.prefs.new_art_basic {
|
||||
if self.prefs.new_art_basic || self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
|
||||
return;
|
||||
}
|
||||
let Some(st) = self.active() else { return };
|
||||
@@ -227,9 +228,11 @@ impl Session {
|
||||
if !self.prefs.new_art_basic {
|
||||
return;
|
||||
}
|
||||
let has_paint = self
|
||||
.proxy_source(false)
|
||||
.is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some());
|
||||
// A Live Paint group with edges and no faces shows only a stroke.
|
||||
let has_paint = [false, true].into_iter().any(|stroke| {
|
||||
self.proxy_source(stroke)
|
||||
.is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some())
|
||||
});
|
||||
if !has_paint {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -218,12 +218,32 @@ pub(super) fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
let m = measure(s, p, "object.align")?;
|
||||
let (h, v) = direction(p, "object.align")?;
|
||||
choice(p, "object.align", "to", &["selection", "artboard", "key"])?;
|
||||
let to = choice(p, "object.align", "to", &["selection", "artboard", "key", "auto"])?;
|
||||
check_switches(p, &["patterns"], "object.align")?;
|
||||
check_numbers(p, &["artboard"], "object.align")?;
|
||||
if h.is_none() && v.is_none() {
|
||||
return Err(bad("object.align", "give horizontal or vertical"));
|
||||
}
|
||||
// Resolve only the explicit automatic target at this step, without changing the caller's
|
||||
// parameters or selection. The existing reference/anchor/guide paths receive a concrete target.
|
||||
let automatic_params = if to == Some("auto") {
|
||||
let selection = &s.doc()?.selection;
|
||||
let to = if selection.has_key() {
|
||||
"key"
|
||||
} else if selection.anchors.is_empty() && selection.len() == 1 {
|
||||
"artboard"
|
||||
} else {
|
||||
"selection"
|
||||
};
|
||||
let Some(mut params) = p.as_object().cloned() else {
|
||||
return Err(bad("object.align", "expected an object of align parameters"));
|
||||
};
|
||||
params.insert("to".into(), Value::String(to.into()));
|
||||
Some(Value::Object(params))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let p = automatic_params.as_ref().unwrap_or(p);
|
||||
// Anchor points selected with Direct Selection align themselves, as in Illustrator (#1180).
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
return align_anchors(s, p, &ids, (h, v));
|
||||
|
||||
@@ -334,6 +334,9 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if matches!(st.doc.node(id).ok_or(EngineError::NoNode(id))?.kind, NodeKind::Text(_)) {
|
||||
return Err(bad("object.isolate", "type objects can't be isolated"));
|
||||
}
|
||||
if st.doc.node(id).is_some_and(|n| n.is_ruler_guide()) {
|
||||
return Err(bad("object.isolate", "ruler guides can't be isolated"));
|
||||
}
|
||||
let isolation =
|
||||
st.doc.node(id).filter(|n| n.extras().shaper.is_some()).and_then(|n| n.children()).and_then(|c| c.first()).map_or(id, |n| n.id);
|
||||
// A hidden or locked object, one in a hidden or locked group or layer, and a guide path while
|
||||
|
||||
@@ -241,7 +241,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Enter Isolation Mode",
|
||||
[],
|
||||
None,
|
||||
"{id?} isolate a group, a layer or a single object (default: the first selected object); type, a hidden or locked object, an object in a hidden or locked group or layer, and a guide path while Lock Guides is on are refused, and so is every object while an opacity mask is edited",
|
||||
"{id?} isolate a group, a layer or a single object (default: the first selected object); type, a ruler guide, a hidden or locked object, an object in a hidden or locked group or layer, and a guide path while Lock Guides is on are refused, and so is every object while an opacity mask is edited",
|
||||
crate::cmd::maskedit::outside_mask_editing,
|
||||
isolate
|
||||
),
|
||||
@@ -268,7 +268,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, geometry effects and projected 3D art), 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",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\"|\"auto\" (\"auto\": resolve at each call from the current selection: the key object, key anchor or key guide while set, else the artboard for exactly one selected object without selected anchors, else the selection; 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\", or \"auto\" choosing the 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, geometry effects and projected 3D art), 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
|
||||
),
|
||||
|
||||
@@ -326,14 +326,15 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
|
||||
let (gx, gy) = (dx, dy);
|
||||
let (dx, dy) = along_constrain_angle(dx, dy, s.prefs.constrain_angle);
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
let objects = transforms_objects(p);
|
||||
if objects && !s.doc()?.selection.anchors.is_empty() {
|
||||
// When the anchors move by 0, the document and its undo history stay as they are.
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
return ok();
|
||||
}
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
|
||||
}
|
||||
if s.doc()?.selection.is_empty() {
|
||||
if objects && s.doc()?.selection.is_empty() {
|
||||
let copy = bool_or(p, "copy", false);
|
||||
// When guides move by 0 without a copy, the document and its undo history stay as they are.
|
||||
if gx == 0.0 && gy == 0.0 && !copy {
|
||||
@@ -342,6 +343,21 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return crate::cmd::docmenu::guide_move(s, &json!({ "dx": gx, "dy": gy, "copy": copy }));
|
||||
}
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
if !objects && !bool_or(p, "copy", false) {
|
||||
// Pattern-only nudges of art without a pattern change nothing, including undo history.
|
||||
if !bool_or(p, "patterns", s.prefs.transform_pattern_tiles) {
|
||||
return ok();
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let paths = st.doc.index_paths(ids.iter().copied());
|
||||
let mut uses_patterns = false;
|
||||
for node in ids.iter().filter_map(|id| paths.get(id)).filter_map(|path| st.doc.node_at(path)) {
|
||||
node.walk(&mut |n| uses_patterns |= vectorcraft_doc::pattern::uses_pattern(n, None));
|
||||
}
|
||||
if !uses_patterns {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Some(Vec2::new(gx, gy)))
|
||||
}
|
||||
|
||||
|
||||
+267
-39
@@ -4,7 +4,9 @@ use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::appearance::{FillLayer, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
|
||||
use vectorcraft_tools::builder::{edges, faces, is_live_paint};
|
||||
|
||||
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
|
||||
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
|
||||
@@ -14,6 +16,10 @@ use super::{
|
||||
};
|
||||
use crate::{DocState, EngineError};
|
||||
|
||||
/// The Live Paint Bucket's tool id. While it is active, a fill or stroke color chosen for no
|
||||
/// object in particular is the color it paints with ([`apply_paint`]).
|
||||
pub(crate) const LIVE_PAINT_BUCKET: &str = "livePaintBucket";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -21,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -30,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -39,7 +45,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 what the swap changes on 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. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. 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). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
|
||||
has_doc,
|
||||
swap
|
||||
),
|
||||
@@ -48,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke 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?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke 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). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -69,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"None",
|
||||
[],
|
||||
Some("/"),
|
||||
"{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does → {objects}",
|
||||
"{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}",
|
||||
has_doc,
|
||||
|s, _| {
|
||||
let f = s.fill_active;
|
||||
@@ -96,7 +102,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -105,7 +111,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Complement",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
|
||||
),
|
||||
@@ -114,7 +120,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Color",
|
||||
[],
|
||||
Some(","),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = Paint::solid(s.last_solid);
|
||||
@@ -126,7 +132,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Gradient",
|
||||
[],
|
||||
Some("."),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
|
||||
@@ -154,7 +160,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Fill and Stroke",
|
||||
[],
|
||||
None,
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
|
||||
always,
|
||||
proxies
|
||||
),
|
||||
@@ -178,10 +184,11 @@ impl Session {
|
||||
|
||||
/// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the
|
||||
/// first selected object's own stack) for the proxy of its kind, else the first selected
|
||||
/// object's (a group's first painted object's; type: its first run's), else the defaults for
|
||||
/// new art. When the object whose fill the proxy shows is a gradient mesh with points picked
|
||||
/// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid
|
||||
/// fill color changes.
|
||||
/// object's (a group's first painted object's; a Live Paint group's first face's fill and first
|
||||
/// edge's stroke, or the next selected object's when it has no face or edge; type: its first
|
||||
/// run's), else the defaults for new art. When the object whose fill the proxy shows is a
|
||||
/// gradient mesh with points picked ([`Session::fill_mesh_points`]), the fill is its first
|
||||
/// picked point's color, which a solid fill color changes.
|
||||
pub fn proxy_paints(&self) -> (Paint, Paint) {
|
||||
let points = self.fill_mesh_points();
|
||||
let show = |stroke: bool| match self.proxy_source(stroke) {
|
||||
@@ -196,8 +203,12 @@ impl Session {
|
||||
/// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item
|
||||
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With
|
||||
/// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that
|
||||
/// object as the instance draws it.
|
||||
/// object as the instance draws it. None while the Live Paint Bucket is the active tool: the
|
||||
/// proxies show the colors it paints with.
|
||||
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option<usize>)> {
|
||||
if self.tool_id() == LIVE_PAINT_BUCKET {
|
||||
return None;
|
||||
}
|
||||
let st = self.active()?;
|
||||
if let Some(part) = st.selected_symbol_part() {
|
||||
return Some((Cow::Owned(part), None));
|
||||
@@ -207,9 +218,20 @@ impl Session {
|
||||
if first.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return Some((Cow::Borrowed(first), item));
|
||||
}
|
||||
let mut nodes = vec![];
|
||||
painted(first, true, &mut nodes);
|
||||
nodes.first().map(|n| (Cow::Borrowed(*n), None))
|
||||
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
|
||||
// object without a painted object shows the defaults for new art.
|
||||
for id in st.selection.subjects() {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, stroke, &mut nodes);
|
||||
if let Some(n) = nodes.first() {
|
||||
return Some((Cow::Borrowed(*n), None));
|
||||
}
|
||||
if !is_live_paint(n) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
|
||||
@@ -250,21 +272,35 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
|
||||
pub(crate) fn live_paint_parts(n: &Node) -> Vec<NodeId> {
|
||||
if !is_live_paint(n) {
|
||||
return vec![];
|
||||
}
|
||||
faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
|
||||
}
|
||||
|
||||
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
|
||||
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
|
||||
/// other containers inside them), a compound path for its parts.
|
||||
pub(crate) fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
|
||||
/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
|
||||
/// faces in the fill proxy (`stroke` false) and for its edges in the stroke proxy, the parts a fill
|
||||
/// or a stroke given to it changes ([`live_paint_parts_skipped`]).
|
||||
pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'a Node>) {
|
||||
// A ruler guide has no paints.
|
||||
if n.is_ruler_guide() {
|
||||
return;
|
||||
}
|
||||
if is_live_paint(n) {
|
||||
out.extend(if stroke { edges(n) } else { faces(n) }.into_iter().map(|part| &**part));
|
||||
return;
|
||||
}
|
||||
let expand = match n.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => true,
|
||||
NodeKind::Compound { .. } => false,
|
||||
_ => !top && n.is_container(),
|
||||
};
|
||||
if expand {
|
||||
n.children().into_iter().flatten().for_each(|c| painted(c, false, out));
|
||||
n.children().into_iter().flatten().for_each(|c| painted(c, false, stroke, out));
|
||||
} else {
|
||||
out.push(n);
|
||||
}
|
||||
@@ -293,18 +329,31 @@ impl DocState {
|
||||
}
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let mut covered = std::collections::HashSet::new();
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
#[cfg(test)]
|
||||
tests::note_gathered();
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
if covered.contains(&n.id) {
|
||||
continue;
|
||||
}
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
let set = if item.is_some() {
|
||||
&selected
|
||||
} else if stroke {
|
||||
&strokes
|
||||
} else {
|
||||
&fills
|
||||
};
|
||||
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
|
||||
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
|
||||
c => c.into_iter().map(Paint::solid).collect(),
|
||||
@@ -331,7 +380,11 @@ impl DocState {
|
||||
impl Session {
|
||||
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
|
||||
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
|
||||
/// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]).
|
||||
pub fn proxy_mixed(&self) -> (bool, bool) {
|
||||
if self.tool_id() == LIVE_PAINT_BUCKET {
|
||||
return (false, false);
|
||||
}
|
||||
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
|
||||
}
|
||||
}
|
||||
@@ -478,6 +531,8 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result
|
||||
/// remember the paint. Replies `{objects}`: how many objects took the paint.
|
||||
pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result<Value> {
|
||||
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
|
||||
let bucket = bucket_color_params(s, p, cmd)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let focus = switch_or(p, "focus", true, cmd)?;
|
||||
let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?;
|
||||
// Characters selected with the Type tool take the paint, not the whole type object (#1063).
|
||||
@@ -554,7 +609,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
}
|
||||
// Resolve the requested targets before mutating defaults or the active proxy.
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, fill);
|
||||
let selected = item.targets(s, p)?;
|
||||
let selected = item.targets_for(s, p, fill)?;
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let paint = if span {
|
||||
@@ -682,6 +737,89 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
|
||||
}
|
||||
|
||||
/// Is the Live Paint Bucket the active tool while `p` names no `ids`, `id` or `item`? A fill,
|
||||
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
|
||||
/// and the selection keeps its paint.
|
||||
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
|
||||
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
|
||||
s.tool_id() == LIVE_PAINT_BUCKET && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
|
||||
}
|
||||
|
||||
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
|
||||
/// A bad `target` or `aligned` is refused first, as it is without the bucket.
|
||||
pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
|
||||
if !for_bucket(s, p) {
|
||||
return Ok(None);
|
||||
}
|
||||
super::appearance::aligned(p, cmd)?;
|
||||
super::appearance::targets_contents(p)?;
|
||||
let mut v = p.as_object().cloned().unwrap_or_default();
|
||||
v.insert("ids".into(), json!([]));
|
||||
Ok(Some(Value::Object(v)))
|
||||
}
|
||||
|
||||
/// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of
|
||||
/// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command
|
||||
/// changes: a given or selected object other than a group or layer (a blend, say) and a compound
|
||||
/// shape are painted as one object, and a Live Paint group kept among another one's hidden sources
|
||||
/// is not one of them. The art of graph designs drawn in graph series is left out.
|
||||
fn live_paint_groups(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, Vec<NodeId>, Vec<NodeId>)> {
|
||||
fn find<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
|
||||
let group = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. });
|
||||
if is_live_paint(n) {
|
||||
out.push(n);
|
||||
} else if (group || !top) && !n.is_compound_shape() && !matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
n.children().into_iter().flatten().for_each(|c| find(c, false, out));
|
||||
}
|
||||
}
|
||||
let mut found = vec![];
|
||||
for n in roots.iter().filter_map(|r| d.node(*r)) {
|
||||
find(n, true, &mut found);
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
found.retain(|g| seen.insert(g.id));
|
||||
// A given or selected compound shape or compound path (or one inside a given or selected object) paints its members,
|
||||
// also when one of them is given as well. A Live Paint group given inside one that is not given stays a Live Paint group.
|
||||
let owns = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_compound_shape() || matches!(n.kind, NodeKind::Compound { .. }));
|
||||
let given: std::collections::HashSet<NodeId> = roots.iter().copied().collect();
|
||||
found.retain(|g| {
|
||||
!d.ancestry(g.id).is_some_and(|up| {
|
||||
let outer = up.iter().position(|a| given.contains(a)).unwrap_or(up.len());
|
||||
up.iter().skip(outer).any(|a| *a != g.id && owns(a))
|
||||
})
|
||||
});
|
||||
let kept: std::collections::HashSet<NodeId> = super::appearance::drop_design_art(d, found.iter().map(|g| g.id).collect()).into_iter().collect();
|
||||
let ids = |parts: Vec<&std::sync::Arc<Node>>| parts.into_iter().map(|part| part.id).collect();
|
||||
found.into_iter().filter(|g| kept.contains(&g.id)).map(|g| (g.id, ids(faces(g)), ids(edges(g)))).collect()
|
||||
}
|
||||
|
||||
/// Every object inside the Live Paint groups `groups` (faces, edges and the hidden source paths).
|
||||
fn inside_live_paint(d: &Document, groups: &[(NodeId, Vec<NodeId>, Vec<NodeId>)]) -> std::collections::HashSet<NodeId> {
|
||||
let mut out = std::collections::HashSet::new();
|
||||
for n in groups.iter().filter_map(|(g, _, _)| d.node(*g)) {
|
||||
n.walk(&mut |c| {
|
||||
if c.id != n.id {
|
||||
out.insert(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The objects inside the Live Paint groups in `roots` (or inside them) that a fill (`fill`) or a
|
||||
/// stroke given to the whole group leaves as they are: a fill paints the group's faces only, and a
|
||||
/// stroke its edges only. Their edges (faces) and hidden source paths are left out.
|
||||
pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: bool) -> std::collections::HashSet<NodeId> {
|
||||
let groups = live_paint_groups(d, roots);
|
||||
let mut out = inside_live_paint(d, &groups);
|
||||
for (_, faces, edges) in &groups {
|
||||
for id in if fill { faces } else { edges } {
|
||||
out.remove(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The instance whose object is selected with Direct Selection, and that object's path
|
||||
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
|
||||
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
|
||||
@@ -986,18 +1124,62 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize>
|
||||
}
|
||||
}
|
||||
|
||||
/// The paint every one of `parts` has on top as its fill (`fill`) or stroke, swatch link included
|
||||
/// and gradient placement left out ([`unplaced`]: each part fits it to its own bounds), or None
|
||||
/// when they differ or there are none. A freeform gradient's points and their colors belong to the
|
||||
/// part they sit on, so a freeform gradient on any part counts as a paint the parts do not share.
|
||||
fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option<Paint> {
|
||||
let mut paints = parts.iter().filter_map(|id| d.node(*id)).map(|n| if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() });
|
||||
let first = paints.next()?;
|
||||
let freeform =
|
||||
|p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some());
|
||||
if freeform(&first) {
|
||||
return None;
|
||||
}
|
||||
let first = unplaced(&first);
|
||||
paints.all(|p| !freeform(&p) && unplaced(&p) == first).then_some(first)
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bucket = bucket_color_params(s, p, "paint.swap")?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
// A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share.
|
||||
let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?);
|
||||
let inside = inside_live_paint(&s.doc()?.doc, &groups);
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect());
|
||||
// Only design art was given or selected: nothing changes, the defaults included.
|
||||
if given && ids.is_empty() {
|
||||
if given && ids.is_empty() && groups.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
if !ids.is_empty() || !groups.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// A group whose faces' fills (or edges' strokes) differ or are freeform gradients, or that has no face or no edge,
|
||||
// keeps its paint.
|
||||
let swaps: Vec<(&[NodeId], &[NodeId], Paint, Paint)> = groups
|
||||
.iter()
|
||||
.filter_map(|(_, faces, edges)| {
|
||||
Some((faces.as_slice(), edges.as_slice(), shared_paint(&before, faces, true)?, shared_paint(&before, edges, false)?))
|
||||
})
|
||||
.collect();
|
||||
let parts: Vec<NodeId> = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect();
|
||||
super::overprint::edit_counted(s, "Swap Fill and Stroke", |d| {
|
||||
for (faces, edges, fill, stroke) in &swaps {
|
||||
for id in *faces {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.appearance.set_fill(stroke.clone());
|
||||
}
|
||||
}
|
||||
for id in *edges {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
restore_unpainted_stroke(&mut n.appearance, None, fill);
|
||||
n.appearance.set_stroke(fill.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let parts_changed = super::appearance::count_changed(d, &before, &parts);
|
||||
for id in &ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
@@ -1017,7 +1199,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The swap writes the paint of the topmost fill and stroke, not their opacity.
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false, None);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels))
|
||||
})?;
|
||||
}
|
||||
if s.paint.stroke.is_none() && !s.paint.fill.is_none() && s.paint.stroke_width == 0.0 {
|
||||
@@ -1027,20 +1209,44 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The weight of the stroke [`paint.default`](default_paint) gives the edges of a whole Live Paint group.
|
||||
const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5;
|
||||
|
||||
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bucket = bucket_color_params(s, p, "paint.default")?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
// A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke.
|
||||
let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?);
|
||||
let inside = inside_live_paint(&s.doc()?.doc, &groups);
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect());
|
||||
// Only design art was given or selected: nothing changes, the defaults included.
|
||||
if given && ids.is_empty() {
|
||||
if given && ids.is_empty() && groups.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
if !ids.is_empty() || !groups.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
|
||||
let style = super::newart::redefined_default_style(&before).cloned();
|
||||
let parts: Vec<NodeId> = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect();
|
||||
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
|
||||
for (_, faces, edges) in &groups {
|
||||
let face = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::None))], ..Appearance::default() };
|
||||
let edge = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), LIVE_PAINT_DEFAULT_WEIGHT))],
|
||||
..Appearance::default()
|
||||
};
|
||||
for (ids, look) in [(faces, &face), (edges, &edge)] {
|
||||
for id in ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.appearance = look.clone().into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let parts_changed = super::appearance::count_changed(d, &before, &parts);
|
||||
for id in &ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
match &mut n.kind {
|
||||
@@ -1067,10 +1273,20 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.stroke = Paint::None;
|
||||
});
|
||||
let lines = super::graph::capture_line_fill_stroke_rows(d, &ids);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines))
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels || lines))
|
||||
})?;
|
||||
}
|
||||
super::newart::reset(s);
|
||||
if ids.is_empty() && !groups.is_empty() {
|
||||
// With only whole Live Paint groups given or selected, new art takes what their parts took, and nothing else.
|
||||
s.paint = vectorcraft_tools::PaintDefaults {
|
||||
fill: Paint::None,
|
||||
stroke: Paint::solid(Color::BLACK),
|
||||
stroke_width: LIVE_PAINT_DEFAULT_WEIGHT,
|
||||
..Default::default()
|
||||
};
|
||||
} else {
|
||||
super::newart::reset(s);
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -1078,6 +1294,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// default when there are none) and remember the first target's new paint. The Appearance panel's
|
||||
/// active item of the proxy's kind is recoloured in each selected object's own stack instead.
|
||||
fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
let bucket = bucket_color_params(s, p, cmd)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let stroke = stroke_param(s, p, cmd)?;
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: the solid color
|
||||
// it shows is recolored for this instance only. A gradient or pattern is refused, and so is type
|
||||
@@ -1174,11 +1392,20 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
if roots.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
|
||||
// The fill or stroke the proxy shows of each group among the roots, before the edit.
|
||||
// A Live Paint group's fill is its faces' fills and its stroke its edges' strokes, also with `target: "contents"`;
|
||||
// like any group, it recolors rows of its own as well.
|
||||
let parts_skipped = live_paint_parts_skipped(d, &ids, !stroke);
|
||||
let roots: Vec<NodeId> = roots.into_iter().filter(|id| !parts_skipped.contains(id)).collect();
|
||||
if roots.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let mut art: std::collections::HashSet<NodeId> = super::appearance::design_art_in(d, &roots).into_iter().collect();
|
||||
art.extend(parts_skipped.iter().copied());
|
||||
// The fill or stroke the proxy shows of each group among the roots, before the edit (a Live Paint group shows
|
||||
// its faces' or edges').
|
||||
let own = |d: &Document, id: NodeId| {
|
||||
d.node(id)
|
||||
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
|
||||
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !is_live_paint(n))
|
||||
.and_then(|n| n.proxy_paint_only(stroke, None))
|
||||
.cloned()
|
||||
};
|
||||
@@ -1196,7 +1423,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
shown_at = Some((*id, None));
|
||||
break;
|
||||
}
|
||||
if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
|
||||
let leaves = leaf_targets(s, &[*id])?.into_iter().filter(|leaf| !parts_skipped.contains(leaf)).collect();
|
||||
if let Some(leaf) = super::appearance::drop_design_art(d, leaves).first() {
|
||||
shown_at = Some((*leaf, None));
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
@@ -38,17 +38,28 @@ fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -
|
||||
return (false, false);
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
let mut covered = HashSet::new();
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
if !covered.contains(&n.id) {
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
}
|
||||
});
|
||||
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
let set = if item.is_some() {
|
||||
&selected
|
||||
} else if stroke {
|
||||
&strokes
|
||||
} else {
|
||||
&fills
|
||||
};
|
||||
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
|
||||
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
|
||||
c => c.into_iter().map(Paint::solid).collect(),
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -461,10 +461,15 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return link_handle(s, p, id, si, ai, out, pos);
|
||||
}
|
||||
let independent = switch_or(p, "independent", false, "path.setHandle")?;
|
||||
let at = match p.get("at").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
|
||||
};
|
||||
// A handle already there, on an anchor already of the kind it would get, changes nothing and
|
||||
// records no undo step. The handle is compared directly: `set_handle` would recompute the
|
||||
// other handle of a smooth anchor, which need not give back the same value.
|
||||
if let Some(a) = anchor_of(s, id, si, ai)?
|
||||
&& at.is_none_or(|to| to == a.p)
|
||||
&& (if out { a.h_out } else { a.h_in }) == pos
|
||||
&& !(independent && a.kind != AnchorKind::Corner)
|
||||
{
|
||||
@@ -473,7 +478,32 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Reshape", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.set_handle(out, pos, independent);
|
||||
let old_point = a.p;
|
||||
let old_handle = if out { a.h_out } else { a.h_in };
|
||||
if let Some(to) = at {
|
||||
a.translate(to - a.p);
|
||||
}
|
||||
let handle = if out { a.h_out } else { a.h_in };
|
||||
let kind_changes = independent && a.kind != AnchorKind::Corner;
|
||||
// Ordinary decimal moves can round `at - old_point` differently from the handle's
|
||||
// translation. Within that calculation's roundoff, place the selected point exactly
|
||||
// without realigning the other stored Smooth handle. Real edits still use set_handle.
|
||||
let translation_roundoff = at.is_some_and(|to| {
|
||||
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
|
||||
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
|
||||
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
|
||||
};
|
||||
to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
|
||||
});
|
||||
if !kind_changes && (handle == pos || translation_roundoff) {
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
}
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -499,7 +529,7 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a
|
||||
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
|
||||
})
|
||||
});
|
||||
if unchanged {
|
||||
@@ -515,6 +545,78 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Whether a smooth anchor `a` already has its `out` (or incoming) handle at `pos` and its other
|
||||
/// handle exactly where [`Anchor::link_handle`] puts it for that handle at some positive length.
|
||||
/// Turning the other handle again from its stored end measures its length anew, which can round
|
||||
/// the end differently in the last bit; a handle that passes this test only gets that rounding,
|
||||
/// and any other handle is turned. `p + u * len` here is the same arithmetic as in
|
||||
/// `Anchor::link_handle`, `dir / l` included.
|
||||
fn linked_already(a: &Anchor, out: bool, pos: Point) -> bool {
|
||||
let (moved, other) = if out { (a.h_out, a.h_in) } else { (a.h_in, a.h_out) };
|
||||
let dir = a.p - pos;
|
||||
let l = dir.x.hypot(dir.y);
|
||||
if a.kind != AnchorKind::Smooth || moved != pos || !(l > 0.0 && l.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let u = dir / l;
|
||||
// The lengths that give each stored coordinate exactly; the smallest length both ranges hold
|
||||
// is checked against the whole end.
|
||||
let (mut lo, mut hi) = (0.0_f64, f64::INFINITY);
|
||||
for (p, o, u) in [(a.p.x, other.x, u.x), (a.p.y, other.y, u.y)] {
|
||||
if u == 0.0 {
|
||||
if o != p {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((first, last)) = lengths_onto(p, u, o) else {
|
||||
return false;
|
||||
};
|
||||
(lo, hi) = (lo.max(first), hi.min(last));
|
||||
}
|
||||
lo <= hi && lo > 0.0 && lo.is_finite() && a.p + u * lo == other
|
||||
}
|
||||
|
||||
/// The lengths `len` for which `p + u * len` rounds to exactly `o`, as their smallest and largest,
|
||||
/// for a `u` other than 0. The rounded sum moves the same way as `len`, so a range around the
|
||||
/// unrounded answer is widened until it brackets `o` and then halved down to each end.
|
||||
fn lengths_onto(p: f64, u: f64, o: f64) -> Option<(f64, f64)> {
|
||||
let s = u.signum();
|
||||
let below = |len: f64| s * (p + u * len) < s * o;
|
||||
let above = |len: f64| s * (p + u * len) > s * o;
|
||||
let c = (o - p) / u;
|
||||
let mut d = (o.abs() + p.abs()).max(f64::MIN_POSITIVE) * f64::EPSILON / u.abs();
|
||||
let mut bracket = None;
|
||||
for _ in 0..64 {
|
||||
if below(c - d) && above(c + d) {
|
||||
bracket = Some((c - d, c + d));
|
||||
break;
|
||||
}
|
||||
d *= 2.0;
|
||||
}
|
||||
let (lo, hi) = bracket?;
|
||||
let first = halve(lo, hi, |len| !below(len)).1;
|
||||
let last = halve(lo, hi, above).0;
|
||||
(first <= last).then_some((first, last))
|
||||
}
|
||||
|
||||
/// Narrows `lo..hi`, where `pred` is false at `lo` and true at `hi` and changes once between
|
||||
/// them, to two neighboring values with the same property.
|
||||
fn halve(mut lo: f64, mut hi: f64, pred: impl Fn(f64) -> bool) -> (f64, f64) {
|
||||
for _ in 0..2200 {
|
||||
let m = lo + (hi - lo) / 2.0;
|
||||
if m <= lo || m >= hi {
|
||||
break;
|
||||
}
|
||||
if pred(m) {
|
||||
hi = m;
|
||||
} else {
|
||||
lo = m;
|
||||
}
|
||||
}
|
||||
(lo, hi)
|
||||
}
|
||||
|
||||
/// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point
|
||||
/// tool's Shift-drag).
|
||||
fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -695,6 +695,7 @@ impl PlaceJob {
|
||||
/// the renderers' image store for the first frame that draws them
|
||||
/// ([`super::links::readable_and_kept`]).
|
||||
pub fn read(self) -> Result<PlaceRead> {
|
||||
crate::cancel::check()?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
|
||||
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
|
||||
match &mut loaded.art {
|
||||
|
||||
@@ -46,6 +46,8 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.packaging.setRole",
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.boundingCircle",
|
||||
"addon.pathtools.boundingRectangle",
|
||||
"addon.pathtools.bridge",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.commonTangents",
|
||||
@@ -461,6 +463,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"path.mirrorCut",
|
||||
"path.moveAnchor",
|
||||
"path.moveAnchors",
|
||||
"path.quickPen",
|
||||
"path.rectCut",
|
||||
"path.removeAnchor",
|
||||
"path.removeAnchors",
|
||||
@@ -557,6 +560,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.update",
|
||||
"shape.arc",
|
||||
"shape.circleThroughPoints",
|
||||
"shape.curvatureCircle",
|
||||
"shape.editFlare",
|
||||
"shape.ellipse",
|
||||
"shape.flare",
|
||||
@@ -600,6 +604,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"swatch.move",
|
||||
"swatch.new",
|
||||
"swatch.newGroup",
|
||||
"swatch.renameGroup",
|
||||
"swatch.resetDefaults",
|
||||
"swatch.setSpot",
|
||||
"swatch.sortByKind",
|
||||
@@ -698,6 +703,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"type.resetHorizontalScale",
|
||||
"type.resetTracking",
|
||||
"type.retype",
|
||||
"type.retypeFonts",
|
||||
"type.ruby",
|
||||
"type.scaleTextAttributes",
|
||||
"type.size.decrease",
|
||||
|
||||
@@ -456,6 +456,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
choice(&[("default", "Default"), ("object", "Transform Object Only"), ("pattern", "Transform Pattern Only"), ("both", "Transform Both")])
|
||||
),
|
||||
p!("useRegistrationPointForSymbol", "General", "Transform Panel", "Use Registration Point for Symbol", bool),
|
||||
// The Transform panel menu: drawing a shape shows the panel.
|
||||
p!("showOnShapeCreation", "General", "Transform Panel", "Show on Shape Creation", bool),
|
||||
// The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink.
|
||||
p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool),
|
||||
p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool),
|
||||
|
||||
@@ -45,6 +45,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
#[path = "retype_fonts.rs"]
|
||||
pub(super) mod fonts;
|
||||
|
||||
/// A shape to match: a path or compound path, in document space.
|
||||
struct Piece {
|
||||
id: NodeId,
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Retype's matching fonts (`type.retypeFonts`): the fonts whose glyphs match the selected outlined
|
||||
//! text, ranked, for the Retype panel's list
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>).
|
||||
//! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with
|
||||
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same
|
||||
//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its
|
||||
//! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many
|
||||
//! of the shapes it matches, then by how closely, on average, and then by name. The query changes
|
||||
//! nothing.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_text::FontDb;
|
||||
use vectorcraft_text::retype::{RetypeIndex, shape_key};
|
||||
|
||||
use super::super::edit::selected_roots;
|
||||
use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path};
|
||||
use super::{candidate_faces, collect};
|
||||
|
||||
pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "type.retypeFonts",
|
||||
"Find Matching Fonts",
|
||||
[],
|
||||
None,
|
||||
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
|
||||
has_selected_path,
|
||||
retype_fonts
|
||||
)]
|
||||
}
|
||||
|
||||
/// The fonts listed when `count` is left out.
|
||||
pub(super) const DEFAULT_COUNT: usize = 10;
|
||||
/// The most fonts one query lists: every face the matching indexes.
|
||||
pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES;
|
||||
|
||||
/// One font that matched some of the shapes.
|
||||
struct Ranked {
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
/// How many shapes it matched.
|
||||
matched: usize,
|
||||
/// The sum of those matches' leftover distances.
|
||||
residual: f64,
|
||||
}
|
||||
|
||||
impl Ranked {
|
||||
fn mean(&self) -> f64 {
|
||||
self.residual / self.matched.max(1) as f64
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
retype_fonts_in(s, p, FontDb::global())
|
||||
}
|
||||
|
||||
/// [`retype_fonts`] with the fonts of `db`.
|
||||
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
const C: &str = "type.retypeFonts";
|
||||
let count = match p.get("count") {
|
||||
None | Some(Value::Null) => DEFAULT_COUNT,
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_COUNT).contains(n))
|
||||
.ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?,
|
||||
};
|
||||
let roots = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut pieces = vec![];
|
||||
let (mut barrier, mut truncated) = (true, false);
|
||||
for r in &roots {
|
||||
if let Some(n) = d.node(*r) {
|
||||
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
}
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
|
||||
}
|
||||
// Only glyphs with a selected shape's key (segments per contour) can match one.
|
||||
let wanted: BTreeSet<u64> = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect();
|
||||
// A font is chosen by its family and style, which set the version the name gives: of two
|
||||
// versions of one font, only that one is compared. The other versions do not take the places
|
||||
// of fonts loaded after them.
|
||||
let by_name = |f: &Arc<vectorcraft_text::FontFace>| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id());
|
||||
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect();
|
||||
for f in db.loaded_faces() {
|
||||
if faces.len() >= vectorcraft_text::retype::MAX_FACES {
|
||||
break;
|
||||
}
|
||||
if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) {
|
||||
faces.push(f);
|
||||
}
|
||||
}
|
||||
// No shape has a key: no font is read.
|
||||
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) };
|
||||
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
|
||||
let mut ranked: Vec<Ranked> = vec![];
|
||||
for pc in &pieces {
|
||||
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
|
||||
// closest fit.
|
||||
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64)> = vec![];
|
||||
for m in index.all_matches(&pc.path) {
|
||||
match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) {
|
||||
Some(b) => b.1 = b.1.min(m.residual),
|
||||
None => best.push((m.face, m.residual)),
|
||||
}
|
||||
}
|
||||
for (face, residual) in best {
|
||||
match ranked.iter_mut().find(|r| r.face.id() == face.id()) {
|
||||
Some(r) => {
|
||||
r.matched += 1;
|
||||
r.residual += residual;
|
||||
}
|
||||
None => ranked.push(Ranked { face, matched: 1, residual }),
|
||||
}
|
||||
}
|
||||
}
|
||||
ranked.sort_by(|a, b| {
|
||||
b.matched
|
||||
.cmp(&a.matched)
|
||||
.then(a.mean().total_cmp(&b.mean()))
|
||||
.then_with(|| a.face.family.to_lowercase().cmp(&b.face.family.to_lowercase()))
|
||||
.then_with(|| a.face.style.to_lowercase().cmp(&b.face.style.to_lowercase()))
|
||||
.then(a.face.id().cmp(&b.face.id()))
|
||||
});
|
||||
let more = ranked.len() > count;
|
||||
ranked.truncate(count);
|
||||
Ok(json!({
|
||||
"fonts": ranked.iter().map(|r| json!({"family": r.face.family, "style": r.face.style, "matched": r.matched})).collect::<Vec<_>>(),
|
||||
"shapes": pieces.len(),
|
||||
"more": more,
|
||||
"truncated": truncated,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "retype_fonts_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,159 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The bundled fonts alone: other tests add copies of them to the global database, and a copy
|
||||
/// ties with its original, so the ranking is read against a database of its own.
|
||||
fn bundled() -> &'static FontDb {
|
||||
static DB: OnceLock<FontDb> = OnceLock::new();
|
||||
DB.get_or_init(|| FontDb::with_font_dirs(vec![]))
|
||||
}
|
||||
|
||||
/// `type.retypeFonts` with `params`, comparing the fonts of `db`.
|
||||
fn query(s: &mut Session, params: Value, db: &FontDb) -> Value {
|
||||
super::retype_fonts_in(s, ¶ms, db).unwrap()
|
||||
}
|
||||
|
||||
/// Point text, outlined: the id of the outlines' group.
|
||||
fn outlined(s: &mut Session, p: Value) -> u64 {
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn names(r: &Value) -> Vec<(String, String, u64)> {
|
||||
r["fonts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|f| (f["family"].as_str().unwrap().to_string(), f["style"].as_str().unwrap().to_string(), f["matched"].as_u64().unwrap()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_fonts_rank_by_how_many_shapes_each_matches() {
|
||||
let mut s = session();
|
||||
// Seven shapes in Source Sans 3 Bold, three in Source Serif 4.
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ranking", "size": 30, "font": "Source Sans 3", "style": "Bold"}));
|
||||
let b = outlined(&mut s, json!({"x": 40, "y": 200, "text": "Wxy", "size": 30, "font": "Source Serif 4", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = query(&mut s, json!({}), bundled());
|
||||
assert_eq!(r["shapes"], json!(10), "{r}");
|
||||
let fonts = names(&r);
|
||||
assert_eq!(fonts.first(), Some(&("Source Sans 3".to_string(), "Bold".to_string(), 7)), "{r}");
|
||||
let serif = fonts.iter().position(|f| f.0 == "Source Serif 4" && f.1 == "Regular").expect("the serif is listed");
|
||||
assert_eq!(fonts[serif].2, 3, "{r}");
|
||||
// Each font once, and no font matches more shapes than one listed before it.
|
||||
for (i, f) in fonts.iter().enumerate() {
|
||||
assert!(!fonts[..i].iter().any(|g| g.0 == f.0 && g.1 == f.1), "{f:?} is listed twice: {r}");
|
||||
assert!(fonts[..i].iter().all(|g| g.2 >= f.2), "{f:?} ranks after a font that matches fewer shapes: {r}");
|
||||
}
|
||||
assert_eq!(r["truncated"], json!(false));
|
||||
// The command: a query, so the document stays as it was, and there is no undo step for it.
|
||||
let r = s.execute("type.retypeFonts", &json!({})).unwrap();
|
||||
assert_eq!(r["shapes"], json!(10), "{r}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc != before, "undo takes back the last outlining, not the query");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_lists_the_first_fonts_and_more_says_others_match() {
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Aa", "size": 30, "font": "Source Sans 3", "style": "Regular"}));
|
||||
let b = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 30, "font": "Source Serif 4", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let all = query(&mut s, json!({"count": 96}), bundled());
|
||||
assert!(names(&all).len() >= 2, "{all}");
|
||||
assert_eq!(all["more"], json!(false), "{all}");
|
||||
let one = query(&mut s, json!({"count": 1}), bundled());
|
||||
assert_eq!(names(&one), vec![("Source Sans 3".to_string(), "Regular".to_string(), 2)], "{one}");
|
||||
assert_eq!(one["more"], json!(true), "{one}");
|
||||
assert_eq!(query(&mut s, json!({"count": null}), bundled()), query(&mut s, json!({}), bundled()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_that_is_not_a_whole_number_from_1_to_96_is_an_error() {
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 30}));
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
for bad in [json!(0), json!(97), json!(-1), json!(2.5), json!("10"), json!(true)] {
|
||||
let e = s.execute("type.retypeFonts", &json!({"count": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`count` must be a whole number from 1 to 96"), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_that_are_no_glyph_list_no_font() {
|
||||
let mut s = session();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
let r = query(&mut s, json!({}), bundled());
|
||||
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
|
||||
// Live type alone holds no shape to compare.
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
assert!(s.execute("type.retypeFonts", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_past_the_limits_are_reported_as_left_out() {
|
||||
let mut s = session();
|
||||
let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
|
||||
// B, nested deeper than Retype looks.
|
||||
let mut deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40}));
|
||||
for _ in 0..20 {
|
||||
s.execute("select.set", &json!({"ids": [deep]})).unwrap();
|
||||
deep = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [top, deep]})).unwrap();
|
||||
let r = query(&mut s, json!({}), bundled());
|
||||
assert_eq!((r["shapes"].clone(), r["truncated"].clone()), (json!(1), json!(true)), "{r}");
|
||||
}
|
||||
|
||||
/// Two versions of one font: choosing the font by name sets the version the name gives, so only
|
||||
/// that version is compared, and a font whose other version alone matches is not listed.
|
||||
#[test]
|
||||
fn of_two_versions_only_the_one_the_name_gives_is_listed() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
const FAMILY: &str = "Versiontest Sans";
|
||||
// A database of its own, so that no other test sees these fonts.
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
// The first version loaded (Source Sans 3's glyphs) is the one the name gives.
|
||||
db.add_font(named_copy(false, (FAMILY, "Regular", "Version 1.000", "VersiontestSans-Regular")).unwrap());
|
||||
db.add_font(named_copy(true, (FAMILY, "Regular", "Version 2.000", "VersiontestSans-Regular")).unwrap());
|
||||
assert_eq!(db.face(FAMILY, "Regular").unwrap().version, "Version 1.000");
|
||||
let mut s = session();
|
||||
let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kg", "size": 40, "font": "Inter", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [inter]})).unwrap();
|
||||
let r = query(&mut s, json!({"count": 96}), &db);
|
||||
let fonts = names(&r);
|
||||
assert!(fonts.iter().any(|f| f.0 == "Inter"), "{r}");
|
||||
assert!(!fonts.iter().any(|f| f.0 == FAMILY), "version 2 matches, but choosing the font sets version 1: {r}");
|
||||
let source = outlined(&mut s, json!({"x": 40, "y": 200, "text": "Kg", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [source]})).unwrap();
|
||||
let r = query(&mut s, json!({"count": 96}), &db);
|
||||
assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_that_stay_outlines_still_name_their_font() {
|
||||
// A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph.
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 40, "font": "Source Serif 4", "style": "Regular"}));
|
||||
let glyph = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(g)).unwrap().children().unwrap()[0].id.0;
|
||||
s.execute("select.set", &json!({"ids": [glyph]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let r = query(&mut s, json!({}), bundled());
|
||||
assert_eq!(names(&r).first().map(|f| (f.0.as_str(), f.1.as_str())), Some(("Source Serif 4", "Regular")), "{r}");
|
||||
}
|
||||
@@ -8,9 +8,10 @@ use vectorcraft_doc::{
|
||||
Unit, WidthProfile,
|
||||
};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::appearance::{ItemTarget, edit_items, item_target};
|
||||
use super::paint::painted;
|
||||
use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
|
||||
use crate::DocState;
|
||||
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
|
||||
@@ -22,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
["Window", "Stroke"],
|
||||
None,
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}",
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
|
||||
has_doc,
|
||||
stroke_set
|
||||
),
|
||||
@@ -31,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Weight Up",
|
||||
[],
|
||||
Some("Cmd+Alt+."),
|
||||
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}",
|
||||
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}",
|
||||
has_doc,
|
||||
|s, p| stroke_step(s, p, true)
|
||||
),
|
||||
@@ -49,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
[],
|
||||
None,
|
||||
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)",
|
||||
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
|
||||
has_doc,
|
||||
stroke_advanced
|
||||
),
|
||||
@@ -210,20 +211,25 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool {
|
||||
|
||||
/// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of
|
||||
/// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other
|
||||
/// targets reach their painted leaves, as before.
|
||||
/// targets reach their painted leaves, as before (a Live Paint group's edges, not its faces).
|
||||
fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::NodeId>> {
|
||||
let picked = super::targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A Live Paint group's stroke is its edges' strokes, also when it has a stroke row of its own.
|
||||
let own = |id: &vectorcraft_doc::NodeId| {
|
||||
d.node(*id).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
&& !n.is_compound_shape()
|
||||
&& n.appearance.stroke().is_some()
|
||||
&& !is_live_paint(n)
|
||||
})
|
||||
};
|
||||
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
|
||||
let faces = live_paint_parts_skipped(d, &rest, false);
|
||||
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
|
||||
let mut seen: std::collections::HashSet<vectorcraft_doc::NodeId> = out.iter().copied().collect();
|
||||
for id in super::leaf_targets(s, &rest)? {
|
||||
if seen.insert(id) {
|
||||
if !faces.contains(&id) && seen.insert(id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
@@ -233,13 +239,26 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::N
|
||||
fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.set";
|
||||
let change = StrokeChange::parse(p, C)?;
|
||||
// The stroke the Live Paint Bucket paints with changes; the selection keeps its own, and its
|
||||
// active Appearance row is not a target.
|
||||
let bucket_p = super::paint::bucket_color_params(s, p, C)?;
|
||||
let bucket = bucket_p.is_some();
|
||||
let p = bucket_p.as_ref().unwrap_or(p);
|
||||
let item = item_target(s, p, C)?.of_kind(s, false);
|
||||
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
|
||||
let new_art = no_targets(&ids, p);
|
||||
let given = !ids.is_empty();
|
||||
let mut ids = if bucket {
|
||||
vec![]
|
||||
} else if item == ItemTarget::Top {
|
||||
own_stroke_or_leaves(s, p)?
|
||||
} else {
|
||||
item.targets(s, p)?
|
||||
};
|
||||
// A Live Paint group without edges was still selected or given: the options do not go to new art.
|
||||
let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
|
||||
let new_art = bucket || (no_targets(&ids, p) && !live_paint);
|
||||
let given = !ids.is_empty() || live_paint;
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
|
||||
// With only design art, the weight for new art stays as it is too.
|
||||
// With only design art, or only Live Paint groups without edges, the weight for new art stays as it is too.
|
||||
let only_design_art = given && ids.is_empty();
|
||||
if item == ItemTarget::Top {
|
||||
// Images and symbol instances take no stroke from the panel.
|
||||
@@ -371,9 +390,14 @@ pub(crate) fn step_weight(w: f64, unit: Unit, up: bool) -> f64 {
|
||||
fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
let c = if up { "stroke.weightUp" } else { "stroke.weightDown" };
|
||||
let unit = s.stroke_unit();
|
||||
// The weight the Live Paint Bucket paints with changes; the selection keeps its own, and its
|
||||
// active Appearance row is not a target.
|
||||
let bucket_p = super::paint::bucket_color_params(s, p, c)?;
|
||||
let bucket = bucket_p.is_some();
|
||||
let p = bucket_p.as_ref().unwrap_or(p);
|
||||
let item = item_target(s, p, c)?.of_kind(s, false);
|
||||
let ids = item.targets(s, p)?;
|
||||
if no_targets(&ids, p) {
|
||||
let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? };
|
||||
if bucket || (no_targets(&ids, p) && !skipped) {
|
||||
let w = step_weight(s.paint.stroke_width, unit, up);
|
||||
s.paint.stroke_width = w;
|
||||
if let Some(st) = s.new_art_stroke_mut() {
|
||||
@@ -412,13 +436,18 @@ impl Session {
|
||||
|
||||
/// The stroke the Stroke panel, the Control bar and the Properties panel show, picked as the
|
||||
/// Stroke proxy picks its paint: the Appearance panel's active item when it is a stroke, else
|
||||
/// the first selected object's (a group's first painted object's) top stroke, type's first
|
||||
/// run's character stroke; with an object of a dynamic symbol instance selected
|
||||
/// the first selected object's (a group's first painted object's, a Live Paint group's first
|
||||
/// edge's, or the next selected object's when a Live Paint group has no edge) top stroke, type's
|
||||
/// first run's character stroke; with an object of a dynamic symbol instance selected
|
||||
/// ([`DocState::selected_symbol_part`]), that object's as the instance draws it; with nothing
|
||||
/// selected, the next object drawn's ([`Session::new_art_stroke`]). None without a document or
|
||||
/// the selection's stroke.
|
||||
/// selected, the next object drawn's ([`Session::new_art_stroke`]), and so while the Live Paint
|
||||
/// Bucket is the active tool (the stroke it paints with). None without a document or the
|
||||
/// selection's stroke.
|
||||
pub fn shown_stroke(&self) -> Option<StrokeLayer> {
|
||||
let st = self.active()?;
|
||||
if self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
|
||||
return Some(self.new_art_stroke());
|
||||
}
|
||||
if let Some(part) = st.selected_symbol_part() {
|
||||
return node_stroke(&part);
|
||||
}
|
||||
@@ -427,9 +456,20 @@ impl Session {
|
||||
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
|
||||
return first.appearance.stroke_at(Some(i)).cloned();
|
||||
}
|
||||
let mut nodes = vec![];
|
||||
painted(first, true, &mut nodes);
|
||||
node_stroke(nodes.first()?)
|
||||
// A Live Paint group without edges shows the next selected object's stroke; any other object
|
||||
// without a painted object shows none.
|
||||
for id in &st.selection.objects {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, true, &mut nodes);
|
||||
if let Some(n) = nodes.first() {
|
||||
return node_stroke(n);
|
||||
}
|
||||
if !is_live_paint(n) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush
|
||||
@@ -488,12 +528,13 @@ impl DocState {
|
||||
let part = self.selected_symbol_part();
|
||||
let mut nodes = vec![];
|
||||
if let Some(part) = &part {
|
||||
painted(part, true, &mut nodes);
|
||||
painted(part, true, true, &mut nodes);
|
||||
} else {
|
||||
for id in &self.selection.objects {
|
||||
if let Some(n) = self.doc.node(*id) {
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let covered: std::collections::HashSet<vectorcraft_doc::NodeId> = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
|
||||
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
|
||||
painted(n, true, true, &mut nodes);
|
||||
}
|
||||
}
|
||||
let mut strokes = vec![];
|
||||
@@ -568,9 +609,14 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if scale.is_none() && flip.is_none() && !swap && brush.is_none() {
|
||||
return Err(bad(C, "nothing to change"));
|
||||
}
|
||||
// As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own.
|
||||
// A brush still goes to the selection.
|
||||
let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None };
|
||||
let bucket = bucket_p.is_some();
|
||||
let p = bucket_p.as_ref().unwrap_or(p);
|
||||
let item = item_target(s, p, C)?.of_kind(s, false);
|
||||
let ids = item.targets(s, p)?;
|
||||
let new_art = no_targets(&ids, p);
|
||||
let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? };
|
||||
let new_art = bucket || (no_targets(&ids, p) && !skipped);
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
|
||||
let arrows_and_profile = |st: &mut StrokeLayer| {
|
||||
|
||||
@@ -9,7 +9,9 @@ use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, ma
|
||||
use vectorcraft_doc::{Document, NodeId};
|
||||
|
||||
use super::paint::paint_from;
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or, text_param,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -106,6 +108,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
swatch_ungroup
|
||||
),
|
||||
cmd!(
|
||||
"swatch.renameGroup",
|
||||
"Color Group Options",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{group: color group, name: its new name (trimmed)} rename a color group, as one undo step; its swatches, their colors and the art linked to them stay as they are. Swatches and color groups share one set of names, so a name another color group or a swatch has is an error, as is an empty name; the group's own name records no undo step. A drag still in progress becomes an undo step of its own first → {name}",
|
||||
has_doc,
|
||||
swatch_rename_group
|
||||
),
|
||||
cmd!(
|
||||
"swatch.sortByKind",
|
||||
"Sort by Kind",
|
||||
@@ -1200,6 +1211,35 @@ fn swatch_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "swatches": moved }))
|
||||
}
|
||||
|
||||
fn swatch_rename_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.renameGroup";
|
||||
let group = text_param(p, "group", C)?.ok_or_else(|| bad(C, "missing `group`"))?.to_string();
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.trim().to_string();
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, "`name` is empty"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
if !d.swatch_groups.iter().any(|g| g.name == group) {
|
||||
return Err(bad(C, format!("no colour group `{group}`")));
|
||||
}
|
||||
if name == group {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
if d.swatch_name_taken(&name) {
|
||||
return Err(bad(C, format!("a swatch or color group named `{name}` already exists")));
|
||||
}
|
||||
// A drag still in progress is a step of its own, so canceling or undoing it leaves the rename.
|
||||
if !s.previewing && s.batch_stash.is_none() && s.in_interaction() {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
s.edit("Color Group Options", |d, _| {
|
||||
let g = d.swatch_groups.iter_mut().find(|g| g.name == group).ok_or_else(|| bad(C, format!("no colour group `{group}`")))?;
|
||||
g.name.clone_from(&name);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
fn swatch_sort_by_kind(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let rank = |w: &Swatch| match &w.paint {
|
||||
Paint::None => 0,
|
||||
|
||||
@@ -170,6 +170,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[
|
||||
BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons },
|
||||
BuiltinSymbolLibrary { id: "skill-icons", name: "Skill Icons", make: skill_icons },
|
||||
BuiltinSymbolLibrary { id: "weather-icons", name: "Weather Icons", make: weather_icons },
|
||||
BuiltinSymbolLibrary { id: "media-controls", name: "Media Controls", make: media_controls },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -502,6 +503,130 @@ fn weather_icons() -> SymbolLibrary {
|
||||
SymbolLibrary { name: "Weather Icons".into(), doc }
|
||||
}
|
||||
|
||||
/// Media Controls: play, pause, stop, skip next, shuffle and repeat for audio/video UI art (original, no 9-slice).
|
||||
fn media_controls() -> SymbolLibrary {
|
||||
// 1. Play: Right-pointing equilateral triangle.
|
||||
let play = shapes::polygon(Point::ZERO, 18.0, 3, 90.0);
|
||||
|
||||
// 2. Pause: Two parallel vertical rounded bars.
|
||||
let mut pause_subpaths = Vec::new();
|
||||
pause_subpaths.extend(shapes::rounded_rectangle(Rect::new(-11.0, -15.0, -3.0, 15.0), 3.0).subpaths);
|
||||
pause_subpaths.extend(shapes::rounded_rectangle(Rect::new(3.0, -15.0, 11.0, 15.0), 3.0).subpaths);
|
||||
let pause = PathData::new(pause_subpaths);
|
||||
|
||||
// 3. Stop: Rounded square.
|
||||
let stop = shapes::rounded_rectangle(Rect::new(-14.0, -14.0, 14.0, 14.0), 4.0);
|
||||
|
||||
// 4. Skip Next: Right-pointing triangle with adjacent vertical bar.
|
||||
let mut skip_subpaths = Vec::new();
|
||||
let tri_pts = [Point::new(-14.0, -14.0), Point::new(6.0, 0.0), Point::new(-14.0, 14.0)];
|
||||
skip_subpaths.push(SubPath::polyline(&tri_pts, true));
|
||||
skip_subpaths.extend(shapes::rounded_rectangle(Rect::new(8.0, -14.0, 13.0, 14.0), 2.0).subpaths);
|
||||
let skip_next = PathData::new(skip_subpaths);
|
||||
|
||||
// Helper for ribbon arrows with optional arrowhead
|
||||
let make_arrow = |pts: &[Point], half_w: f64, head: Option<(f64, f64)>| -> SubPath {
|
||||
let n = pts.len();
|
||||
let mut left_pts = Vec::new();
|
||||
let mut right_pts = Vec::new();
|
||||
|
||||
let mut seg_normals = Vec::with_capacity(n - 1);
|
||||
let mut seg_dirs = Vec::with_capacity(n - 1);
|
||||
for i in 0..(n - 1) {
|
||||
let d = pts[i + 1] - pts[i];
|
||||
let len = (d.x * d.x + d.y * d.y).sqrt().max(1e-6);
|
||||
let dir = Point::new(d.x / len, d.y / len);
|
||||
let normal = Point::new(-dir.y, dir.x);
|
||||
seg_dirs.push(dir);
|
||||
seg_normals.push(normal);
|
||||
}
|
||||
|
||||
for i in 0..n {
|
||||
let normal = if i == 0 {
|
||||
seg_normals[0]
|
||||
} else if i == n - 1 {
|
||||
seg_normals[n - 2]
|
||||
} else {
|
||||
let n1 = seg_normals[i - 1];
|
||||
let n2 = seg_normals[i];
|
||||
let avg = Point::new((n1.x + n2.x) * 0.5, (n1.y + n2.y) * 0.5);
|
||||
let len = (avg.x * avg.x + avg.y * avg.y).sqrt().max(1e-6);
|
||||
Point::new(avg.x / len, avg.y / len)
|
||||
};
|
||||
left_pts.push(Point::new(pts[i].x + normal.x * half_w, pts[i].y + normal.y * half_w));
|
||||
right_pts.push(Point::new(pts[i].x - normal.x * half_w, pts[i].y - normal.y * half_w));
|
||||
}
|
||||
|
||||
let mut poly = left_pts;
|
||||
if let Some((head_w, head_len)) = head {
|
||||
let end_pt = pts[n - 1];
|
||||
let end_dir = seg_dirs[n - 2];
|
||||
let end_norm = seg_normals[n - 2];
|
||||
poly.push(Point::new(end_pt.x + end_norm.x * head_w, end_pt.y + end_norm.y * head_w));
|
||||
poly.push(Point::new(end_pt.x + end_dir.x * head_len, end_pt.y + end_dir.y * head_len));
|
||||
poly.push(Point::new(end_pt.x - end_norm.x * head_w, end_pt.y - end_norm.y * head_w));
|
||||
}
|
||||
right_pts.reverse();
|
||||
poly.extend(right_pts);
|
||||
SubPath::polyline(&poly, true)
|
||||
};
|
||||
|
||||
// 5. Shuffle: Two crossing/intertwined arrows.
|
||||
let a1 = [Point::new(-14.0, -9.0), Point::new(-5.0, -9.0), Point::new(5.0, 9.0), Point::new(8.0, 9.0)];
|
||||
let a2a = [Point::new(-14.0, 9.0), Point::new(-5.0, 9.0), Point::new(-1.8, 3.24)];
|
||||
let a2b = [Point::new(1.8, -3.24), Point::new(5.0, -9.0), Point::new(8.0, -9.0)];
|
||||
let shuffle = PathData::new(vec![make_arrow(&a1, 1.4, Some((4.0, 6.0))), make_arrow(&a2a, 1.4, None), make_arrow(&a2b, 1.4, Some((4.0, 6.0)))]);
|
||||
|
||||
// 6. Repeat: Looping circular arrows.
|
||||
let r_mid = 11.5;
|
||||
let r_in = 9.8;
|
||||
let r_out = 13.2;
|
||||
let head_w = 4.0;
|
||||
let tip_len = 5.0;
|
||||
let a_start = -150.0_f64.to_radians();
|
||||
let a_end = -15.0_f64.to_radians();
|
||||
let steps = 14;
|
||||
|
||||
let mut top_pts = Vec::new();
|
||||
for i in 0..=steps {
|
||||
let a = a_start + (a_end - a_start) * (i as f64) / (steps as f64);
|
||||
top_pts.push(Point::new(r_out * a.cos(), r_out * a.sin()));
|
||||
}
|
||||
top_pts.push(Point::new((r_mid + head_w) * a_end.cos(), (r_mid + head_w) * a_end.sin()));
|
||||
let t_dir = Point::new(-a_end.sin(), a_end.cos());
|
||||
top_pts.push(Point::new(r_mid * a_end.cos() + tip_len * t_dir.x, r_mid * a_end.sin() + tip_len * t_dir.y));
|
||||
top_pts.push(Point::new((r_mid - head_w) * a_end.cos(), (r_mid - head_w) * a_end.sin()));
|
||||
for i in (0..=steps).rev() {
|
||||
let a = a_start + (a_end - a_start) * (i as f64) / (steps as f64);
|
||||
top_pts.push(Point::new(r_in * a.cos(), r_in * a.sin()));
|
||||
}
|
||||
|
||||
let bottom_pts: Vec<Point> = top_pts.iter().map(|p| Point::new(-p.x, -p.y)).collect();
|
||||
|
||||
let repeat = PathData::new(vec![SubPath::polyline(&top_pts, true), SubPath::polyline(&bottom_pts, true)]);
|
||||
|
||||
let icons = [
|
||||
("Play", play, "#2ecc71"),
|
||||
("Pause", pause, "#f39c12"),
|
||||
("Stop", stop, "#e74c3c"),
|
||||
("Skip Next", skip_next, "#3498db"),
|
||||
("Shuffle", shuffle, "#9b59b6"),
|
||||
("Repeat", repeat, "#1abc9c"),
|
||||
];
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (name, path, hex) in icons {
|
||||
let fill = Color::from_hex(hex).unwrap_or(Color::BLACK);
|
||||
let edge = fill.lerp(&Color::BLACK, 0.35);
|
||||
let id = doc.alloc_id();
|
||||
let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25));
|
||||
let Ok((art, size, _)) = normalize(art) else { continue };
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
set_natural_size(&mut doc, name, Some(size));
|
||||
}
|
||||
doc.title = "Media Controls".into();
|
||||
SymbolLibrary { name: "Media Controls".into(), doc }
|
||||
}
|
||||
|
||||
/// An instance of symbol `name` (what the resource gathering follows).
|
||||
fn instance(name: &str) -> Node {
|
||||
Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Sample Color",
|
||||
[],
|
||||
None,
|
||||
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
|
||||
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
|
||||
has_doc,
|
||||
sample_color
|
||||
),
|
||||
|
||||
@@ -24,6 +24,11 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
|
||||
/// `indices` instead.
|
||||
pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"];
|
||||
|
||||
/// The commands that the Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment
|
||||
/// tools and their dialogs, and the Shaper tool for a shape it recognizes, run to draw a shape
|
||||
/// ([`crate::Session::take_shape_drawn`]).
|
||||
pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.polygon", "shape.star", "shape.line"];
|
||||
|
||||
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
|
||||
/// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the
|
||||
/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the
|
||||
|
||||
@@ -110,6 +110,9 @@ pub struct Session {
|
||||
/// Set while saved steps play ([`Session::replay`]): [`Session::execute`] then takes keys the
|
||||
/// command's params description doesn't name instead of refusing them.
|
||||
replaying: bool,
|
||||
/// Set when a command that draws a shape was journaled outside saved steps
|
||||
/// ([`Session::take_shape_drawn`]).
|
||||
shape_drawn: bool,
|
||||
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
|
||||
tool_panic: Option<EngineError>,
|
||||
/// How many times switching or closing documents, or replacing the active one, has started the
|
||||
@@ -411,7 +414,7 @@ mod session;
|
||||
pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, OpenRows, RecalledSelection};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -403,6 +403,11 @@ pub struct Prefs {
|
||||
/// selected, the panel and the Properties panel's Transform section measure and transform it
|
||||
/// from its symbol's registration point instead of the reference point.
|
||||
pub use_registration_point_for_symbol: bool,
|
||||
/// The Transform panel menu's Show on Shape Creation: drawing a shape with the Rectangle,
|
||||
/// Rounded Rectangle, Ellipse, Polygon, Star or Line Segment tool (a drag or OK in the tool's
|
||||
/// dialog, also on the active perspective plane), a shape the Shaper tool recognizes, or running
|
||||
/// one of [`crate::DRAWS_SHAPE`], shows the Transform panel.
|
||||
pub show_on_shape_creation: bool,
|
||||
/// The tools' persistent options by store (a tool id, or a store a family shares: `liquify`
|
||||
/// holds the Liquify tools' Global Brush Dimensions), see [`vectorcraft_tools::settings`]:
|
||||
/// kept across tool switches and saved with the preferences. Not a Preferences dialog field:
|
||||
@@ -625,6 +630,7 @@ impl Default for Prefs {
|
||||
single_corner_radius: true,
|
||||
transform_panel_patterns: "default".to_string(),
|
||||
use_registration_point_for_symbol: false,
|
||||
show_on_shape_creation: false,
|
||||
tool_settings: Default::default(),
|
||||
perspective_presets: vec![],
|
||||
blend_options: None,
|
||||
|
||||
@@ -49,7 +49,8 @@ pub(crate) fn doc_sane(d: &Document, sel: &Selection) -> bool {
|
||||
&& objects_in_range(d, &sel.objects)
|
||||
}
|
||||
|
||||
fn rect_in_range(r: vectorcraft_geom::Rect) -> bool {
|
||||
/// Is every edge of `r` finite and within [`MAX_COORD`] of the origin?
|
||||
pub(crate) fn rect_in_range(r: vectorcraft_geom::Rect) -> bool {
|
||||
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
|
||||
use super::command_sets::{DRAWS_SHAPE, JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
|
||||
use super::doc_state::DocState;
|
||||
use super::error::{EngineError, Result};
|
||||
use super::history::NamedStep;
|
||||
|
||||
@@ -68,6 +68,7 @@ impl Session {
|
||||
preview_memo: Default::default(),
|
||||
depth: 0,
|
||||
replaying: false,
|
||||
shape_drawn: false,
|
||||
tool_panic: None,
|
||||
tool_resets: 0,
|
||||
tool_set_since_reset: false,
|
||||
|
||||
@@ -321,6 +321,9 @@ impl Session {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
// While the Live Paint Bucket is active, paint previews change only the bucket's colors, so
|
||||
// each preview starts from the colors the interaction began with.
|
||||
let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
|
||||
let (paint, restore_paint) = {
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
@@ -334,8 +337,10 @@ impl Session {
|
||||
st.doc = it.doc.clone();
|
||||
// A batch, or a preview that changed the new-art paints (a pattern rename), started from
|
||||
// the paints the interaction began with.
|
||||
let restore_paint =
|
||||
cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some();
|
||||
let restore_paint = bucket
|
||||
|| cmd == "command.batch"
|
||||
|| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")
|
||||
|| it.color_mode_paints.is_some();
|
||||
let paint = it.paint.clone();
|
||||
it.preview_paint = None;
|
||||
it.color_mode_paints = None;
|
||||
@@ -458,6 +463,7 @@ impl Session {
|
||||
st.last_perspective = perspective_again;
|
||||
}
|
||||
let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs());
|
||||
self.note_shape_drawn(&preview.0, &preview.1);
|
||||
self.journal.push(preview);
|
||||
self.journal_in_undo_groups(doc, &grouped, journal);
|
||||
if self.depth == 0 {
|
||||
@@ -477,10 +483,13 @@ impl Session {
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.pending_paint = None;
|
||||
// While the Live Paint Bucket is active, a previewed color is the bucket's color, which the
|
||||
// cancel puts back as well.
|
||||
let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
|
||||
if let Some(paint) = self
|
||||
.active()
|
||||
.and_then(|st| st.interaction.as_ref())
|
||||
.filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some())
|
||||
.filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some())
|
||||
.map(|it| it.paint.clone())
|
||||
{
|
||||
self.paint = paint;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user