mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 01:44:57 +01:00
Merge main into feat/find-replace-dialog
This commit is contained in:
commit
775f8c182c
605 files changed
+57726
-3965
No files matched your search
Generated
+3
@@ -6632,6 +6632,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-testkit",
|
||||
@@ -6824,6 +6825,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
"flate2",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6928,6 +6930,7 @@ name = "vectorcraft-ui-egui"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"chrono",
|
||||
"craft-keymap",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
|
||||
@@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified
|
||||
The scores are self-assessed from our code against public documentation;
|
||||
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
|
||||
|
||||
All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview.
|
||||
|
||||
**What's missing:**
|
||||
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
|
||||
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
|
||||
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
|
||||
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
|
||||
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
|
||||
- scripting, and the rest of Variables (image and graph kinds, dataset import);
|
||||
- generative AI features.
|
||||
|
||||
+5
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -125,6 +125,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
## Progress log
|
||||
|
||||
- 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.
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -132,6 +133,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
@@ -224,6 +226,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
|
||||
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
|
||||
|
||||
@@ -120,6 +120,13 @@ impl StoredArt {
|
||||
doc.number_mounted_art();
|
||||
}
|
||||
|
||||
/// Sets the art on `doc` as [`Document::mounted_art`] with the ids it is stored with, the id
|
||||
/// counter left as it is: what a save looks through, writing back only the brushes whose art it
|
||||
/// changed ([`Self::write_back`]).
|
||||
pub fn mount_as_stored(&self, doc: &mut Document) {
|
||||
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
|
||||
}
|
||||
|
||||
/// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids
|
||||
/// included) back into its library entry: the entry at its index when that entry is as it was
|
||||
/// read or reads as the brush as it was apart from its name, else the first entry that reads as
|
||||
|
||||
@@ -596,6 +596,9 @@ struct Walk<'a> {
|
||||
clips: Vec<Region>,
|
||||
/// The points those masks hold ([`MAX_MASK_POINTS`]).
|
||||
mask_points: usize,
|
||||
/// Set while the stroke pieces of a clipping path whose fill paints are drawn: they close, as
|
||||
/// its fill closes its outline.
|
||||
closing: bool,
|
||||
runs: Vec<Run>,
|
||||
points: usize,
|
||||
clip_tests: u64,
|
||||
@@ -624,6 +627,7 @@ impl<'a> Walk<'a> {
|
||||
tolerance,
|
||||
clips: vec![],
|
||||
mask_points: 0,
|
||||
closing: false,
|
||||
runs: vec![],
|
||||
points: 0,
|
||||
clip_tests: 0,
|
||||
@@ -827,7 +831,9 @@ impl<'a> Walk<'a> {
|
||||
let mut paint = first.clip_paint();
|
||||
// A stroke at 0% opacity isn't drawn, so the clipping path is drawn in its fill.
|
||||
let type_stroke = |s: &Node| matches!(&s.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.has_stroke()));
|
||||
paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s));
|
||||
// The strokes of a clipping path whose stroke effects were applied are a group of pieces,
|
||||
// which effects around it may have put in groups of their own.
|
||||
paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s) || strokes_in_pieces(s));
|
||||
if paint.stroke.is_none()
|
||||
&& let Some(fill) = &paint.fill
|
||||
{
|
||||
@@ -852,9 +858,16 @@ impl<'a> Walk<'a> {
|
||||
None => {}
|
||||
}
|
||||
// Drawn whole where its stroke paints: a fill closes its outline, and type's characters
|
||||
// without a stroke are drawn too.
|
||||
if paint.stroke.is_some() {
|
||||
self.node(first, false);
|
||||
// without a stroke are drawn too. Pieces of a clipping path whose fill and stroke effects
|
||||
// were applied are drawn in its stroke pieces alone, closed where its fill paints.
|
||||
if let Some(stroke) = &paint.stroke {
|
||||
if first.extras().clip_pieces {
|
||||
let closing = std::mem::replace(&mut self.closing, paint.fill.as_ref().is_some_and(fills_in_pieces));
|
||||
self.node(stroke, false);
|
||||
self.closing = closing;
|
||||
} else {
|
||||
self.node(first, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,7 +887,8 @@ impl<'a> Walk<'a> {
|
||||
|
||||
/// A path drawn in its color: the topmost stroke's that paints, else the topmost fill's that
|
||||
/// paints (visible, with a paint and some opacity). A filled path's every subpath is closed,
|
||||
/// as its fill closes it, also when its stroke gives the color.
|
||||
/// as its fill closes it, also when its stroke gives the color, and so is each stroke piece
|
||||
/// of a clipping path whose fill paints ([`Walk::closing`]).
|
||||
fn shape(&mut self, n: &Node, bp: &BezPath) {
|
||||
if bp.elements().is_empty() {
|
||||
return;
|
||||
@@ -896,7 +910,7 @@ impl<'a> Walk<'a> {
|
||||
(None, None) => return,
|
||||
};
|
||||
let rgb = self.flat(paint);
|
||||
self.draw(rgb, bp, fill.is_some());
|
||||
self.draw(rgb, bp, fill.is_some() || self.closing);
|
||||
}
|
||||
|
||||
/// `bp` drawn in `rgb`: flattened (with `close` every subpath closed), then cut and added.
|
||||
@@ -1146,6 +1160,18 @@ fn top_stroke(n: &Node) -> Option<&StrokeLayer> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a member of `n`, at any depth of its groups, has a stroke that paints ([`top_stroke`]),
|
||||
/// with it and the groups around it shown and not fully transparent.
|
||||
fn strokes_in_pieces(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().filter(|c| c.visible && c.opacity > 0.0).any(|c| top_stroke(c).is_some() || strokes_in_pieces(c)))
|
||||
}
|
||||
|
||||
/// Whether a member of `n`, at any depth of its groups, has a fill that paints ([`top_fill`]),
|
||||
/// with it and the groups around it shown and not fully transparent.
|
||||
fn fills_in_pieces(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().filter(|c| c.visible && c.opacity > 0.0).any(|c| top_fill(c).is_some() || fills_in_pieces(c)))
|
||||
}
|
||||
|
||||
/// The paint of the topmost fill of `n` that paints: visible, with a paint and some opacity.
|
||||
fn top_fill(n: &Node) -> Option<&Paint> {
|
||||
n.appearance.items.iter().rev().find_map(|i| match i {
|
||||
|
||||
@@ -747,6 +747,86 @@ fn a_clipping_path_is_drawn_where_it_paints() {
|
||||
});
|
||||
let t = text(&plot(&open_doc, &opts(&open_doc)));
|
||||
assert!(t.ends_with("SP2;PU282,1129;PD564,1129,564,847,282,1129;PU;SP0;"), "{t}");
|
||||
// A stroke with a geometry effect of its own is drawn once, over the art it clips, in its color.
|
||||
let moved = doc_with(|d| {
|
||||
let (blue, red) = (Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)));
|
||||
let mut clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::basic(blue, red, 1.0));
|
||||
for item in &mut clip.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item {
|
||||
let params = serde_json::json!({"moveH": 5});
|
||||
s.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
}
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
});
|
||||
assert_eq!(plot(&moved, &opts(&moved)).pens, [[0, 0, 0], [255, 0, 0]]);
|
||||
// So are the stroke's pieces when an effect around them put them in a group of their own.
|
||||
let grouped = |opacity: f32| {
|
||||
doc_with(|d| {
|
||||
// One path for each, carrying only that fill or stroke.
|
||||
let piece = |d: &mut Document, fill: bool| {
|
||||
let mut a = Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0);
|
||||
a.items.retain(|i| matches!(i, AppearanceItem::Fill(_)) == fill);
|
||||
Arc::new(Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), a))
|
||||
};
|
||||
let (fill, stroke) = (piece(d, true), piece(d, false));
|
||||
let mut copies = Node::group(d.alloc_id(), vec![stroke]);
|
||||
copies.opacity = opacity;
|
||||
let mut clip = Node::group(d.alloc_id(), vec![fill, Arc::new(copies)]);
|
||||
clip.extras_mut().clip_pieces = true;
|
||||
let black = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), black);
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
})
|
||||
};
|
||||
let shown = grouped(1.0);
|
||||
assert_eq!(plot(&shown, &opts(&shown)).pens, [[0, 0, 0], [255, 0, 0]]);
|
||||
// In a group at 0% opacity they are not drawn, and the clipping path is drawn in its fill.
|
||||
let faded = grouped(0.0);
|
||||
assert_eq!(plot(&faded, &opts(&faded)).pens, [[0, 0, 255], [0, 0, 0]]);
|
||||
// An open clipping path with a fill is drawn closed also where its stroke's effect moved it.
|
||||
let open_moved = |fill_opacity: f32| {
|
||||
doc_with(|d| {
|
||||
let mut open = BezPath::new();
|
||||
open.move_to((20.0, 20.0));
|
||||
open.line_to((40.0, 20.0));
|
||||
open.line_to((40.0, 40.0));
|
||||
let a = Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0);
|
||||
let mut clip = Node::path(d.alloc_id(), PathData::from_bezpath(&open), a);
|
||||
for item in &mut clip.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => f.opacity = fill_opacity,
|
||||
AppearanceItem::Stroke(s) => {
|
||||
let params = serde_json::json!({"moveH": 5});
|
||||
s.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
let black = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), black);
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
})
|
||||
};
|
||||
let filled = open_moved(1.0);
|
||||
let t = text(&plot(&filled, &opts(&filled)));
|
||||
assert!(t.ends_with("SP2;PU353,1129;PD635,1129,635,847,353,1129;PU;SP0;"), "{t}");
|
||||
// A fill at 0% opacity does not close it.
|
||||
let unfilled = open_moved(0.0);
|
||||
let t = text(&plot(&unfilled, &opts(&unfilled)));
|
||||
assert!(t.ends_with("SP2;PU353,1129;PD635,1129,635,847;PU;SP0;"), "{t}");
|
||||
}
|
||||
|
||||
/// A symbol `art` and an instance of it at its place.
|
||||
|
||||
+98
-2
@@ -94,6 +94,50 @@ impl Intent {
|
||||
}
|
||||
}
|
||||
|
||||
/// A color management policy (Edit → Color Settings): what opening a document does with a profile
|
||||
/// it is tagged with that is not the working space of its model.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Policy {
|
||||
/// The document loses the profile; its color numbers stay as they are.
|
||||
Off,
|
||||
/// The document keeps the profile.
|
||||
#[default]
|
||||
PreserveEmbedded,
|
||||
/// The colors are converted from the profile into the working space, which keeps their
|
||||
/// appearance, and the document loses the profile.
|
||||
Convert,
|
||||
/// CMYK only: the document loses the profile; its color numbers stay as they are.
|
||||
PreserveNumbers,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
/// The RGB policies, in menu order.
|
||||
pub const RGB: [Policy; 3] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert];
|
||||
/// The CMYK policies, in menu order.
|
||||
pub const CMYK: [Policy; 4] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers];
|
||||
/// Parse an id of [`Policy::id`].
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers].into_iter().find(|p| p.id() == s)
|
||||
}
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "off",
|
||||
Policy::PreserveEmbedded => "preserveEmbedded",
|
||||
Policy::Convert => "convert",
|
||||
Policy::PreserveNumbers => "preserveNumbers",
|
||||
}
|
||||
}
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "Off",
|
||||
Policy::PreserveEmbedded => "Preserve Embedded Profiles",
|
||||
Policy::Convert => "Convert to Working Space",
|
||||
Policy::PreserveNumbers => "Preserve Numbers",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProfileKind {
|
||||
@@ -134,11 +178,25 @@ pub struct ColorSettings {
|
||||
pub intent: Intent,
|
||||
/// Black-point compensation.
|
||||
pub bpc: bool,
|
||||
/// The color management policy for RGB profiles (one of [`Policy::RGB`]). Settings saved
|
||||
/// without one take the default.
|
||||
#[serde(default)]
|
||||
pub rgb_policy: Policy,
|
||||
/// The color management policy for CMYK profiles. Settings saved without one take the default.
|
||||
#[serde(default)]
|
||||
pub cmyk_policy: Policy,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
fn default() -> Self {
|
||||
Self { rgb: SRGB.into(), cmyk: GENERIC_CMYK.into(), intent: Intent::RelativeColorimetric, bpc: true }
|
||||
Self {
|
||||
rgb: SRGB.into(),
|
||||
cmyk: GENERIC_CMYK.into(),
|
||||
intent: Intent::RelativeColorimetric,
|
||||
bpc: true,
|
||||
rgb_policy: Policy::default(),
|
||||
cmyk_policy: Policy::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,6 +576,41 @@ impl Cms {
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
|
||||
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
|
||||
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
|
||||
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
|
||||
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
|
||||
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
|
||||
/// Lab colours stay as they are.
|
||||
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
let icc = |s: &RgbSpace| match s {
|
||||
RgbSpace::Icc(p) => Some(p.clone()),
|
||||
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
|
||||
};
|
||||
let [r, g, b] = icc(&self.rgb)
|
||||
.zip(icc(&dest.rgb))
|
||||
.and_then(|(s, d)| s.to_rgb_of(&d, &[r, g, b], intent, self.settings.bpc))
|
||||
.unwrap_or_else(|| dest.srgb_to_rgb(self.rgb_to_srgb([r, g, b])));
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
Color::Cmyk { c, m, y, k } => {
|
||||
let inks = [c, m, y, k].map(|v| v.clamp(0.0, 1.0));
|
||||
let direct = match (&self.cmyk, &dest.cmyk) {
|
||||
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
|
||||
_ => None,
|
||||
};
|
||||
let [c, m, y, k] = match direct.as_deref() {
|
||||
Some(&[c, m, y, k]) => [c, m, y, k],
|
||||
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
Color::Gray { .. } | Color::Lab { .. } => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (ΔE2000) the best CMYK reproduction of `c` is from `c` (0 for CMYK/grey colours).
|
||||
pub fn gamut_error(&self, c: &Color) -> f32 {
|
||||
match c {
|
||||
@@ -966,8 +1059,11 @@ pub fn working_settings() -> ColorSettings {
|
||||
}
|
||||
|
||||
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
|
||||
/// leaving both unchanged, if a profile is unknown).
|
||||
/// leaving both unchanged, if a profile is unknown or the RGB policy is Preserve Numbers).
|
||||
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
if !Policy::RGB.contains(&settings.rgb_policy) {
|
||||
return Err(CmsError::Unsupported(format!("the RGB policy can't be {}", settings.rgb_policy.id())));
|
||||
}
|
||||
let cms = Arc::new(Cms::new(settings)?);
|
||||
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
|
||||
install(cms);
|
||||
|
||||
@@ -34,6 +34,17 @@ type Xf = Option<Arc<TransformF32Executor>>;
|
||||
/// generation only lets the cache drop what reloads left behind.
|
||||
type DirectKey = (u64, u64, usize, bool);
|
||||
|
||||
/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear
|
||||
/// tone curves, where black-point compensation is a linear remap, and from there into the
|
||||
/// destination.
|
||||
struct SameModel {
|
||||
into: Arc<TransformF32Executor>,
|
||||
out_of: Arc<TransformF32Executor>,
|
||||
/// The source's and the destination's black as luminance in the linear space (both 0 without
|
||||
/// compensation).
|
||||
black: [f32; 2],
|
||||
}
|
||||
|
||||
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
|
||||
pub struct IccProfile {
|
||||
pub name: String,
|
||||
@@ -49,6 +60,9 @@ pub struct IccProfile {
|
||||
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
|
||||
/// and black-point compensation.
|
||||
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
|
||||
/// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as
|
||||
/// [`Self::direct`] is.
|
||||
same_model: Mutex<Vec<(DirectKey, Option<Arc<SameModel>>)>>,
|
||||
}
|
||||
|
||||
/// A transform from one profile into an RGB profile without passing through sRGB: into the
|
||||
@@ -99,6 +113,7 @@ impl IccProfile {
|
||||
to_srgb: Default::default(),
|
||||
from_srgb: Default::default(),
|
||||
direct: Mutex::new(Vec::new()),
|
||||
same_model: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -172,6 +187,21 @@ impl IccProfile {
|
||||
Some(dst.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// Device pixels `v` (RGB / CMYK / Gray, 0..1, the profile's channels a pixel, any number of
|
||||
/// pixels) → sRGB in `dst` (three values a pixel), converted with `intent` in one pass of the
|
||||
/// cached transform. `None` when `v` doesn't hold whole pixels, `dst` doesn't hold three values
|
||||
/// for each, or no transform can be built.
|
||||
pub fn to_srgb_pixels(&self, v: &[f32], dst: &mut [f32], intent: Intent) -> Option<()> {
|
||||
let n = self.channels();
|
||||
if !v.len().is_multiple_of(n) || dst.len() != v.len() / n * 3 {
|
||||
return None;
|
||||
}
|
||||
let xf = self.to_xf(intent)?;
|
||||
xf.transform(v, dst).ok()?;
|
||||
dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// sRGB → device values.
|
||||
pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option<Vec<f32>> {
|
||||
let xf = self.inverse_xf(intent)?;
|
||||
@@ -249,6 +279,69 @@ impl IccProfile {
|
||||
Some(Direct { to_linear, to_dest: Some(to_dest), black })
|
||||
}
|
||||
|
||||
/// Device values of this profile → device values of `dest`, a profile of the same model,
|
||||
/// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB
|
||||
/// keep their place. With `bpc` (and an intent other than absolute), this profile's black
|
||||
/// maps onto the destination's black (black-point compensation). `None` when `dest` is of
|
||||
/// another model or no transform can be built.
|
||||
pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<Vec<f32>> {
|
||||
if dest.kind != self.kind || v.len() != self.channels() {
|
||||
return None;
|
||||
}
|
||||
let bpc = bpc && intent != Intent::AbsoluteColorimetric;
|
||||
let generation = profiles_generation();
|
||||
let key = (dest.id, generation, intent_index(intent), bpc);
|
||||
let t = {
|
||||
let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.retain(|(k, _)| k.1 == generation);
|
||||
match cache.iter().find(|(k, _)| *k == key) {
|
||||
Some((_, t)) => t.clone(),
|
||||
None => {
|
||||
let t = self.build_same_model(dest, intent, bpc).map(Arc::new);
|
||||
cache.push((key, t.clone()));
|
||||
t
|
||||
}
|
||||
}
|
||||
}?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
t.into.transform(v, &mut lin).ok()?;
|
||||
let [from, to] = t.black;
|
||||
if from > 0.0 || to > 0.0 {
|
||||
lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from));
|
||||
}
|
||||
let lin = lin.map(|x| x.clamp(0.0, 1.0));
|
||||
let mut out = vec![0.0f32; dest.channels()];
|
||||
t.out_of.transform(&lin, &mut out).ok()?;
|
||||
Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
|
||||
}
|
||||
|
||||
fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<SameModel> {
|
||||
let mut linear = rgb_space(super::PROPHOTO_RGB)?;
|
||||
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
|
||||
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
|
||||
}
|
||||
linear.cicp = None;
|
||||
let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?;
|
||||
let black = if bpc {
|
||||
// Each profile's black: the darkest colour it reproduces, found as `build_direct`
|
||||
// finds it, as luminance in the linear space.
|
||||
let luminance = |p: &IccProfile, xf: &Arc<TransformF32Executor>| -> Option<f32> {
|
||||
let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
xf.transform(&inks, &mut lin).ok()?;
|
||||
let y = |c: &moxcms::Xyzd| c.y as f32;
|
||||
let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant);
|
||||
Some(lum.clamp(0.0, 0.5))
|
||||
};
|
||||
let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
[luminance(self, &into)?, luminance(dest, &back)?]
|
||||
} else {
|
||||
[0.0; 2]
|
||||
};
|
||||
Some(SameModel { into, out_of, black })
|
||||
}
|
||||
|
||||
/// Whether transforms can be built for this profile (checked at registration).
|
||||
pub fn usable(&self) -> bool {
|
||||
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
|
||||
|
||||
@@ -442,3 +442,39 @@ fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
let unknown = for_document(Some("no such profile"), Some(SRGB));
|
||||
assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space");
|
||||
}
|
||||
|
||||
/// The color management policies parse from their ids, Preserve Numbers is a CMYK policy only, and
|
||||
/// settings saved before the policies existed read with the default policy.
|
||||
#[test]
|
||||
fn policies_parse_and_default_in_saved_settings() {
|
||||
for p in Policy::CMYK {
|
||||
assert_eq!(Policy::parse(p.id()), Some(p));
|
||||
}
|
||||
assert_eq!(Policy::parse("bogus"), None);
|
||||
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
assert_eq!((old.rgb_policy, old.cmyk_policy), (Policy::PreserveEmbedded, Policy::PreserveEmbedded));
|
||||
let saved = serde_json::to_value(ColorSettings { cmyk_policy: Policy::PreserveNumbers, ..Default::default() }).unwrap();
|
||||
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
|
||||
}
|
||||
|
||||
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
|
||||
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
|
||||
/// Lab colors stay as they are.
|
||||
#[test]
|
||||
fn convert_into_keeps_the_appearance() {
|
||||
let wide = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
|
||||
let working = cms();
|
||||
let rgb = Color::Rgb { r: 0.25, g: 0.4, b: 0.6 };
|
||||
let moved = wide.convert_into(&working, &rgb, Intent::RelativeColorimetric);
|
||||
assert_ne!(moved, rgb, "the numbers change");
|
||||
assert!(de(wide.display_rgb(&rgb), working.display_rgb(&moved)) < 1.0, "{rgb:?} → {moved:?}");
|
||||
let ink = Color::Cmyk { c: 0.2, m: 0.4, y: 0.6, k: 0.1 };
|
||||
let moved = wide.convert_into(&working, &ink, Intent::RelativeColorimetric);
|
||||
assert!(matches!(moved, Color::Cmyk { .. }) && moved != ink, "{ink:?} → {moved:?}");
|
||||
assert!(delta_e2000(wide.lab(&ink), working.lab(&moved)) < 3.0, "{ink:?} → {moved:?}");
|
||||
for c in [Color::Gray { k: 0.3 }, Color::Lab { l: 50.0, a: 10.0, b: -20.0 }] {
|
||||
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,28 @@ fn gray_is_srgb_toned() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_pixels_convert_as_each_one_does() {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(DISPLAY_P3).unwrap()).unwrap();
|
||||
let px = [[1.0f32, 0.0, 0.0], [0.2, 0.6, 0.9], [0.5, 0.5, 0.5], [0.0, 1.0, 0.0]];
|
||||
for intent in Intent::ALL {
|
||||
let v: Vec<f32> = px.iter().flatten().copied().collect();
|
||||
let mut dst = vec![0.0; v.len()];
|
||||
p.to_srgb_pixels(&v, &mut dst, intent).unwrap();
|
||||
for (i, rgb) in px.iter().enumerate() {
|
||||
let one = p.to_srgb(rgb, intent).unwrap();
|
||||
assert!(dst[i * 3..i * 3 + 3].iter().zip(one).all(|(a, b)| (a - b).abs() < 1e-5), "{intent:?} {rgb:?}: {dst:?} vs {one:?}");
|
||||
}
|
||||
}
|
||||
// Lengths that aren't whole pixels, or a destination of another size, are refused.
|
||||
assert!(p.to_srgb_pixels(&[0.5; 4], &mut [0.0; 3], Intent::Perceptual).is_none());
|
||||
assert!(p.to_srgb_pixels(&[0.5; 3], &mut [0.0; 6], Intent::Perceptual).is_none());
|
||||
let gray = IccProfile::from_bytes(None, &icc_bytes(GRAY).unwrap()).unwrap();
|
||||
let mut dst = [0.0; 6];
|
||||
gray.to_srgb_pixels(&[0.25, 0.75], &mut dst, Intent::RelativeColorimetric).unwrap();
|
||||
assert!(dst.iter().zip([0.25, 0.25, 0.25, 0.75, 0.75, 0.75]).all(|(a, b)| (a - b).abs() < 0.01), "{dst:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_profiles_are_reproducible() {
|
||||
assert_eq!(icc::builtin_rgb_bytes(DISPLAY_P3).unwrap(), icc::builtin_rgb_bytes(DISPLAY_P3).unwrap());
|
||||
@@ -252,3 +274,55 @@ fn settings_built_before_a_reload_dont_leave_the_old_transform_to_the_new_ones()
|
||||
assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}");
|
||||
assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}");
|
||||
}
|
||||
|
||||
/// A CMYK profile converts into another CMYK profile, ink for ink, and refuses a profile
|
||||
/// of another model or inks of the wrong count.
|
||||
#[test]
|
||||
fn cmyk_profiles_convert_into_each_other_directly() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let srgb = IccProfile::from_bytes(None, &icc_bytes(SRGB).unwrap()).unwrap();
|
||||
let inks = [0.2, 0.4, 0.6, 0.1];
|
||||
let out = generic.to_same_model_of(&device, &inks, Intent::RelativeColorimetric, false).unwrap();
|
||||
assert_eq!(out.len(), 4);
|
||||
assert!(out.iter().zip(inks).any(|(a, b)| (a - b).abs() > 0.01), "{out:?}");
|
||||
assert!(generic.to_same_model_of(&srgb, &inks, Intent::RelativeColorimetric, false).is_none());
|
||||
assert!(generic.to_same_model_of(&device, &inks[..3], Intent::RelativeColorimetric, false).is_none());
|
||||
}
|
||||
|
||||
/// With black-point compensation, a CMYK profile's darkest ink converts into an ink as dark as a
|
||||
/// darker profile's darkest ink, and a dark grey of a darker profile converts lighter into a
|
||||
/// profile whose black is lighter; absolute colorimetric never compensates.
|
||||
#[test]
|
||||
fn cmyk_to_cmyk_compensates_the_black_point() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let rel = Intent::RelativeColorimetric;
|
||||
let lightness = |p: &IccProfile, inks: &[f32]| lab::srgb_to_lab(p.to_srgb(inks, rel).unwrap()).l;
|
||||
let black = |p: &IccProfile| p.from_srgb([0.0; 3], rel).unwrap();
|
||||
// Generic CMYK's black is a dark grey, the uncalibrated profile's is black.
|
||||
let (light, dark) = (lightness(&generic, &black(&generic)), lightness(&device, &black(&device)));
|
||||
assert!(light > dark + 5.0, "{light} vs {dark}");
|
||||
let into_device = |bpc| lightness(&device, &generic.to_same_model_of(&device, &black(&generic), rel, bpc).unwrap());
|
||||
let (on, off) = (into_device(true), into_device(false));
|
||||
assert!((on - dark).abs() < 1.5 && off > dark + 5.0, "with {on}, without {off}, the black {dark}");
|
||||
let grey = device.from_srgb([0.2; 3], rel).unwrap();
|
||||
let into_generic = |bpc| lightness(&generic, &device.to_same_model_of(&generic, &grey, rel, bpc).unwrap());
|
||||
let (on, off) = (into_generic(true), into_generic(false));
|
||||
assert!(on > off + 1.0, "with {on}, without {off}");
|
||||
for (from, to, inks) in [(&generic, &device, black(&generic)), (&device, &generic, grey)] {
|
||||
let abs = |bpc| from.to_same_model_of(to, &inks, Intent::AbsoluteColorimetric, bpc).unwrap();
|
||||
assert_eq!(abs(true), abs(false));
|
||||
}
|
||||
// Convert to Working Space (Cms::convert_into) compensates as Color Settings say.
|
||||
let device_name = register_icc(&icc_bytes(DEVICE_CMYK).unwrap(), Some("Test ICC Device CMYK".into())).unwrap().name;
|
||||
let rich = Color::Cmyk { c: 0.9, m: 0.8, y: 0.8, k: 1.0 };
|
||||
let convert = |bpc| {
|
||||
let dest = Cms::new(&ColorSettings { cmyk: device_name.clone(), bpc, ..ColorSettings::default() }).unwrap();
|
||||
icc_cmyk(bpc).convert_into(&dest, &rich, rel)
|
||||
};
|
||||
assert_ne!(convert(true), convert(false));
|
||||
// White is untouched.
|
||||
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
|
||||
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
|
||||
}
|
||||
+12
-8
@@ -840,15 +840,19 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the strokes of path `n` for Reverse Path Direction, before its subpaths flagged in
|
||||
/// `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its last
|
||||
/// anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and rotation
|
||||
/// then run the new way, so the stroke draws as it did. A stroke reads one profile along every
|
||||
/// subpath, so it turns only when all of them turn alike. Arrowheads stay at the path's start and
|
||||
/// end.
|
||||
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
|
||||
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
|
||||
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
|
||||
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
|
||||
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return };
|
||||
let mut turns = path.subpaths.iter().enumerate().map(|(i, sp)| {
|
||||
let subpaths: Vec<&SubPath> = match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().collect(),
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(),
|
||||
_ => return,
|
||||
};
|
||||
let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| {
|
||||
let mut o = Orient::of(sp);
|
||||
if reversed.get(i).copied().unwrap_or(false) {
|
||||
if sp.closed {
|
||||
|
||||
+802
-46
@@ -332,20 +332,24 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
|
||||
pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder<Cursor<&[u8]>>)> {
|
||||
/// The decoder of TIFF `bytes`' first image; `None` for other bytes and [`oversized_tiff`] images.
|
||||
fn tiff_decoder(bytes: &[u8]) -> Option<tiff::decoder::Decoder<Cursor<&[u8]>>> {
|
||||
if !is_tiff(bytes) || oversized_tiff(bytes).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut d = tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()?;
|
||||
tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()
|
||||
}
|
||||
|
||||
/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
|
||||
pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder<Cursor<&[u8]>>)> {
|
||||
let mut d = tiff_decoder(bytes)?;
|
||||
Some((d.colortype().ok()?, d))
|
||||
}
|
||||
|
||||
/// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images
|
||||
/// and TIFFs without one. Reads only its header.
|
||||
/// and TIFFs without one. Reads only its header, for any color type.
|
||||
pub fn tiff_orientation(bytes: &[u8]) -> Option<u16> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
tiff_decoder(bytes)?.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
@@ -363,20 +367,175 @@ pub fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
}
|
||||
|
||||
/// TIFF bytes as a reader sees them with some of them replaced: each patch is an offset and the
|
||||
/// bytes read there instead, at most four, in order of offset without overlaps. The file is not
|
||||
/// copied.
|
||||
struct Patched<'a> {
|
||||
bytes: Cursor<&'a [u8]>,
|
||||
patches: Vec<(usize, &'static [u8])>,
|
||||
}
|
||||
|
||||
impl std::io::Read for Patched<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX);
|
||||
let read = std::io::Read::read(&mut self.bytes, buf)?;
|
||||
let got = buf.get_mut(..read).unwrap_or_default();
|
||||
let end = start.saturating_add(read);
|
||||
// The patches are in order and apart, and each is at most four bytes long.
|
||||
let first = self.patches.partition_point(|&(at, _)| at.saturating_add(4) <= start);
|
||||
for &(at, with) in self.patches.get(first..).unwrap_or_default().iter().take_while(|&&(at, _)| at < end) {
|
||||
for (k, &b) in with.iter().enumerate() {
|
||||
if let Some(slot) = at.checked_add(k).and_then(|i| i.checked_sub(start)).and_then(|i| got.get_mut(i)) {
|
||||
*slot = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(read)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for Patched<'_> {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
std::io::Seek::seek(&mut self.bytes, to)
|
||||
}
|
||||
}
|
||||
|
||||
/// TIFF `bytes` read with the PhotometricInterpretation (tag 262) of their first image set to 1
|
||||
/// (black is zero) in each of its entries that holds one SHORT or LONG value. The decoder gives
|
||||
/// every sample of a grayscale image's pixels, in the order the file stores them, where it gives a
|
||||
/// CMYK image's inks and at most the first extra sample, and doesn't read a white-is-zero image
|
||||
/// with extra samples. `None` for bytes that aren't a TIFF and when the first image has no such
|
||||
/// entry.
|
||||
fn as_black_is_zero(bytes: &[u8]) -> Option<Patched<'_>> {
|
||||
let le = bytes.starts_with(b"II*\0");
|
||||
if !le && !bytes.starts_with(b"MM\0*") {
|
||||
return None;
|
||||
}
|
||||
let u16_at = |at: usize| -> Option<u16> {
|
||||
let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?;
|
||||
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
|
||||
};
|
||||
let u32_at = |at: usize| -> Option<u32> {
|
||||
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
|
||||
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
|
||||
};
|
||||
let ifd = usize::try_from(u32_at(4)?).ok()?;
|
||||
let mut patches = Vec::new();
|
||||
for i in 0..usize::from(u16_at(ifd)?) {
|
||||
let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?;
|
||||
let (Some(tag), Some(ty), Some(count)) = (u16_at(e), u16_at(e.checked_add(2)?), u32_at(e.checked_add(4)?)) else { break };
|
||||
if tag != 262 || count != 1 {
|
||||
continue;
|
||||
}
|
||||
// The value sits in the entry, in the file's byte order.
|
||||
let one: &'static [u8] = match (ty, le) {
|
||||
(3, true) => &[1, 0],
|
||||
(3, false) => &[0, 1],
|
||||
(4, true) => &[1, 0, 0, 0],
|
||||
(4, false) => &[0, 0, 0, 1],
|
||||
_ => continue,
|
||||
};
|
||||
let at = e.checked_add(8)?;
|
||||
bytes.get(at..at.checked_add(one.len())?)?;
|
||||
patches.push((at, one));
|
||||
}
|
||||
(!patches.is_empty()).then(|| Patched { bytes: Cursor::new(bytes), patches })
|
||||
}
|
||||
|
||||
/// The ExtraSamples values of the image `d` reads, one for each sample after its color, in order:
|
||||
/// 0 not alpha, 1 associated alpha, 2 unassociated alpha. Empty without the tag.
|
||||
fn extra_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Vec<u16> {
|
||||
d.find_tag_unsigned_vec::<u16>(tiff::tags::Tag::ExtraSamples).ok().flatten().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Does `kind`, the color type of the TIFF `d` reads, hold inks that Open and Place keep: CMYK of 8
|
||||
/// or 16 bits, with no extra sample that the file names as alpha? The decoder gives a CMYK color
|
||||
/// type to a file whose alpha follows another extra sample. [`ImageBlob::cmyk`] reads the inks of
|
||||
/// such a file all the same: a document saved with one as a CMYK image keeps it.
|
||||
fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
matches!(kind, tiff::ColorType::CMYK(8 | 16)) && !extra_samples(d).iter().any(|e| matches!(e, 1 | 2))
|
||||
}
|
||||
|
||||
/// Most samples a pixel of a TIFF is read with, its color and extra samples included, as the
|
||||
/// file's SamplesPerPixel counts them: VectorCraft's own limit.
|
||||
const MAX_EXTRA_SAMPLES_PIXEL: usize = 64;
|
||||
|
||||
/// The bytes of the row the decoder of the TIFF `d` reads takes before it reads each strip or tile
|
||||
/// of a file that stores a pixel's samples together and has more of them (its SamplesPerPixel)
|
||||
/// than the decoder gives: one row of the strip or tile, every sample of each pixel. 0 for other
|
||||
/// files. `None` when the file has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, when its
|
||||
/// samples aren't unsigned integers (a SampleFormat other than 1, which the readers don't take, and
|
||||
/// which the floating-point predictor needs) and when its color type isn't read. Reads only the
|
||||
/// file's tags.
|
||||
fn row_buffer<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>) -> Option<u64> {
|
||||
use tiff::tags::Tag;
|
||||
let kind = d.colortype().ok()?;
|
||||
let all = d.find_tag_unsigned::<u16>(Tag::SamplesPerPixel).ok()?.unwrap_or(1);
|
||||
if usize::from(all) > MAX_EXTRA_SAMPLES_PIXEL {
|
||||
return None;
|
||||
}
|
||||
if d.find_tag_unsigned_vec::<u16>(Tag::SampleFormat).ok()?.is_some_and(|f| f.iter().any(|&f| f != 1)) {
|
||||
return None;
|
||||
}
|
||||
if all <= kind.num_samples() || planar(d) {
|
||||
return Some(0);
|
||||
}
|
||||
// A strip is as wide as the image, a tile as its TileWidth.
|
||||
let width = match d.get_chunk_type() {
|
||||
tiff::decoder::ChunkType::Tile => d.find_tag_unsigned::<u32>(Tag::TileWidth).ok()??,
|
||||
tiff::decoder::ChunkType::Strip => d.dimensions().ok()?.0,
|
||||
};
|
||||
u64::from(width).checked_mul(u64::from(all))?.checked_mul(u64::from(kind.bit_depth().div_ceil(8)))
|
||||
}
|
||||
|
||||
/// `d`, the decoder of a TIFF of `file` bytes, set to decode `n` pixels of `per` samples of `bits`
|
||||
/// bits each into RGBA. `None` when the file has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a
|
||||
/// pixel, when its samples aren't unsigned integers (a SampleFormat other than 1), and when the
|
||||
/// decoded samples, the copy that puts a planar file's samples pixel by pixel, the row the decoder
|
||||
/// reads each strip or tile into ([`row_buffer`]) and the RGBA pixels together take more than
|
||||
/// [`crate::MAX_RASTER_ALLOC`]. The decoder may then decode no more than those samples, and read no
|
||||
/// strip or tile of more compressed bytes than the file holds (nor more than its own limit of
|
||||
/// 128 MiB).
|
||||
fn with_room<R: std::io::Read + std::io::Seek>(
|
||||
mut d: tiff::decoder::Decoder<R>,
|
||||
file: usize,
|
||||
n: usize,
|
||||
per: usize,
|
||||
bits: u8,
|
||||
) -> Option<tiff::decoder::Decoder<R>> {
|
||||
if per > MAX_EXTRA_SAMPLES_PIXEL {
|
||||
return None;
|
||||
}
|
||||
let row = row_buffer(&mut d)?;
|
||||
let need = n.checked_mul(per)?.checked_mul(usize::from(bits.div_ceil(8)))?;
|
||||
let copies = if per > 1 && planar(&mut d) { 2 } else { 1 };
|
||||
let peak = u64::try_from(need).ok()?.checked_mul(copies)?.checked_add(u64::try_from(n).ok()?.checked_mul(4)?)?.checked_add(row)?;
|
||||
if peak > crate::MAX_RASTER_ALLOC {
|
||||
return None;
|
||||
}
|
||||
let mut limits = tiff::decoder::Limits::default();
|
||||
limits.decoding_buffer_size = need;
|
||||
limits.intermediate_buffer_size = limits.intermediate_buffer_size.min(file);
|
||||
Some(d.with_limits(limits))
|
||||
}
|
||||
|
||||
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
|
||||
fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
fn planar<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
|
||||
}
|
||||
|
||||
/// The samples of the `n` pixels of the TIFF `d` reads, `per` to a pixel (the number its color
|
||||
/// type has), pixel by pixel and 8 bits each (16-bit samples to their high byte), whether the file
|
||||
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
|
||||
/// type has), pixel by pixel and 8 bits each (16-bit samples rounded to the nearest), whether the
|
||||
/// file stores each pixel's samples together or one plane per channel. `None` when they don't decode to
|
||||
/// that many samples, which includes images whose planes together need more than the decoder's
|
||||
/// limit (256 MB of samples).
|
||||
/// limit (256 MiB of samples), and, before any decoding, files with more than
|
||||
/// [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, files whose samples aren't unsigned integers (a
|
||||
/// SampleFormat other than 1) and ones whose samples with the row the decoder reads each strip or
|
||||
/// tile into ([`row_buffer`]) take more than [`crate::MAX_RASTER_ALLOC`].
|
||||
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
Some(match read_samples_at_depth(d, n, per)? {
|
||||
Samples::Eight(v) => v,
|
||||
Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
Samples::Sixteen(v) => v.iter().map(|&s| u8::try_from((u32::from(s) + 128) / 257).unwrap_or(u8::MAX)).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -404,7 +563,20 @@ enum SampleSlice<'a> {
|
||||
}
|
||||
|
||||
/// [`read_samples`], keeping 16-bit samples at 16 bits.
|
||||
fn read_samples_at_depth(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Samples> {
|
||||
fn read_samples_at_depth<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>, n: usize, per: usize) -> Option<Samples> {
|
||||
// Checked from the tags, before anything is decoded.
|
||||
let row = row_buffer(d)?;
|
||||
let bytes = u64::from(d.colortype().ok()?.bit_depth().div_ceil(8));
|
||||
let need = u64::try_from(n).ok()?.checked_mul(u64::try_from(per).ok()?)?.checked_mul(bytes)?;
|
||||
if need.checked_add(row)? > crate::MAX_RASTER_ALLOC {
|
||||
return None;
|
||||
}
|
||||
decode_samples(d, n, per)
|
||||
}
|
||||
|
||||
/// [`read_samples_at_depth`] without its checks, for a decoder that [`with_room`] made. Its tags
|
||||
/// can't be read once its limits are set: the decoder holds a tag's values to its decoding limit.
|
||||
fn decode_samples<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>, n: usize, per: usize) -> Option<Samples> {
|
||||
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
|
||||
let layout = d.read_image_to_buffer(&mut buf).ok()?;
|
||||
match buf {
|
||||
@@ -415,7 +587,8 @@ fn read_samples_at_depth(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize
|
||||
}
|
||||
|
||||
/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples
|
||||
/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample.
|
||||
/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. The copy
|
||||
/// of a planar file's samples is allocated once, at its length.
|
||||
fn chunky<T: Copy>(data: Vec<T>, planes: usize, n: usize, per: usize) -> Option<Vec<T>> {
|
||||
if Some(data.len()) != n.checked_mul(per) {
|
||||
return None;
|
||||
@@ -427,7 +600,13 @@ fn chunky<T: Copy>(data: Vec<T>, planes: usize, n: usize, per: usize) -> Option<
|
||||
return None;
|
||||
}
|
||||
let planes: Vec<&[T]> = data.chunks_exact(n).collect();
|
||||
Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect())
|
||||
let mut out = Vec::with_capacity(data.len());
|
||||
for i in 0..n {
|
||||
for p in &planes {
|
||||
out.push(*p.get(i)?);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or
|
||||
@@ -439,13 +618,25 @@ pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> {
|
||||
icc.get(16..20)?.try_into().ok()
|
||||
}
|
||||
|
||||
/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one.
|
||||
/// The most bytes of an ICC profile a TIFF's tag 34675 is read with (16 MiB).
|
||||
const MAX_TIFF_ICC: u64 = 16 << 20;
|
||||
|
||||
/// The ICC profile of TIFF tag 34675 (ICCProfile, of type UNDEFINED or BYTE) of the image `d`
|
||||
/// reads, as its bytes; `None` without one and for one over [`MAX_TIFF_ICC`] bytes.
|
||||
fn tiff_icc(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Option<Vec<u8>> {
|
||||
d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty())
|
||||
use tiff::tags::{Tag, Type, ValueBuffer};
|
||||
let mut ifd = d.image_ifd();
|
||||
let entry = ifd.find_entry(Tag::IccProfile)?;
|
||||
if !matches!(entry.field_type(), Type::UNDEFINED | Type::BYTE) || entry.count() == 0 || entry.count() > MAX_TIFF_ICC {
|
||||
return None;
|
||||
}
|
||||
let mut buf = ValueBuffer::empty(Type::UNDEFINED);
|
||||
ifd.find_tag_buf(Tag::IccProfile, &mut buf).ok()??;
|
||||
Some(buf.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own
|
||||
/// limits, whatever the size of the image; `None` for other images and TIFFs without one.
|
||||
/// The ICC profile of TIFF `bytes`' first image (tag 34675), up to [`MAX_TIFF_ICC`] bytes whatever
|
||||
/// the size of the image; `None` for other images, TIFFs without one and a longer one.
|
||||
pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
tiff_icc(&mut d)
|
||||
@@ -459,6 +650,75 @@ fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
d.icc_profile().filter(|icc| !icc.is_empty())
|
||||
}
|
||||
|
||||
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
|
||||
/// the count of segments.
|
||||
const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
|
||||
|
||||
/// JPEG `bytes` carrying `icc` in place of the ICC profile they carry, if any: every
|
||||
/// `ICC_PROFILE` APP2 segment before the scan taken out, `icc` written as numbered APP2 segments
|
||||
/// after the leading application segments, and the other segments and the scan as they are. `None`
|
||||
/// for bytes whose segments before the scan can't be read, an empty `icc`, and one longer than 255
|
||||
/// segments hold.
|
||||
pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
// A segment's length counts itself (2 bytes) and the name, number and count (14).
|
||||
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
|
||||
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
|
||||
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
|
||||
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
|
||||
segments.extend_from_slice(&[0xFF, 0xE2]);
|
||||
segments.extend_from_slice(&len.to_be_bytes());
|
||||
segments.extend_from_slice(ICC_SEGMENT);
|
||||
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
|
||||
segments.extend_from_slice(chunk);
|
||||
}
|
||||
with_icc_segments(bytes, segments)
|
||||
}
|
||||
|
||||
/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the
|
||||
/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose
|
||||
/// segments before the scan can't be read.
|
||||
pub fn jpeg_without_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
with_icc_segments(bytes, vec![])
|
||||
}
|
||||
|
||||
/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments`
|
||||
/// written after the leading application segments; `None` when the bytes don't start a JPEG or
|
||||
/// their segments before the scan can't be read.
|
||||
fn with_icc_segments(bytes: &[u8], segments: Vec<u8>) -> Option<Vec<u8>> {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() + segments.len());
|
||||
out.extend_from_slice(&[0xFF, 0xD8]);
|
||||
let mut icc_segments = Some(segments);
|
||||
let mut at = 2;
|
||||
// The segments before the scan (SOS), each with its length; a marker without one ends them.
|
||||
// Fill bytes (0xFF) before a marker are left out.
|
||||
loop {
|
||||
while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) {
|
||||
at += 1;
|
||||
}
|
||||
let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None };
|
||||
let app = (0xE0..=0xEF).contains(&marker);
|
||||
if !app && let Some(s) = icc_segments.take() {
|
||||
out.extend_from_slice(&s);
|
||||
}
|
||||
if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) {
|
||||
break;
|
||||
}
|
||||
let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?));
|
||||
let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?;
|
||||
if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) {
|
||||
out.extend_from_slice(segment);
|
||||
}
|
||||
at += segment.len();
|
||||
}
|
||||
out.extend_from_slice(bytes.get(at..)?);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
|
||||
fn cmyk_icc(icc: Option<Vec<u8>>) -> Option<Vec<u8>> {
|
||||
icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"))
|
||||
@@ -473,10 +733,14 @@ struct CmykSource {
|
||||
}
|
||||
|
||||
/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with
|
||||
/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`].
|
||||
/// the TIFF's CMYK ICC profile; `None` for other images, CMYK ones with alpha, ones larger than
|
||||
/// [`MAX_CMYK_PIXELS`], and, before any decoding, ones with more than [`MAX_EXTRA_SAMPLES_PIXEL`]
|
||||
/// samples a pixel (their SamplesPerPixel), ones whose samples aren't unsigned integers (a
|
||||
/// SampleFormat other than 1) and ones whose samples with the row the decoder reads each strip or
|
||||
/// tile into ([`row_buffer`]) take more than [`crate::MAX_RASTER_ALLOC`].
|
||||
fn tiff_source(bytes: &[u8]) -> Option<CmykSource> {
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) {
|
||||
if !cmyk_inks(kind, &mut d) {
|
||||
return None;
|
||||
}
|
||||
let (width, height) = d.dimensions().ok()?;
|
||||
@@ -563,6 +827,14 @@ impl ImageBlob {
|
||||
Some(Self::new("image/tiff", tiff))
|
||||
}
|
||||
|
||||
/// [`ImageBlob::cmyk_tiff`], carrying `icc` as tag 34675 (ICCProfile) when it is a profile of
|
||||
/// CMYK colors; any other profile is left out. The caller checks the rest of the profile.
|
||||
pub fn cmyk_tiff_with_icc(inks: &Inks, icc: Option<&[u8]>) -> Option<Self> {
|
||||
let icc = icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"));
|
||||
let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), None, icc)?;
|
||||
Some(Self::new("image/tiff", tiff))
|
||||
}
|
||||
|
||||
/// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its
|
||||
/// header.
|
||||
pub fn is_cmyk(&self) -> bool {
|
||||
@@ -687,7 +959,10 @@ fn jpeg_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
}
|
||||
|
||||
/// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane
|
||||
/// per ink.
|
||||
/// per ink. `None` for other images, ones larger than [`MAX_CMYK_PIXELS`], and the files
|
||||
/// [`read_samples`] refuses: more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, samples that
|
||||
/// aren't unsigned integers, or samples that with the decoder's row take more than
|
||||
/// [`crate::MAX_RASTER_ALLOC`].
|
||||
fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
let (w, h) = d.dimensions().ok()?;
|
||||
@@ -701,8 +976,8 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
|
||||
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
|
||||
/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits
|
||||
/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs
|
||||
/// whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
/// the file has, carrying the file's CMYK ICC profile. `None` for other images, for CMYK TIFFs
|
||||
/// with an extra sample named as alpha and for ones whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
|
||||
let source = tiff_source(bytes)?;
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
@@ -716,7 +991,8 @@ pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>
|
||||
/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels,
|
||||
/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep
|
||||
/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other
|
||||
/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
/// images, for CMYK TIFFs with an extra sample named as alpha and for CMYK images whose inks
|
||||
/// [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec<u8>, (u32, u32))> {
|
||||
let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?;
|
||||
// Four inks to a pixel, turned as four channels of the same depth are.
|
||||
@@ -735,31 +1011,58 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi:
|
||||
}
|
||||
|
||||
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
|
||||
/// all, as RGBA pixels: CMYK with an alpha channel (5 samples), each colour converted by `rgb` (ink
|
||||
/// amounts 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB),
|
||||
/// and grayscale with extra samples, of which the first is the alpha when the file says so (other
|
||||
/// channels are left out). Associated (premultiplied) alpha is divided back out, and a pixel with
|
||||
/// no associated alpha has no color. 16-bit samples are converted at 16 bits, and only the result
|
||||
/// is rounded to 8 bits. The samples may be stored together or one plane per channel. `None` for
|
||||
/// other images and ones larger than [`MAX_CMYK_PIXELS`].
|
||||
/// all, as RGBA pixels: CMYK with an alpha channel, each color converted by `rgb` (ink amounts
|
||||
/// 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB), and
|
||||
/// grayscale with extra samples. The alpha is the first extra sample whose ExtraSamples value
|
||||
/// names it (1 or 2), whatever extra samples come before it; the other extra samples are left out,
|
||||
/// and without such a value the pixels are opaque. A CMYK file with a fifth sample and no
|
||||
/// ExtraSamples tag has that sample as unassociated alpha. Associated (premultiplied) alpha is
|
||||
/// divided back out, and a pixel with no associated alpha has no color. 16-bit samples are
|
||||
/// converted at 16 bits, and only the result is rounded to 8 bits. The samples may be stored
|
||||
/// together or one plane per channel. A CMYK file with two or more samples past its inks and its
|
||||
/// ExtraSamples values (or with no ExtraSamples tag) is read too, opaque when none of those values
|
||||
/// names an alpha. `None` for other images, CMYK ones without alpha (their inks are read by
|
||||
/// [`ImageBlob::cmyk`]), ones larger than [`MAX_CMYK_PIXELS`], ones whose SamplesPerPixel is more
|
||||
/// than [`MAX_EXTRA_SAMPLES_PIXEL`], ones whose samples aren't unsigned integers (a SampleFormat
|
||||
/// other than 1) and ones whose samples, with the copy a planar file needs, the row the decoder
|
||||
/// reads each strip or tile into and the RGBA pixels, take more than [`crate::MAX_RASTER_ALLOC`];
|
||||
/// those are refused from the file's tags, before any decoding.
|
||||
pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option<image::RgbaImage> {
|
||||
use tiff::tags::Tag;
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
let mut d = tiff_decoder(bytes)?;
|
||||
// The decoder gives no color type to a CMYK file that has six or more samples besides the
|
||||
// ones its ExtraSamples values count.
|
||||
let kind = d.colortype().ok();
|
||||
let (w, h) = d.dimensions().ok()?;
|
||||
// 0: white is zero, 1: black is zero (the two grayscales).
|
||||
// 0: white is zero, 1: black is zero (the two grayscales), 5: CMYK.
|
||||
let photometric = d.find_tag_unsigned::<u16>(Tag::PhotometricInterpretation).ok().flatten();
|
||||
// ExtraSamples 1: associated alpha (premultiplied colour), 2: unassociated alpha, 0: not alpha.
|
||||
let extra = d.find_tag_unsigned_vec::<u16>(Tag::ExtraSamples).ok().flatten().and_then(|v| v.first().copied());
|
||||
// (samples in a pixel, how many of them are its colour, is the next one alpha?)
|
||||
let (samples, colour, alpha) = match kind {
|
||||
tiff::ColorType::CMYKA(8 | 16) => (5, 4, true),
|
||||
tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: n @ 2.. } if matches!(photometric, Some(0 | 1)) => {
|
||||
(usize::from(n), 1, matches!(extra, Some(1 | 2)))
|
||||
}
|
||||
let extras = extra_samples(&mut d);
|
||||
// The first extra sample named as alpha: (its place among the extra samples, is it associated?)
|
||||
let named = extras.iter().position(|e| matches!(e, 1 | 2)).map(|i| (i, extras.get(i) == Some(&1)));
|
||||
// The samples of a pixel that no ExtraSamples value counts.
|
||||
let uncounted = d.find_tag_unsigned::<u16>(Tag::SamplesPerPixel).ok().flatten().and_then(|all| usize::from(all).checked_sub(extras.len()));
|
||||
// (how many of a pixel's samples are its color, the alpha among the extra samples)
|
||||
let (colour, alpha) = match kind {
|
||||
Some(tiff::ColorType::CMYKA(8 | 16)) => (4, if extras.is_empty() { Some((0, false)) } else { named }),
|
||||
Some(tiff::ColorType::CMYK(8 | 16)) if named.is_some() => (4, named),
|
||||
Some(tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: 2.. }) if matches!(photometric, Some(0 | 1)) => (1, named),
|
||||
None if photometric == Some(5) && uncounted.is_some_and(|c| c > 5) => (4, named),
|
||||
_ => return None,
|
||||
};
|
||||
let n = usize::try_from(pixels(w, h)?).ok()?;
|
||||
let data = read_samples_at_depth(&mut d, n, samples)?;
|
||||
// The decoder gives a CMYK pixel its inks and at most one extra sample, and doesn't read
|
||||
// white-is-zero gray with extra samples: those are read as black-is-zero gray, every sample.
|
||||
let given = kind.map_or(0, |k| usize::from(k.num_samples()));
|
||||
let (data, samples) = if photometric == Some(0) || kind.is_none() || alpha.is_some_and(|(i, _)| colour + i >= given) {
|
||||
let mut d = tiff::decoder::Decoder::new(as_black_is_zero(bytes)?).ok()?;
|
||||
let tiff::ColorType::Multiband { bit_depth: bits @ (8 | 16), num_samples } = d.colortype().ok()? else { return None };
|
||||
let samples = usize::from(num_samples);
|
||||
(decode_samples(&mut with_room(d, bytes.len(), n, samples, bits)?, n, samples)?, samples)
|
||||
} else {
|
||||
(decode_samples(&mut with_room(d, bytes.len(), n, given, kind?.bit_depth())?, n, given)?, given)
|
||||
};
|
||||
// (the alpha's sample in a pixel, is it associated?), when the pixel has that sample.
|
||||
let alpha = alpha.map(|(i, associated)| (colour + i, associated)).filter(|(at, _)| *at < samples);
|
||||
// Sample `i` of the image, 0..1.
|
||||
let level_at = |i: usize| match &data {
|
||||
Samples::Eight(v) => v.get(i).map(|&s| f32::from(s) / 255.0),
|
||||
@@ -772,13 +1075,16 @@ pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3])
|
||||
};
|
||||
let mut out = Vec::with_capacity(n.checked_mul(4)?);
|
||||
for first in (0..n).map(|p| p * samples) {
|
||||
let (opacity, a) = if alpha { (byte_at(first + colour).unwrap_or(u8::MAX), level_at(first + colour).unwrap_or(1.0)) } else { (u8::MAX, 1.0) };
|
||||
let (opacity, a) = match alpha {
|
||||
Some((at, _)) => (byte_at(first + at).unwrap_or(u8::MAX), level_at(first + at).unwrap_or(1.0)),
|
||||
None => (u8::MAX, 1.0),
|
||||
};
|
||||
let level = |s: usize| {
|
||||
let v = level_at(first + s).unwrap_or(0.0);
|
||||
match extra {
|
||||
Some(1) if a > 0.0 => (v / a).min(1.0),
|
||||
match alpha {
|
||||
Some((_, true)) if a > 0.0 => (v / a).min(1.0),
|
||||
// No associated alpha: the color is zero (TIFF 6.0, Associated Alpha Handling).
|
||||
Some(1) if alpha => 0.0,
|
||||
Some((_, true)) => 0.0,
|
||||
_ => v,
|
||||
}
|
||||
};
|
||||
@@ -1083,6 +1389,380 @@ mod tests {
|
||||
assert_eq!(gray.into_raw(), [0, 0, 0, 0], "a gray of zero");
|
||||
}
|
||||
|
||||
/// A pixel type of `$n` samples of `$inner`, `$bits` bits each, in color space `$space`.
|
||||
macro_rules! samples {
|
||||
($name:ident, $inner:ty, $space:ident, $bits:literal, $n:literal) => {
|
||||
struct $name;
|
||||
impl tiff::encoder::colortype::ColorType for $name {
|
||||
type Inner = $inner;
|
||||
const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::$space;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[$bits; $n];
|
||||
const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; $n];
|
||||
fn horizontal_predict(row: &[$inner], result: &mut Vec<$inner>) {
|
||||
result.extend_from_slice(row);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
samples!(Cmyk6x8, u8, CMYK, 8, 6);
|
||||
samples!(Cmyk6x16, u16, CMYK, 16, 6);
|
||||
samples!(Cmyk7x8, u8, CMYK, 8, 7);
|
||||
samples!(Cmyk8x8, u8, CMYK, 8, 8);
|
||||
samples!(Gray3x8, u8, BlackIsZero, 8, 3);
|
||||
samples!(WhiteGray2x8, u8, WhiteIsZero, 8, 2);
|
||||
|
||||
/// A one-row TIFF of `C`'s pixels `data`, with the ExtraSamples values `extra`.
|
||||
fn extras_tiff<C: tiff::encoder::colortype::ColorType>(extra: &[u16], data: &[C::Inner]) -> Vec<u8>
|
||||
where
|
||||
[C::Inner]: tiff::encoder::TiffValue,
|
||||
{
|
||||
let samples = C::BITS_PER_SAMPLE.len();
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap();
|
||||
let mut img = enc.new_image::<C>(u32::try_from(data.len() / samples).unwrap(), 1).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, extra).unwrap();
|
||||
img.write_data(data).unwrap();
|
||||
file.into_inner()
|
||||
}
|
||||
|
||||
/// Two pixels of four inks with an alpha sample and another extra sample, the alpha first when
|
||||
/// `alpha_first`: cyan at an alpha of 128 (or premultiplied, at 128 of cyan when `associated`)
|
||||
/// with an extra sample of 9, then black, opaque, with an extra sample of 64.
|
||||
fn inks_alpha_and_extra(alpha_first: bool, associated: bool) -> Vec<u16> {
|
||||
let cyan = if associated { 128 } else { 255 };
|
||||
let px = |inks: [u16; 4], alpha: u16, other: u16| {
|
||||
let extras = if alpha_first { [alpha, other] } else { [other, alpha] };
|
||||
[&inks[..], &extras[..]].concat()
|
||||
};
|
||||
[px([cyan, 0, 0, 0], 128, 9), px([0, 0, 0, 255], 255, 64)].concat()
|
||||
}
|
||||
|
||||
/// A CMYK TIFF whose pixels have alpha and another extra sample reads the sample its
|
||||
/// ExtraSamples names as alpha, first or second, at 8 and 16 bits, and leaves the other out.
|
||||
/// Open and Place don't keep its inks. A blob that holds the file, as a document saved with it
|
||||
/// as a CMYK image does, is a CMYK image with those inks when the alpha is the second extra
|
||||
/// sample.
|
||||
#[test]
|
||||
fn a_cmyk_tiff_with_alpha_and_another_extra_sample_reads_its_alpha() {
|
||||
let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)];
|
||||
for extra in [[1, 0], [2, 0], [0, 1], [0, 2]] {
|
||||
let data = inks_alpha_and_extra(extra[0] != 0, extra.contains(&1));
|
||||
let eight: Vec<u8> = data.iter().map(|&v| u8::try_from(v).unwrap()).collect();
|
||||
let sixteen: Vec<u16> = data.iter().map(|&v| v * 257).collect();
|
||||
for (bits, bytes) in [(8, extras_tiff::<Cmyk6x8>(&extra, &eight)), (16, extras_tiff::<Cmyk6x16>(&extra, &sixteen))] {
|
||||
let px = extra_samples_tiff_rgba(&bytes, naive).unwrap_or_else(|| panic!("{extra:?}, {bits} bits: reads"));
|
||||
assert_eq!(px.into_raw(), [0, 255, 255, 128, 0, 0, 0, 255], "{extra:?}, {bits} bits: cyan at half alpha, then black");
|
||||
assert!(stored_cmyk_tiff(&bytes, None).is_none(), "{extra:?}, {bits} bits: the inks can't be kept with the alpha");
|
||||
let b = ImageBlob::new("image/tiff", bytes);
|
||||
if extra[0] != 0 {
|
||||
// The decoder gives these the color type of CMYK with alpha.
|
||||
assert!(!b.is_cmyk() && b.cmyk().is_none(), "{extra:?}, {bits} bits: never stored as inks");
|
||||
continue;
|
||||
}
|
||||
assert!(b.is_cmyk(), "{extra:?}, {bits} bits: a stored one stays a CMYK image");
|
||||
assert_eq!(b.is_cmyk16(), bits == 16, "{extra:?}, {bits} bits");
|
||||
let cyan = u8::try_from(data[0]).unwrap();
|
||||
assert_eq!(b.cmyk().map(|i| i.data), Some(vec![cyan, 0, 0, 0, 0, 0, 0, 255]), "{extra:?}, {bits} bits: a stored one keeps its inks");
|
||||
}
|
||||
}
|
||||
// Two extra samples, neither of them alpha: the inks are kept, as with one.
|
||||
let bytes = extras_tiff::<Cmyk6x8>(&[0, 0], &[255, 0, 0, 0, 9, 128, 0, 0, 0, 255, 64, 255]);
|
||||
assert!(extra_samples_tiff_rgba(&bytes, naive).is_none(), "not alpha: not this reader's");
|
||||
assert!(stored_cmyk_tiff(&bytes, None).is_some());
|
||||
let b = ImageBlob::new("image/tiff", bytes);
|
||||
assert!(b.is_cmyk() && !b.is_cmyk16());
|
||||
assert_eq!(b.cmyk().map(|i| i.data), Some(vec![255, 0, 0, 0, 0, 0, 0, 255]));
|
||||
}
|
||||
|
||||
/// A CMYK TIFF of six samples a pixel whose ExtraSamples has only one value: the sample after
|
||||
/// the inks is alpha only when that value says so, and the sample after it is never alpha. Files
|
||||
/// with more samples than the decoder gives a color type read the same way, opaque when no
|
||||
/// value names an alpha.
|
||||
#[test]
|
||||
fn a_cmyk_tiff_with_fewer_extra_sample_values_than_samples_reads_only_a_named_alpha() {
|
||||
let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)];
|
||||
let data = [255, 0, 0, 0, 128, 9, 0, 0, 0, 255, 255, 64];
|
||||
let read = |extra: u16| extra_samples_tiff_rgba(&extras_tiff::<Cmyk6x8>(&[extra], &data), naive).expect("reads").into_raw();
|
||||
assert_eq!(read(2), [0, 255, 255, 128, 0, 0, 0, 255], "the sample after the inks is the alpha");
|
||||
assert_eq!(read(0), [0, 255, 255, 255, 0, 0, 0, 255], "not alpha: opaque");
|
||||
// Eight samples with two values: the decoder gives the file no color type. The second
|
||||
// value names the sixth sample as the alpha.
|
||||
let wide = [255, 0, 0, 0, 9, 128, 17, 18];
|
||||
let px = extra_samples_tiff_rgba(&extras_tiff::<Cmyk8x8>(&[0, 2], &wide), naive).expect("reads");
|
||||
assert_eq!(px.into_raw(), [0, 255, 255, 128], "cyan at the alpha the second value names");
|
||||
let px = extra_samples_tiff_rgba(&extras_tiff::<Cmyk8x8>(&[0, 0], &wide), naive).expect("no value names an alpha: reads");
|
||||
assert_eq!(px.into_raw(), [0, 255, 255, 255], "no value names an alpha: opaque cyan");
|
||||
// Six samples and no ExtraSamples tag: the decoder gives the file no color type either.
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap();
|
||||
enc.write_image::<Cmyk6x8>(1, 1, &wide[..6]).unwrap();
|
||||
let px = extra_samples_tiff_rgba(&file.into_inner(), naive).expect("no ExtraSamples tag: reads");
|
||||
assert_eq!(px.into_raw(), [0, 255, 255, 255], "no ExtraSamples tag: opaque cyan");
|
||||
// Seven samples with two values: the decoder reads it as CMYK with alpha.
|
||||
let px = extra_samples_tiff_rgba(&extras_tiff::<Cmyk7x8>(&[0, 2], &wide[..7]), naive).expect("reads");
|
||||
assert_eq!(px.into_raw(), [0, 255, 255, 128], "seven samples: cyan at the alpha the second value names");
|
||||
// Its Orientation tag is read too.
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap();
|
||||
let mut img = enc.new_image::<Cmyk8x8>(1, 1).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[0u16, 2][..]).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::Orientation, 6u16).unwrap();
|
||||
img.write_data(&wide).unwrap();
|
||||
let turned = file.into_inner();
|
||||
assert_eq!(tiff_orientation(&turned), Some(6));
|
||||
assert_eq!(exif_orientation(&turned), Some(image::metadata::Orientation::Rotate90));
|
||||
}
|
||||
|
||||
/// A white-is-zero grayscale TIFF `width` pixels wide and `rows` tall (2 or more), each pixel
|
||||
/// `samples` samples of 8 bits: a level of 0, an unassociated alpha of 128, then zeros. Each
|
||||
/// row is a strip, and every strip is the same bytes of the file.
|
||||
fn tall_gray_tiff(width: u32, rows: u32, samples: u16) -> Vec<u8> {
|
||||
gray_tiff(width, rows, samples, false)
|
||||
}
|
||||
|
||||
/// [`tall_gray_tiff`], or with `planar` one plane per sample, each row of each plane a strip
|
||||
/// of zeros, every strip the same bytes of the file.
|
||||
fn gray_tiff(width: u32, rows: u32, samples: u16, planar: bool) -> Vec<u8> {
|
||||
let at = |f: &Vec<u8>| u32::try_from(f.len()).unwrap();
|
||||
let mut f = b"II*\0\0\0\0\0".to_vec();
|
||||
let row = at(&f);
|
||||
if planar {
|
||||
f.resize(f.len() + usize::try_from(width).unwrap(), 0);
|
||||
} else {
|
||||
for _ in 0..width {
|
||||
f.extend([0, 128]);
|
||||
f.resize(f.len() + usize::from(samples) - 2, 0);
|
||||
}
|
||||
}
|
||||
let (strips, strip) = if planar { (rows * u32::from(samples), width) } else { (rows, width * u32::from(samples)) };
|
||||
let offsets = at(&f);
|
||||
f.extend((0..strips).flat_map(|_| row.to_le_bytes()));
|
||||
let counts = at(&f);
|
||||
f.extend((0..strips).flat_map(|_| strip.to_le_bytes()));
|
||||
let ifd = at(&f);
|
||||
f[4..8].copy_from_slice(&ifd.to_le_bytes());
|
||||
// (tag, type (3 SHORT, 4 LONG), count, value or offset)
|
||||
let entries = [
|
||||
(256u16, 4u16, 1, width),
|
||||
(257, 4, 1, rows),
|
||||
(258, 3, 1, 8),
|
||||
(259, 3, 1, 1),
|
||||
(262, 3, 1, 0),
|
||||
(273, 4, strips, offsets),
|
||||
(277, 3, 1, u32::from(samples)),
|
||||
(278, 4, 1, 1),
|
||||
(279, 4, strips, counts),
|
||||
(284, 3, 1, if planar { 2 } else { 1 }),
|
||||
(338, 3, 1, 2),
|
||||
];
|
||||
f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
|
||||
for (tag, ty, count, value) in entries {
|
||||
f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat());
|
||||
f.extend([count.to_le_bytes(), value.to_le_bytes()].concat());
|
||||
}
|
||||
f.extend([0; 4]);
|
||||
f
|
||||
}
|
||||
|
||||
/// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MiB
|
||||
/// reads: here 256 × 16,385 pixels of 64 samples, 16,384 bytes more than the limit.
|
||||
#[test]
|
||||
fn a_tiff_with_extra_samples_past_the_decoders_limit_reads() {
|
||||
let (width, rows, samples) = (256, 16_385, 64);
|
||||
assert!(u64::from(width * rows) * u64::from(samples) > 256 << 20);
|
||||
let px = extra_samples_tiff_rgba(&tall_gray_tiff(width, rows, samples), |_| [0.0; 3]).expect("reads");
|
||||
assert_eq!((px.width(), px.height()), (width, rows));
|
||||
assert!(px.pixels().all(|p| p.0 == [255, 255, 255, 128]), "white at an alpha of 128");
|
||||
}
|
||||
|
||||
/// A pixel of more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples is not read.
|
||||
#[test]
|
||||
fn a_tiff_with_too_many_samples_a_pixel_is_not_read() {
|
||||
let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap();
|
||||
assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples), |_| [0.0; 3]).is_some(), "at the limit: reads");
|
||||
assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples + 1), |_| [0.0; 3]).is_none(), "past it: not read");
|
||||
}
|
||||
|
||||
/// The header of a one-row CMYK TIFF `width` pixels wide, each pixel `samples` samples of
|
||||
/// `bits` bits stored together, with the ExtraSamples values `extras` (more than two). Its one
|
||||
/// strip claims every sample of the row, uncompressed, and holds four bytes of zeros.
|
||||
fn cmyk_header(width: u32, samples: u16, bits: u16, extras: &[u16]) -> Vec<u8> {
|
||||
assert!(extras.len() > 2, "the values sit outside the entry");
|
||||
let mut f = b"II*\0\0\0\0\0".to_vec();
|
||||
f.extend([0; 4]);
|
||||
let at = u32::try_from(f.len()).unwrap();
|
||||
f.extend(extras.iter().flat_map(|e| e.to_le_bytes()));
|
||||
let ifd = u32::try_from(f.len()).unwrap();
|
||||
f[4..8].copy_from_slice(&ifd.to_le_bytes());
|
||||
let strip = u32::try_from(u64::from(width) * u64::from(samples) * u64::from(bits / 8)).unwrap();
|
||||
// (tag, type (3 SHORT, 4 LONG), count, value or offset)
|
||||
let entries = [
|
||||
(256u16, 4u16, 1, width),
|
||||
(257, 4, 1, 1),
|
||||
(258, 3, 1, u32::from(bits)),
|
||||
(259, 3, 1, 1),
|
||||
(262, 3, 1, 5),
|
||||
(273, 4, 1, 8),
|
||||
(277, 3, 1, u32::from(samples)),
|
||||
(278, 4, 1, 1),
|
||||
(279, 4, 1, strip),
|
||||
(284, 3, 1, 1),
|
||||
(338, 3, u32::try_from(extras.len()).unwrap(), at),
|
||||
];
|
||||
f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
|
||||
for (tag, ty, count, value) in entries {
|
||||
f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat());
|
||||
f.extend([count.to_le_bytes(), value.to_le_bytes()].concat());
|
||||
}
|
||||
f.extend([0; 4]);
|
||||
f
|
||||
}
|
||||
|
||||
/// A CMYK TIFF whose first ExtraSamples value is alpha has the color type of CMYK with alpha,
|
||||
/// five samples, however many samples its pixels have; one with more than
|
||||
/// [`MAX_EXTRA_SAMPLES_PIXEL`] is refused from its tags, before the decoder takes a row of
|
||||
/// every sample (here 8,192 × 65,535 × 2 bytes, 1 GiB). Neither is it read as inks.
|
||||
#[test]
|
||||
fn a_cmyk_tiff_with_more_samples_a_pixel_than_the_limit_is_refused_before_decoding() {
|
||||
let (width, samples) = (8192u32, u16::MAX);
|
||||
for first in [1u16, 0] {
|
||||
let extras: Vec<u16> = std::iter::once(first).chain(std::iter::repeat_n(0, usize::from(samples) - 5)).collect();
|
||||
let bytes = cmyk_header(width, samples, 16, &extras);
|
||||
let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
|
||||
let kind = d.colortype().unwrap();
|
||||
assert_eq!(kind, if first == 1 { tiff::ColorType::CMYKA(16) } else { tiff::ColorType::CMYK(16) });
|
||||
assert_eq!(row_buffer(&mut d), None, "{kind:?}: refused from the tags");
|
||||
let given = usize::from(kind.num_samples());
|
||||
assert!(with_room(d, bytes.len(), usize::try_from(width).unwrap(), given, 16).is_none(), "{kind:?}: refused before the decode");
|
||||
assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none(), "{kind:?}");
|
||||
assert!(ImageBlob::new("image/tiff", bytes).cmyk().is_none(), "{kind:?}: no inks");
|
||||
}
|
||||
}
|
||||
|
||||
/// The row the decoder reads each strip of a CMYK TIFF with alpha into, every sample of the
|
||||
/// row, counts in the allowance: 2²⁴ pixels of 64 16-bit samples, whose five decoded samples
|
||||
/// and RGBA pixels fit but not with that row of 2 GiB.
|
||||
#[test]
|
||||
fn the_decoders_row_of_every_sample_counts_in_the_allowance() {
|
||||
let width = 1u32 << 24;
|
||||
let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap();
|
||||
let extras: Vec<u16> = std::iter::once(2).chain(std::iter::repeat_n(0, usize::from(samples) - 5)).collect();
|
||||
let bytes = cmyk_header(width, samples, 16, &extras);
|
||||
let n = usize::try_from(width).unwrap();
|
||||
let (need, rgba, row) = (u64::from(width) * 5 * 2, u64::from(width) * 4, u64::from(width) * u64::from(samples) * 2);
|
||||
assert!(need + rgba <= crate::MAX_RASTER_ALLOC && need + rgba + row > crate::MAX_RASTER_ALLOC);
|
||||
let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
|
||||
assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYKA(16));
|
||||
assert_eq!(row_buffer(&mut d), Some(row));
|
||||
assert!(with_room(d, bytes.len(), n, 5, 16).is_none(), "refused before the decode");
|
||||
assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none());
|
||||
}
|
||||
|
||||
/// A TIFF whose samples aren't unsigned integers is refused from its tags.
|
||||
#[test]
|
||||
fn a_tiff_of_float_samples_is_refused_from_its_tags() {
|
||||
use tiff::encoder::colortype::{Gray8, Gray32Float};
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
tiff::encoder::TiffEncoder::new(&mut file).unwrap().write_image::<Gray32Float>(2, 1, &[0.25, 0.5]).unwrap();
|
||||
let float = file.into_inner();
|
||||
let mut d = tiff::decoder::Decoder::new(Cursor::new(&float[..])).unwrap();
|
||||
assert_eq!(row_buffer(&mut d), None, "floats: refused");
|
||||
assert!(read_samples_at_depth(&mut d, 2, 1).is_none());
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
tiff::encoder::TiffEncoder::new(&mut file).unwrap().write_image::<Gray8>(2, 1, &[64, 128]).unwrap();
|
||||
let bytes = file.into_inner();
|
||||
let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
|
||||
assert_eq!(row_buffer(&mut d), Some(0), "unsigned: no extra row");
|
||||
assert_eq!(read_samples_at_depth(&mut d, 2, 1), Some(Samples::Eight(vec![64, 128])));
|
||||
}
|
||||
|
||||
/// The copy that puts a planar file's samples pixel by pixel is allocated at its length, so
|
||||
/// the reader holds no more than the allowance counts. 33 samples: a copy that grew as it
|
||||
/// was filled would hold room for 64.
|
||||
#[test]
|
||||
fn the_planar_copy_is_allocated_at_its_length() {
|
||||
let (n, per) = (11u8, 3u8);
|
||||
let data: Vec<u8> = (0..n * per).collect();
|
||||
let len = data.len();
|
||||
let out = chunky(data, usize::from(per), usize::from(n), usize::from(per)).unwrap();
|
||||
let pixel_by_pixel: Vec<u8> = (0..n).flat_map(|i| (0..per).map(move |p| p * n + i)).collect();
|
||||
assert_eq!(out, pixel_by_pixel);
|
||||
assert!(out.capacity() >= len && out.capacity() < len.next_power_of_two(), "capacity {} for {len} samples", out.capacity());
|
||||
}
|
||||
|
||||
/// A TIFF whose decoded samples fit [`crate::MAX_RASTER_ALLOC`] but not with its RGBA pixels
|
||||
/// beside them is refused before its samples are decoded; so is one whose samples fit with
|
||||
/// the RGBA pixels but not with the copy a planar file needs. The file holds one row of pixels,
|
||||
/// which every strip reuses.
|
||||
#[test]
|
||||
fn a_tiff_whose_decode_with_its_rgba_takes_more_than_the_allowance_is_refused() {
|
||||
let side = 8192u32;
|
||||
let n = usize::try_from(u64::from(side) * u64::from(side)).unwrap();
|
||||
assert_eq!(u64::try_from(n).unwrap(), MAX_CMYK_PIXELS);
|
||||
let max = usize::try_from(crate::MAX_RASTER_ALLOC).unwrap();
|
||||
// One sample fewer than fills the allowance: the samples alone fit.
|
||||
let per = max / n - 1;
|
||||
assert!(n * per <= max && n * per + 4 * n > max);
|
||||
let bytes = tall_gray_tiff(side, side, u16::try_from(per).unwrap());
|
||||
let decoder = || tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
|
||||
assert!(with_room(decoder(), bytes.len(), n, per, 8).is_none(), "refused before the decode");
|
||||
assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none());
|
||||
// Half the allowance in samples fits with the RGBA pixels, but not twice over.
|
||||
let half = max / n / 2;
|
||||
assert!(with_room(decoder(), bytes.len(), n, half, 8).is_some(), "stored together: fits");
|
||||
let planar = gray_tiff(side, side, u16::try_from(half).unwrap(), true);
|
||||
let decoder = tiff::decoder::Decoder::new(Cursor::new(&planar[..])).unwrap();
|
||||
assert!(with_room(decoder, planar.len(), n, half, 8).is_none(), "one plane per sample: refused");
|
||||
}
|
||||
|
||||
/// Patched bytes read the same whole, a byte at a time and after a seek into a patch.
|
||||
#[test]
|
||||
fn patched_bytes_read_with_their_patches() {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let bytes: Vec<u8> = (10..30).collect();
|
||||
let patched = || Patched { bytes: Cursor::new(&bytes[..]), patches: vec![(4, &[1, 0]), (19, &[7, 7])] };
|
||||
let want = [10, 11, 12, 13, 1, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 7];
|
||||
let mut whole = Vec::new();
|
||||
patched().read_to_end(&mut whole).unwrap();
|
||||
assert_eq!(whole, want);
|
||||
let mut one = patched();
|
||||
let bytewise: Vec<u8> = (0..want.len())
|
||||
.map(|_| {
|
||||
let mut b = [0];
|
||||
assert_eq!(one.read(&mut b).unwrap(), 1);
|
||||
b[0]
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(bytewise, want);
|
||||
let mut from = patched();
|
||||
from.seek(SeekFrom::Start(5)).unwrap();
|
||||
let mut b = [9; 3];
|
||||
from.read_exact(&mut b).unwrap();
|
||||
assert_eq!(b, [0, 16, 17], "the second byte of the first patch, then the file");
|
||||
}
|
||||
|
||||
/// A grayscale TIFF whose alpha follows another extra sample reads that alpha.
|
||||
#[test]
|
||||
fn a_grayscale_tiff_with_alpha_after_another_extra_sample_reads_its_alpha() {
|
||||
let read =
|
||||
|extra: [u16; 2], data: &[u8]| extra_samples_tiff_rgba(&extras_tiff::<Gray3x8>(&extra, data), |_| [0.0; 3]).expect("reads").into_raw();
|
||||
// A gray of 64 at an alpha of 204 (premultiplied: 51), with an extra sample of 9.
|
||||
assert_eq!(read([0, 2], &[64, 9, 204]), [64, 64, 64, 204], "unassociated");
|
||||
assert_eq!(read([0, 1], &[51, 9, 204]), [64, 64, 64, 204], "associated, divided back out");
|
||||
assert_eq!(read([2, 0], &[64, 204, 9]), [64, 64, 64, 204], "the alpha first");
|
||||
assert_eq!(read([0, 0], &[64, 9, 204]), [64, 64, 64, 255], "no alpha: opaque");
|
||||
}
|
||||
|
||||
/// A grayscale TIFF whose white is zero (PhotometricInterpretation 0), with alpha, reads with
|
||||
/// its levels turned around.
|
||||
#[test]
|
||||
fn a_white_is_zero_grayscale_tiff_with_alpha_reads_as_rgba() {
|
||||
// White, opaque; black at an alpha of 128.
|
||||
let bytes = extras_tiff::<WhiteGray2x8>(&[2], &[0, 255, 255, 128]);
|
||||
let px = extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).expect("reads");
|
||||
assert_eq!(px.into_raw(), [255, 255, 255, 255, 0, 0, 0, 128]);
|
||||
}
|
||||
|
||||
/// A header claiming more tiles than can be counted: (2^32 − 1)² pixels in tiles of one pixel,
|
||||
/// times 2 planes.
|
||||
#[test]
|
||||
@@ -1377,6 +2057,35 @@ mod tests {
|
||||
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
|
||||
}
|
||||
|
||||
/// A CMYK TIFF written with a CMYK profile carries it byte for byte as tag 34675; a profile of
|
||||
/// other colors, and none, leave the TIFF untagged. The inks are the same either way.
|
||||
#[test]
|
||||
fn a_cmyk_tiff_carries_the_cmyk_profile_it_is_given() {
|
||||
let profile = |space: &[u8; 4]| {
|
||||
let mut icc = vec![0u8; 128];
|
||||
icc[0..4].copy_from_slice(&128u32.to_be_bytes());
|
||||
icc[16..20].copy_from_slice(space);
|
||||
icc[36..40].copy_from_slice(b"acsp");
|
||||
icc
|
||||
};
|
||||
let cmyk = profile(b"CMYK");
|
||||
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), Some(&cmyk)).unwrap();
|
||||
assert_eq!(b.cmyk_icc_profile(), Some(cmyk), "the profile, byte for byte");
|
||||
assert_eq!(b.cmyk(), Some(inks()));
|
||||
// Read back up to 16 MiB; a longer one isn't read.
|
||||
for (len, read) in [(16 << 20, true), ((16 << 20) + 1, false)] {
|
||||
let mut big = profile(b"CMYK");
|
||||
big.resize(len, 0);
|
||||
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), Some(&big)).unwrap();
|
||||
assert_eq!(b.cmyk_icc_profile().is_some_and(|p| p == big), read, "{len} bytes");
|
||||
}
|
||||
for icc in [Some(profile(b"RGB ")), None] {
|
||||
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), icc.as_deref()).unwrap();
|
||||
assert_eq!(tiff_icc_profile(&b.bytes), None, "{icc:?}");
|
||||
assert_eq!(b.cmyk(), Some(inks()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_gives_the_size_without_the_samples() {
|
||||
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
|
||||
@@ -1440,6 +2149,53 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK JPEG given a profile carries it in place of its own, its samples as they were; a
|
||||
/// profile longer than 255 segments hold, an empty one and bytes that aren't a JPEG give none.
|
||||
#[test]
|
||||
fn a_cmyk_jpeg_carries_the_profile_it_is_given() {
|
||||
let profile = |len: usize, mark: u8| {
|
||||
let mut icc = vec![mark; len];
|
||||
icc[16..20].copy_from_slice(b"CMYK");
|
||||
icc
|
||||
};
|
||||
let px: Vec<u8> = (0..16 * 16).flat_map(|_| [10u8, 40, 100, 20]).collect();
|
||||
let mut jpg = Vec::new();
|
||||
let mut e = jpeg_encoder::Encoder::new(&mut jpg, 100);
|
||||
e.add_icc_profile(&profile(300_000, 1)).unwrap();
|
||||
e.encode(&px, 16, 16, jpeg_encoder::ColorType::Cmyk).unwrap();
|
||||
let inks = ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap();
|
||||
// One segment holds 65,519 bytes of a profile.
|
||||
for len in [128, 65_519, 65_520, 300_000, 1 << 20] {
|
||||
let icc = profile(len, 2);
|
||||
let b = ImageBlob::new("image/jpeg", jpeg_with_icc(&jpg, &icc).unwrap());
|
||||
assert!(b.cmyk_icc_profile() == Some(icc), "{len} bytes");
|
||||
assert!(b.cmyk() == Some(inks.clone()), "{len} bytes: the samples as they were");
|
||||
}
|
||||
// A profile segment after the quantization table is taken out too.
|
||||
let dqt = jpg.windows(2).position(|w| w == [0xFF, 0xDB]).unwrap();
|
||||
let after = dqt + 2 + usize::from(u16::from_be_bytes([jpg[dqt + 2], jpg[dqt + 3]]));
|
||||
let mut late = jpg.clone();
|
||||
let stale = profile(128, 3);
|
||||
let segment = [&[0xFF, 0xE2, 0, 144][..], ICC_SEGMENT, &[1, 1], &stale].concat();
|
||||
late.splice(after..after, segment);
|
||||
let icc = profile(128, 2);
|
||||
let b = jpeg_with_icc(&late, &icc).unwrap();
|
||||
assert_eq!(b.windows(ICC_SEGMENT.len()).filter(|w| *w == ICC_SEGMENT).count(), 1, "one profile segment");
|
||||
assert!(ImageBlob::new("image/jpeg", b).cmyk_icc_profile() == Some(icc));
|
||||
// Fill bytes before the quantization table's marker are passed over.
|
||||
let mut filled = jpg.clone();
|
||||
filled.splice(dqt..dqt, [0xFF; 3]);
|
||||
assert!(ImageBlob::new("image/jpeg", filled.clone()).cmyk() == Some(inks.clone()), "the decoder reads it");
|
||||
let icc = profile(128, 2);
|
||||
let b = ImageBlob::new("image/jpeg", jpeg_with_icc(&filled, &icc).unwrap());
|
||||
assert!(b.cmyk_icc_profile() == Some(icc), "fill bytes");
|
||||
assert!(b.cmyk() == Some(inks.clone()), "fill bytes: the samples as they were");
|
||||
assert!(jpeg_with_icc(&jpg, &profile(255 * 65_519, 2)).is_some(), "255 segments");
|
||||
assert!(jpeg_with_icc(&jpg, &profile(255 * 65_519 + 1, 2)).is_none(), "256 segments");
|
||||
assert!(jpeg_with_icc(&jpg, &[]).is_none(), "empty");
|
||||
assert!(jpeg_with_icc(&ImageBlob::cmyk_tiff(&inks).unwrap().bytes, &profile(128, 2)).is_none(), "a TIFF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_images_are_not_cmyk() {
|
||||
let mut png = Vec::new();
|
||||
|
||||
+38
-27
@@ -543,7 +543,7 @@ pub struct GraphSpec {
|
||||
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed: Option<Rect>,
|
||||
/// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph
|
||||
/// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph
|
||||
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed_art: Option<Rect>,
|
||||
@@ -562,6 +562,43 @@ fn edge_to_edge_before_the_option() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn graph_art_without_type(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A
|
||||
/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the
|
||||
/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them,
|
||||
/// give their own bounds.
|
||||
fn without_type(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
use crate::NodeKind::{Compound, Group, Layer, Text};
|
||||
if matches!(n.kind, Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let children: &[std::sync::Arc<crate::Node>] = match &n.kind {
|
||||
Group { clip: true, children } | Layer { clip: true, children, .. } => children,
|
||||
Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(),
|
||||
_ => return (n.geometric_bounds(), false),
|
||||
};
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
let mut clip_has_type = false;
|
||||
let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. });
|
||||
for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) {
|
||||
let (b, t) = without_type(c);
|
||||
had_type |= t;
|
||||
clip_has_type |= i == 0 && t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. });
|
||||
if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl GraphSpec {
|
||||
/// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's.
|
||||
pub fn series_kind(&self, s: usize) -> GraphKind {
|
||||
@@ -630,32 +667,6 @@ impl GraphSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn art_bounds(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type
|
||||
/// gives its own bounds, so a clipping group gives the bounds of its clip.
|
||||
fn art_bounds_of(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
if matches!(n.kind, crate::NodeKind::Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let Some(children) = n.children() else { return (n.geometric_bounds(), false) };
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
for c in children {
|
||||
let (b, t) = art_bounds_of(c);
|
||||
had_type |= t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
if had_type { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl Default for GraphSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
+293
-66
@@ -266,6 +266,7 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
|
||||
/// (`opt.scope`) or on a locked artboard. On a layer whose Preview is off it counts by its
|
||||
/// outline, as a click there hits it.
|
||||
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
selected.iter().rev().copied().find(|&id| {
|
||||
@@ -322,6 +323,7 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
|
||||
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
|
||||
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
|
||||
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let walk = ArtWalk::open();
|
||||
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
|
||||
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
|
||||
// while a group (including a clipping group) is selected as one object. Repeatedly
|
||||
@@ -337,6 +339,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
for layer in doc.layers.iter().rev() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if !layer.is_layer() {
|
||||
walk.restart();
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
@@ -344,7 +347,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely.
|
||||
// The repeated traversal handles that mixed hierarchy precisely, with the whole
|
||||
// limit of symbol art to walk.
|
||||
walk.restart();
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
}
|
||||
@@ -429,6 +434,7 @@ pub const MAX_LOCKED_AT: usize = 20;
|
||||
/// out. While a pattern is edited only its tile layer is searched, and in isolation mode
|
||||
/// (`opt.scope`) only what is inside the isolated group or object.
|
||||
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut out = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
@@ -504,8 +510,9 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// [`hit_test`] passing over the nodes `skip` names (and their contents), and with
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]).
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
@@ -1055,9 +1062,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
|
||||
})
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => {
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
|
||||
}
|
||||
// A symbol instance is hit within its bounds, and outside them where its art paints
|
||||
// ([`instance_art_hit`]). In the art of another instance walked outside that instance's
|
||||
// bounds, it is hit only where its own art paints ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return Some(HitKind::Bounds);
|
||||
}
|
||||
instance_art_hit(n, p, opt, symbols)
|
||||
}
|
||||
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
|
||||
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
|
||||
// and the strokes of an envelope's distorted contents past its bounds.
|
||||
@@ -1105,10 +1121,12 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
stroke_contains(&path.to_bezpath(), 0.0, tol, p)
|
||||
}
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]).
|
||||
/// 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.
|
||||
fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
// Hidden art does not hit.
|
||||
if !n.visible {
|
||||
if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
|
||||
@@ -1164,6 +1182,15 @@ impl<'a> InstanceArt<'a> {
|
||||
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
|
||||
}
|
||||
|
||||
/// How many objects placing the whole art makes: the objects of the art with their opacity
|
||||
/// masks' art ([`Node::count_with_masks`]), or, through the guides, the most that
|
||||
/// [`crate::NineSliceMap::most_placed_with`] counts.
|
||||
fn size(&self) -> u64 {
|
||||
self.map
|
||||
.as_ref()
|
||||
.map_or_else(|| u64::try_from(self.art.count_with_masks()).unwrap_or(u64::MAX), |m| m.most_placed_with(&self.art, &self.boxes))
|
||||
}
|
||||
|
||||
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
|
||||
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
|
||||
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
|
||||
@@ -1211,64 +1238,231 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
struct Find<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
/// `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
|
||||
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
|
||||
if shaper_hides(n, i, None) {
|
||||
continue;
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if self.find(c, path, whole, outline) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
let _walk = ArtWalk::open();
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
struct FindPart<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
/// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws
|
||||
/// them, and clipping paths are not picked by their outline.
|
||||
whole_instance: bool,
|
||||
}
|
||||
|
||||
impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each
|
||||
/// object it visits inside `n` from the [`ArtWalk`] limit.
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
|
||||
let placed = self.art.place(n, whole)?;
|
||||
let _charged = ArtWalk::charge();
|
||||
hit_any(&placed, self.p, opt, self.symbols)
|
||||
}
|
||||
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
|
||||
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
if !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let clip = self.art.place_unclipped(first, whole)?;
|
||||
if !self.whole_instance
|
||||
&& self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& let Some(kind) = clip_outline(&clip, self.p, opt)
|
||||
{
|
||||
path.push(0);
|
||||
return Some(kind);
|
||||
}
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
|
||||
if shaper_hides(n, i, None) {
|
||||
continue;
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if let Some(kind) = self.find(c, path, whole, outline) {
|
||||
return Some(kind);
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click at `p` hits of symbol instance `n`'s art where the canvas draws it (`None` in
|
||||
/// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a
|
||||
/// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a
|
||||
/// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past
|
||||
/// the 9-slice object limit ([`InstanceArt::of`]), when `p` is outside the instance's reach
|
||||
/// ([`Node::reach_bounds_with`]), and once the click has visited as many objects of symbol art as
|
||||
/// [`ArtWalk`] allows.
|
||||
fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
|
||||
if opt.outline || symbols.art(symbol).is_none() || !n.reach_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return None;
|
||||
}
|
||||
let _walk = ArtWalk::open();
|
||||
if ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let art = InstanceArt::of(symbols.document(), n)?;
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let opt = HitOptions { clip_outlines: false, ..opt };
|
||||
let _art_only = ArtOnly::set();
|
||||
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a symbol instance's art is being walked outside the instance's box ([`ArtOnly`]).
|
||||
static ART_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a symbol instance is hit ([`hit_leaf`]) and touched by a marquee
|
||||
/// ([`marquee_with`]) only where its own art is, by the same rule at every level, and not anywhere
|
||||
/// in its box. [`instance_art_hit`] and the marquee's walk of an instance's art hold one: they walk
|
||||
/// the art outside the instance's box, where the box of an instance nested in the art can reach
|
||||
/// past it over empty space.
|
||||
struct ArtOnly {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl ArtOnly {
|
||||
fn set() -> Self {
|
||||
Self { was: ART_ONLY.replace(true) }
|
||||
}
|
||||
|
||||
fn on() -> bool {
|
||||
ART_ONLY.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtOnly {
|
||||
fn drop(&mut self) {
|
||||
ART_ONLY.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]),
|
||||
/// `None` outside one.
|
||||
static ART_WALK_LEFT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]).
|
||||
static ART_WALK_CHARGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The number of objects [`ArtWalk::open`] allows on this thread in place of
|
||||
/// [`crate::MAX_SYMBOL_NODES`].
|
||||
static ART_WALK_LIMIT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// How many symbol instances' art clicks and marquees walked on this thread.
|
||||
static ARTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The objects of symbol art that one click or one marquee may visit: [`crate::MAX_SYMBOL_NODES`]
|
||||
/// in all, the art of the instances nested in that art included, at every level. The first
|
||||
/// [`ArtWalk::open`] of a click or a marquee sets the limit, and the walks opened while its guard
|
||||
/// lives share it. Once the limit is used up, an instance is no longer hit or touched outside its
|
||||
/// box; inside its box it still is.
|
||||
struct ArtWalk {
|
||||
outermost: bool,
|
||||
}
|
||||
|
||||
impl ArtWalk {
|
||||
fn open() -> Self {
|
||||
let walk = Self { outermost: ART_WALK_LEFT.get().is_none() };
|
||||
walk.restart();
|
||||
walk
|
||||
}
|
||||
|
||||
/// For the outermost guard, sets what is left back to the whole limit.
|
||||
fn restart(&self) {
|
||||
if self.outermost {
|
||||
#[cfg(test)]
|
||||
let limit = ART_WALK_LIMIT.get().unwrap_or(crate::MAX_SYMBOL_NODES);
|
||||
#[cfg(not(test))]
|
||||
let limit = crate::MAX_SYMBOL_NODES;
|
||||
ART_WALK_LEFT.set(Some(limit));
|
||||
}
|
||||
}
|
||||
|
||||
/// Is nothing left?
|
||||
fn used_up() -> bool {
|
||||
ART_WALK_LEFT.get() == Some(0)
|
||||
}
|
||||
|
||||
/// Takes `n` objects from what is left. `false` when fewer are left, and nothing is left after.
|
||||
fn take(n: u64) -> bool {
|
||||
let Some(left) = ART_WALK_LEFT.get() else { return true };
|
||||
let rest = left.checked_sub(n);
|
||||
ART_WALK_LEFT.set(Some(rest.unwrap_or(0)));
|
||||
rest.is_some()
|
||||
}
|
||||
|
||||
/// While the guard lives, each object [`hit_any`] visits takes one object from what is left:
|
||||
/// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an
|
||||
/// Intertwine group, and the objects of groups nested deeper than
|
||||
/// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit.
|
||||
fn charge() -> ArtWalkCharge {
|
||||
ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) }
|
||||
}
|
||||
|
||||
/// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])?
|
||||
fn charged() -> bool {
|
||||
ART_WALK_CHARGED.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtWalk {
|
||||
fn drop(&mut self) {
|
||||
if self.outermost {
|
||||
ART_WALK_LEFT.set(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard of [`ArtWalk::charge`].
|
||||
struct ArtWalkCharge {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl Drop for ArtWalkCharge {
|
||||
fn drop(&mut self) {
|
||||
ART_WALK_CHARGED.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
@@ -1435,7 +1629,8 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
|
||||
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
|
||||
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
|
||||
/// by their art ([`Node::geometric_bounds_with`]). The art of a clip group or of a layer with a
|
||||
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
|
||||
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
@@ -1463,6 +1658,7 @@ fn previews_off(n: &Node) -> bool {
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let mut out = Vec::new();
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
@@ -1573,14 +1769,45 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A box with no width or no height (an instance of a symbol that draws a straight
|
||||
// line) is touched where the marquee crosses it.
|
||||
_ => n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
let crosses = (b.width() == 0.0 || b.height() == 0.0) && b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
b.intersect(r).area() > 0.0 || r.contains(b.origin()) || crosses
|
||||
}),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art. In the art of another instance
|
||||
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
_ => box_touches(n, s, r),
|
||||
}
|
||||
}
|
||||
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
|
||||
/// a symbol that draws a straight line) is touched where the marquee crosses it.
|
||||
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
let crosses = (b.width() == 0.0 || b.height() == 0.0) && b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
b.intersect(r).area() > 0.0 || r.contains(b.origin()) || crosses
|
||||
})
|
||||
}
|
||||
/// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as
|
||||
/// it touches a group of that art? Only for art whose clipping paths have live geometry effects
|
||||
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
|
||||
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
|
||||
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
return false;
|
||||
}
|
||||
let _walk = ArtWalk::open();
|
||||
if ArtWalk::used_up() {
|
||||
return false;
|
||||
}
|
||||
let Some(art) = InstanceArt::of(s.document(), n) else { return false };
|
||||
if !ArtWalk::take(art.size()) {
|
||||
return false;
|
||||
}
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let _art_only = ArtOnly::set();
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
|
||||
@@ -1852,6 +1852,325 @@ fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
|
||||
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
|
||||
}
|
||||
|
||||
/// A symbol instance whose art holds a clip group or a clipping layer with a live effect that moves
|
||||
/// its clipping path is clicked, and touched by a marquee, where the moved region shows the art past
|
||||
/// the art's box: inside a group, nested in another symbol's art, moved and scaled. In Outline view,
|
||||
/// below a layer whose Preview is off, where the art is hidden and where no region is left, only the
|
||||
/// box counts.
|
||||
#[test]
|
||||
fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
set_clip_region(moved_clip_region);
|
||||
// `effect` on the clipping path of a clip group (a clipping layer with `layer`), whose art is
|
||||
// shown when `shown`; `xf` places the instance, which with `nest` shows a symbol whose art holds
|
||||
// an instance of the clipped symbol. The instance is in a group: the group, the instance.
|
||||
let build = |effect: &str, xf: Affine, nest: bool, shown: bool, layer: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, mut art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
|
||||
art.visible = shown;
|
||||
let mut clip = if layer {
|
||||
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
*children = vec![Arc::new(mask), Arc::new(art)];
|
||||
}
|
||||
layer
|
||||
} else {
|
||||
Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)])
|
||||
};
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let mut symbol = "Clipped";
|
||||
if nest {
|
||||
let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: Affine::IDENTITY });
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(inner)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(root) });
|
||||
symbol = "Outer";
|
||||
}
|
||||
let (g, inst) = (d.alloc_id(), d.alloc_id());
|
||||
let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: symbol.into(), xf });
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(instance)])).unwrap();
|
||||
(d, g, inst)
|
||||
};
|
||||
let opt = HitOptions::default();
|
||||
let outline = HitOptions { outline: true, ..opt };
|
||||
let at = |d: &Document, x: f64, y: f64, opt: HitOptions| hit_test(d, Point::new(x, y), opt).map(|h| h.leaf);
|
||||
// Across the art's top edge in the moved region, and past the art's right end.
|
||||
let (edge, past) = (Rect::new(140.0, -5.0, 160.0, 5.0), Rect::new(240.0, -5.0, 260.0, 5.0));
|
||||
for layer in [false, true] {
|
||||
let (d, g, inst) = build("test.move", Affine::IDENTITY, false, true, layer);
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), Some(inst), "in the moved region, layer {layer}");
|
||||
assert_eq!(hit_test(&d, Point::new(150.0, 50.0), opt).map(|h| h.top_object(None)), Some(g));
|
||||
assert_eq!(at(&d, 50.0, 50.0, opt), Some(inst), "in the box");
|
||||
assert_eq!(at(&d, 250.0, 50.0, opt), None, "past the art");
|
||||
assert_eq!(at(&d, 150.0, 150.0, opt), None, "below the art");
|
||||
assert_eq!(at(&d, 150.0, 50.0, outline), None, "Outline view draws the plain clipping path");
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
|
||||
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
|
||||
assert!(marquee(&d, past, None, false).is_empty());
|
||||
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
|
||||
}
|
||||
// Preview off for the layer the instance is on.
|
||||
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
|
||||
if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
|
||||
*preview = false;
|
||||
}
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), None, "Preview off");
|
||||
assert!(marquee(&d, edge, None, false).is_empty(), "Preview off");
|
||||
// Moved, scaled (the region moves 100 pt from the placed clipping path) and nested.
|
||||
let (d, _, inst) = build("test.move", Affine::translate((10.0, 20.0)), false, true, false);
|
||||
assert_eq!(at(&d, 160.0, 70.0, opt), Some(inst), "moved");
|
||||
let (d, _, inst) = build("test.move", Affine::scale(2.0), false, true, false);
|
||||
assert_eq!(at(&d, 250.0, 100.0, opt), Some(inst), "scaled");
|
||||
assert_eq!(at(&d, 350.0, 100.0, opt), None, "scaled, past the region");
|
||||
let (d, g, inst) = build("test.move", Affine::IDENTITY, true, true, false);
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), Some(inst), "nested");
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "nested");
|
||||
// Hidden art, and an effect that leaves no region: clicks find only the box. The marquee still
|
||||
// touches the moved clipping path on the edge of its region, as in a clip group, unless no
|
||||
// region is left.
|
||||
for (effect, shown) in [("test.move", false), ("test.empty", true)] {
|
||||
let (d, g, inst) = build(effect, Affine::IDENTITY, false, shown, false);
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), None, "{effect}, shown {shown}");
|
||||
assert_eq!(at(&d, 50.0, 50.0, opt), Some(inst), "{effect}, shown {shown}: in the box");
|
||||
let touched: &[NodeId] = if shown { &[] } else { &[g] };
|
||||
assert_eq!(marquee(&d, edge, None, false), touched, "{effect}, shown {shown}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the stroke of a symbol's art where it paints past the instance's box selects the
|
||||
/// instance; past the stroke, and in Outline view, it does not.
|
||||
#[test]
|
||||
fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// A 20 pt stroke reaches 10 pt past the 0..100 square.
|
||||
let look = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 20.0);
|
||||
let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look);
|
||||
let art = Node::group(d.alloc_id(), vec![Arc::new(square)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Stroked".into(), art: Arc::new(art) });
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::IDENTITY;
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Stroked".into(), xf })).unwrap();
|
||||
let at = |x: f64, opt: HitOptions| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(108.0, HitOptions::default()), Some(inst), "on the stroke past the box");
|
||||
assert_eq!(at(50.0, HitOptions::default()), Some(inst), "in the box");
|
||||
assert_eq!(at(116.0, HitOptions::default()), None, "past the stroke");
|
||||
assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view");
|
||||
}
|
||||
|
||||
/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not
|
||||
/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved
|
||||
/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it
|
||||
/// selects the outer instance.
|
||||
#[test]
|
||||
fn a_nested_symbol_instances_box_past_the_outer_box_is_not_a_hit() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// `Two` draws squares at the corners of 0..200 × 0..100, and with `middle` one at 140..160 ×
|
||||
// 40..60. The outer symbol clips an instance of it to 0..100 × 0..100, which `test.move` moves
|
||||
// to 100..200: the outer box is 0..100, the nested box 0..200.
|
||||
let build = |middle: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |d: &mut Document, r: Rect| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()));
|
||||
let mut squares = vec![square(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)), square(&mut d, Rect::new(190.0, 90.0, 200.0, 100.0))];
|
||||
if middle {
|
||||
squares.push(square(&mut d, Rect::new(140.0, 40.0, 160.0, 60.0)));
|
||||
}
|
||||
group_symbol(&mut d, "Two", squares);
|
||||
let (mut mask, _) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let nested = instance_of(&mut d, "Two");
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), nested]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Outer", vec![Arc::new(clip)]);
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Outer".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
(d, inst)
|
||||
};
|
||||
let at = |d: &Document, x: f64, y: f64| hit_test(d, Point::new(x, y), HitOptions::default()).map(|h| h.leaf);
|
||||
let inside = Rect::new(145.0, 45.0, 155.0, 55.0);
|
||||
let (d, inst) = build(false);
|
||||
assert_eq!(at(&d, 150.0, 50.0), None, "empty space in the nested box");
|
||||
assert!(marquee(&d, inside, None, false).is_empty(), "marquee on empty space in the nested box");
|
||||
assert_eq!(at(&d, 195.0, 95.0), Some(inst), "on the nested art past the outer box");
|
||||
assert_eq!(at(&d, 50.0, 50.0), Some(inst), "in the outer box");
|
||||
let (d, inst) = build(true);
|
||||
assert_eq!(at(&d, 150.0, 50.0), Some(inst), "on the nested art");
|
||||
// Across the middle square's left edge.
|
||||
assert_eq!(marquee(&d, Rect::new(135.0, 45.0, 145.0, 55.0), None, false), [inst], "marquee on the nested art");
|
||||
}
|
||||
|
||||
/// Adds the symbol `Clipped`: a clip group whose clipping path's region `test.move` moves to
|
||||
/// 100..200 × 0..100, past the 0..100 box, over a 0..200 × 0..100 rectangle shown when `shown`.
|
||||
/// A click at (150, 50) hits an instance of it on the rectangle, or, with the rectangle hidden,
|
||||
/// walks its art and finds nothing.
|
||||
fn clipped_symbol(d: &mut Document, shown: bool) {
|
||||
set_clip_region(moved_clip_region);
|
||||
let (mut mask, mut art) = half_clipped(d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
art.visible = shown;
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) });
|
||||
}
|
||||
|
||||
/// A symbol named `name` whose art is a group of `members`.
|
||||
fn group_symbol(d: &mut Document, name: &str, members: Vec<Arc<Node>>) {
|
||||
let root = Node::group(d.alloc_id(), members);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: name.into(), art: Arc::new(root) });
|
||||
}
|
||||
|
||||
/// An instance of the symbol named `symbol`, not moved.
|
||||
fn instance_of(d: &mut Document, symbol: &str) -> Arc<Node> {
|
||||
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }))
|
||||
}
|
||||
|
||||
/// 30 small squares at the origin, which a click at (150, 50) passes by.
|
||||
fn far_squares(d: &mut Document) -> Vec<Arc<Node>> {
|
||||
(0..30).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()))).collect()
|
||||
}
|
||||
|
||||
/// Runs `f` with [`ArtWalk`] allowing `limit` objects, and returns its result with how many
|
||||
/// leaves [`hit_leaf`] tested and how many instances' art was walked meanwhile.
|
||||
fn with_art_limit<R>(limit: u64, f: impl FnOnce() -> R) -> (R, usize, usize) {
|
||||
ART_WALK_LIMIT.with(|c| c.set(Some(limit)));
|
||||
LEAVES_TESTED.with(|c| c.set(0));
|
||||
ARTS_WALKED.with(|c| c.set(0));
|
||||
let r = f();
|
||||
ART_WALK_LIMIT.with(|c| c.set(None));
|
||||
(r, LEAVES_TESTED.with(std::cell::Cell::get), ARTS_WALKED.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// One click visits at most the art walk's limit of objects in a chain of nested symbol
|
||||
/// instances, though each level's art alone is well within it. A click on the art of an
|
||||
/// instance nested in another is still found.
|
||||
#[test]
|
||||
fn a_click_walks_a_chain_of_nested_symbol_instances_within_one_limit() {
|
||||
// Level 0 is `Clipped`; each level above holds an instance of the level below and 30 squares:
|
||||
// 32 objects to visit at each level.
|
||||
let chain = |shown: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
clipped_symbol(&mut d, shown);
|
||||
for level in 1..12 {
|
||||
let below = if level == 1 { "Clipped".to_string() } else { format!("Level {}", level - 1) };
|
||||
let mut members = vec![instance_of(&mut d, &below)];
|
||||
members.extend(far_squares(&mut d));
|
||||
group_symbol(&mut d, &format!("Level {level}"), members);
|
||||
}
|
||||
let inst = instance_of(&mut d, "Level 11");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
(d, id)
|
||||
};
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
|
||||
// Without one limit for the click, the miss walks the art of all 12 levels.
|
||||
let (d, inst) = chain(false);
|
||||
let (hit, _, arts) = with_art_limit(100, || at(&d, 150.0));
|
||||
assert_eq!(hit, None);
|
||||
assert!(arts <= 4, "{arts} levels walked");
|
||||
assert_eq!(with_art_limit(100, || at(&d, 50.0)).0, Some(inst), "in the box");
|
||||
// Past the limit, a click that the art would take finds only the box.
|
||||
let (d, inst) = chain(true);
|
||||
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, None, "past the limit");
|
||||
assert_eq!(at(&d, 150.0), Some(inst), "within the limit");
|
||||
// Two levels: a click on the inner instance's art is found within the limit.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
clipped_symbol(&mut d, true);
|
||||
let inner = instance_of(&mut d, "Clipped");
|
||||
group_symbol(&mut d, "Outer", vec![inner]);
|
||||
let inst = instance_of(&mut d, "Outer");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, Some(id), "nested");
|
||||
}
|
||||
|
||||
/// One click, and one marquee, visit at most the art walk's limit of objects in art that repeats
|
||||
/// one nested instance many times, though the art of each instance alone is well within it. A
|
||||
/// click on one of the nested instances' art is still found.
|
||||
#[test]
|
||||
fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit() {
|
||||
// 50 instances of `Clipped` in one symbol's art, its rectangle shown when `shown`.
|
||||
let repeated = |shown: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
clipped_symbol(&mut d, shown);
|
||||
let members = (0..50).map(|_| instance_of(&mut d, "Clipped")).collect();
|
||||
group_symbol(&mut d, "Repeated", members);
|
||||
let inst = instance_of(&mut d, "Repeated");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
(d, id)
|
||||
};
|
||||
let (d, inst) = repeated(false);
|
||||
// Without one limit for the click, the miss walks the art of all 51 instances. The outer art
|
||||
// takes 1 object of the 100, and each nested instance with its art 4.
|
||||
let (hit, _, arts) = with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf));
|
||||
assert_eq!(hit, None);
|
||||
assert!(arts <= 26, "{arts} instances' art walked");
|
||||
// Select Behind over 60 instances of `Clipped` on the layer shares one limit too: each walk
|
||||
// takes 3 objects of the 100.
|
||||
let mut stack = Document::new(600.0, 400.0);
|
||||
let l = stack.layers[0].id;
|
||||
clipped_symbol(&mut stack, false);
|
||||
for _ in 0..60 {
|
||||
let inst = instance_of(&mut stack, "Clipped");
|
||||
stack.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&stack, Point::new(150.0, 50.0), HitOptions::default(), None));
|
||||
assert!(behind.is_empty());
|
||||
assert!(arts <= 34, "Select Behind: {arts} instances' art walked");
|
||||
// Without one limit for the marquee, it places the art of all 51 instances, inside the moved
|
||||
// region (within each instance's reach and outside its box). Placing the outer art takes 51
|
||||
// objects of the 100, and each nested art 4.
|
||||
let inside = Rect::new(140.0, 40.0, 160.0, 60.0);
|
||||
let (touched, _, arts) = with_art_limit(100, || marquee(&d, inside, None, false));
|
||||
assert!(touched.is_empty());
|
||||
assert!(arts <= 14, "{arts} instances' art placed");
|
||||
assert_eq!(with_art_limit(100, || marquee(&d, Rect::new(40.0, 40.0, 60.0, 60.0), None, false)).0, [inst], "in the box");
|
||||
// A click and a marquee on the nested instances' art are found within the limit.
|
||||
let (d, inst) = repeated(true);
|
||||
assert_eq!(with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)).0, Some(inst), "click");
|
||||
let edge = Rect::new(140.0, -5.0, 160.0, 5.0);
|
||||
assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge");
|
||||
}
|
||||
|
||||
/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects
|
||||
/// for a click, as the members of a plain group do. A click on a member's path past the instance's
|
||||
/// box is still found within the limit.
|
||||
#[test]
|
||||
fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100
|
||||
// box, over an Intertwine group of 200 squares at 140..160 × 40..60.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, _) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let squares = (0..200)
|
||||
.map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art())))
|
||||
.collect();
|
||||
let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares }));
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Woven", vec![Arc::new(clip)]);
|
||||
let inst = instance_of(&mut d, "Woven");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
let opt = HitOptions { path_only: true, ..HitOptions::default() };
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
// Inside the squares and away from their paths, every member is tested and none is hit.
|
||||
let (hit, leaves, _) = with_art_limit(100, || at(150.0));
|
||||
assert_eq!(hit, None);
|
||||
assert!(leaves <= 100, "{leaves} leaves tested");
|
||||
assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
+34
-4
@@ -80,16 +80,22 @@ pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
pub type Link<'a> = Option<(&'a str, f32)>;
|
||||
|
||||
/// An ink amount clamped to 0..1; an amount that is not a finite number prints no ink.
|
||||
fn ink_amount(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate.
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
|
||||
/// not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [tint.clamp(0.0, 1.0); 4], spot: None, registration: true };
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), tint.clamp(0.0, 1.0))), registration: false };
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
|
||||
}
|
||||
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
|
||||
}
|
||||
@@ -104,7 +110,7 @@ pub type StopPlates = Option<[f32; 4]>;
|
||||
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
|
||||
let mut ink = inks(doc, c, color, link, intent);
|
||||
if let (Some(p), Some(_)) = (plates, &ink.spot) {
|
||||
ink.cmyk = p.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
ink.cmyk = p.map(ink_amount);
|
||||
}
|
||||
ink
|
||||
}
|
||||
@@ -227,6 +233,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
|
||||
let d = gold_doc();
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.25, 0.1, 0.8, 0.05);
|
||||
let ink = |link: Link| inks(&d, &c, &look, link, Intent::RelativeColorimetric);
|
||||
for t in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let spot = ink(Some(("Gold", t)));
|
||||
assert_eq!(spot, Inks { cmyk: [0.0; 4], spot: Some(("Gold".into(), 0.0)), registration: false }, "{t}");
|
||||
assert_eq!((spot.on_plate("Gold"), spot.on_plate("Cyan")), (0.0, 0.0), "{t}");
|
||||
let reg = ink(Some((REGISTRATION, t)));
|
||||
assert_eq!(reg, Inks { cmyk: [0.0; 4], spot: None, registration: true }, "{t}");
|
||||
assert_eq!((reg.on_plate("Gold"), reg.on_plate("Black")), (0.0, 0.0), "{t}");
|
||||
// A stop's process plates still print beside a spot tint that prints nothing.
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Gold", t)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!((stop.cmyk, stop.on_plate("Gold")), ([0.25, 0.0, 0.4, 0.0], 0.0), "{t}");
|
||||
}
|
||||
// Finite tints outside 0..1 are clamped.
|
||||
assert_eq!(ink(Some(("Gold", 2.0))).on_plate("Gold"), 1.0);
|
||||
assert_eq!(ink(Some(("Gold", -1.0))).on_plate("Gold"), 0.0);
|
||||
assert_eq!(ink(Some((REGISTRATION, 2.0))).cmyk, [1.0; 4]);
|
||||
assert_eq!(ink(Some((REGISTRATION, -1.0))).cmyk, [0.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() {
|
||||
let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
|
||||
|
||||
@@ -119,6 +119,8 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::GlyphForm;
|
||||
pub use text::PATH_LEAD_MAX;
|
||||
pub use text::WarichuAlign;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
@@ -126,7 +128,7 @@ pub use text::{
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
|
||||
@@ -358,6 +358,34 @@ mod tests {
|
||||
assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 25.0).abs() < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coons_places_are_where_the_patch_bends() {
|
||||
// A rectangle's sides have 65 evenly spaced points.
|
||||
let [u, v] = Coons::rect(Rect::new(0.0, 0.0, 100.0, 50.0)).places();
|
||||
assert_eq!((u.len(), v.len()), (65, 65));
|
||||
assert!(u.iter().enumerate().all(|(i, x)| (x - i as f64 / 64.0).abs() < 1e-12), "{u:?}");
|
||||
// A top object with a curved top: between two places next to each other the patch is
|
||||
// straight, in `u` and in `v`.
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((30.0, -20.0), (70.0, 10.0), (100.0, 0.0));
|
||||
path.line_to((100.0, 50.0));
|
||||
path.line_to((40.0, 50.0));
|
||||
path.line_to((0.0, 50.0));
|
||||
path.close_path();
|
||||
let c = Coons::from_top_object(&PathData::from_bezpath(&path), Some([0, 1, 2, 4])).unwrap();
|
||||
let [u, v] = c.places();
|
||||
assert!(u.first() == Some(&0.0) && u.last() == Some(&1.0) && u.windows(2).all(|w| w[0] < w[1]), "{u:?}");
|
||||
assert!(v.first() == Some(&0.0) && v.last() == Some(&1.0) && v.windows(2).all(|w| w[0] < w[1]), "{v:?}");
|
||||
for w in u.windows(2) {
|
||||
for y in [0.0, 0.3, 1.0] {
|
||||
let mid = c.eval((w[0] + w[1]) / 2.0, y);
|
||||
let half = c.eval(w[0], y).midpoint(c.eval(w[1], y));
|
||||
assert!(mid.distance(half) < 1e-9, "{w:?} {y}: {mid:?} {half:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_go_on_past_the_content_box() {
|
||||
// A stroke outline reaches past the box: a flat mesh and a rectangle stay the identity there.
|
||||
|
||||
@@ -338,6 +338,31 @@ impl Coons {
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
|
||||
/// The places in `u` where the top or bottom side has a point, and the places in `v` where the
|
||||
/// left or right side has one, rising from 0 to 1. Between two places next to each other, each
|
||||
/// side runs straight, so [`Self::eval`] changes linearly in `u` and in `v` inside each cell of
|
||||
/// the grid they make.
|
||||
pub fn places(&self) -> [Vec<f64>; 2] {
|
||||
let sides = [&self.top, &self.right, &self.bottom, &self.left];
|
||||
let at = |which: usize| -> Vec<f64> {
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => knots.clone(),
|
||||
None => {
|
||||
let last = sides[which].len().saturating_sub(1).max(1);
|
||||
(0..=last).map(|i| i as f64 / last as f64).collect()
|
||||
}
|
||||
}
|
||||
};
|
||||
let merge = |a: usize, b: usize| {
|
||||
let mut v = at(a);
|
||||
v.extend(at(b));
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.dedup();
|
||||
v
|
||||
};
|
||||
[merge(0, 2), merge(1, 3)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
|
||||
+37
-4
@@ -105,8 +105,13 @@ impl Document {
|
||||
n += shared(&self.para_styles, &newer.para_styles, styles);
|
||||
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
|
||||
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
|
||||
let custom = |f: &crate::CompositeFont| {
|
||||
vec_bytes(&f.custom) + f.custom.iter().map(|s| s.name.capacity() + s.characters.capacity() + part(&s.part)).sum::<usize>()
|
||||
};
|
||||
vec_bytes(c)
|
||||
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
|
||||
+ c.iter()
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
@@ -276,7 +281,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
});
|
||||
}
|
||||
b += match &n.kind {
|
||||
NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live),
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
let was = other.and_then(|o| match &o.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
});
|
||||
path_bytes_besides(path, was) + boxed(live)
|
||||
}
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
@@ -293,8 +304,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
}
|
||||
|
||||
fn path_bytes(p: &PathData) -> usize {
|
||||
let anchors: usize =
|
||||
p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::<Anchor>() }).sum();
|
||||
path_bytes_besides(p, None)
|
||||
}
|
||||
|
||||
/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too:
|
||||
/// a version made by changing one anchor shares every chunk but the one it changed.
|
||||
fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize {
|
||||
let mut shared: Vec<usize> =
|
||||
other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default();
|
||||
shared.sort_unstable();
|
||||
let chunk = ALLOC + ARC + size_of::<Vec<Anchor>>() + ALLOC;
|
||||
let anchors: usize = p
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let table = s.anchors.table_bytes();
|
||||
let own: usize = s
|
||||
.anchors
|
||||
.chunk_allocations()
|
||||
.filter(|(id, _)| shared.binary_search(id).is_err())
|
||||
.map(|(_, capacity)| chunk + capacity * size_of::<Anchor>())
|
||||
.sum();
|
||||
if table == 0 { own } else { ALLOC + table + own }
|
||||
})
|
||||
.sum();
|
||||
anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::<SubPath>() }
|
||||
}
|
||||
|
||||
|
||||
@@ -74,19 +74,32 @@ impl Node {
|
||||
/// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted
|
||||
/// over it (unclipped). Each part is this object keeping only those appearance items (type:
|
||||
/// also only its characters' fills or strokes); `None` where it paints nothing, as right after
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths.
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths, and so does
|
||||
/// a group of the pieces a clipping path's fills and strokes draw ([`crate::NodeExtras::clip_pieces`]),
|
||||
/// even after effects around it split or copy those pieces into groups: each part is then that
|
||||
/// group keeping only the pieces of those fills or strokes.
|
||||
pub fn clip_paint(&self) -> ClipPaint {
|
||||
use crate::appearance::AppearanceItem;
|
||||
let item = |fill: bool, i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
if matches!(self.kind, NodeKind::Group { clip: false, .. }) && self.extras().clip_pieces {
|
||||
let part = |fill: bool| {
|
||||
let mut paints = false;
|
||||
let mut n = pieces_of(self, fill, &|i| item(fill, i), &mut paints)?;
|
||||
n.extras_mut().clip_pieces = false;
|
||||
paints.then_some(n)
|
||||
};
|
||||
return ClipPaint { fill: part(true), stroke: part(false) };
|
||||
}
|
||||
let runs = match &self.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None,
|
||||
NodeKind::Text(t) => Some(&t.runs),
|
||||
_ => return ClipPaint::default(),
|
||||
};
|
||||
let paints = |fill: bool| {
|
||||
let item = |i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
let item = |i: &AppearanceItem| item(fill, i);
|
||||
let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 };
|
||||
self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run))
|
||||
};
|
||||
@@ -110,6 +123,30 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`, a group of a clipping path's pieces or one of them, keeping only the pieces of its fills
|
||||
/// (`fill`) or of its strokes, at every depth of the groups an effect put them in; `None` when it
|
||||
/// holds none. `paints` is set when one of the kept fills or strokes paints.
|
||||
fn pieces_of(n: &Node, fill: bool, paints_item: &dyn Fn(&crate::appearance::AppearanceItem) -> bool, paints: &mut bool) -> Option<Node> {
|
||||
use crate::appearance::AppearanceItem;
|
||||
if let NodeKind::Group { children, clip: false } = &n.kind {
|
||||
let kept: Vec<_> = children.iter().filter_map(|c| pieces_of(c, fill, paints_item, paints).map(std::sync::Arc::new)).collect();
|
||||
if kept.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = kept;
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let items = &n.appearance.items;
|
||||
if !items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) == fill) {
|
||||
return None;
|
||||
}
|
||||
*paints |= items.iter().any(paints_item);
|
||||
Some(n.clone())
|
||||
}
|
||||
|
||||
/// What a clipping path paints ([`Node::clip_paint`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ClipPaint {
|
||||
|
||||
@@ -79,6 +79,10 @@ pub struct NodeExtras {
|
||||
/// knockout group its knockout shape is the whole area of its triangle, not only where the
|
||||
/// image is opaque ([`Node::knockout_outline`]).
|
||||
pub warp_piece: bool,
|
||||
/// A group of the pieces a clipping path's fills and strokes draw once their geometry effects
|
||||
/// are applied, one path or compound path per fill and stroke: as the clipping path of a clip group it paints
|
||||
/// those pieces as the path paints its fills and strokes ([`Node::clip_paint`]).
|
||||
pub clip_pieces: bool,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -108,6 +112,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
pixel_aligned: false,
|
||||
color_mask: None,
|
||||
warp_piece: false,
|
||||
clip_pieces: false,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -228,7 +228,11 @@ impl Node {
|
||||
/// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice
|
||||
/// guides, that box also holds the art box placed by each cell's map
|
||||
/// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform.
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform. An
|
||||
/// instance whose art holds a clipping path with live geometry effects also takes in the region
|
||||
/// they give it ([`crate::hit::set_clip_region`]): moved with the instance when it only moves its
|
||||
/// art, otherwise placed by it and grown by as far as the region reaches past the art, times √2
|
||||
/// and the larger of 1 and the Frobenius norm of the transform's linear part.
|
||||
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
symbols.quickly(|| self.reach(Some(symbols)))
|
||||
}
|
||||
@@ -268,6 +272,30 @@ impl Node {
|
||||
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
|
||||
}
|
||||
// The live geometry effects of the clipping paths in the art can draw it past its box.
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let Some((s, art, region)) = symbols.and_then(|s| {
|
||||
let a = s.art(symbol)?;
|
||||
Some((s, a, a.reshaped?))
|
||||
}) else {
|
||||
return self.visual(symbols);
|
||||
};
|
||||
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
|
||||
let placed = if moves_only(*xf) && map.is_none() {
|
||||
xf.transform_rect_bbox(region)
|
||||
} else {
|
||||
// An effect can reach a fixed distance past the art or a distance in proportion
|
||||
// to its size, as `SymbolBoxes::effects_reach` estimates it.
|
||||
let g = art.geometric;
|
||||
let all = region.union(g);
|
||||
let past = [g.x0 - region.x0, region.x1 - g.x1, g.y0 - region.y0, region.y1 - g.y1].into_iter().fold(0.0_f64, f64::max);
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let grow = past * std::f64::consts::SQRT_2 * (a * a + b * b + c * c + d * d).sqrt().max(1.0);
|
||||
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
|
||||
};
|
||||
let o = self.appearance.outset();
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
@@ -369,7 +397,7 @@ impl Node {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
// A clipping path that paints (see `clip_paint`) strokes over the clip edge.
|
||||
let clip = children.first()?;
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) {
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) || clip.extras().clip_pieces {
|
||||
clip.visual(symbols)
|
||||
} else {
|
||||
clip.geometric(symbols)
|
||||
|
||||
@@ -24,6 +24,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
|
||||
e.pixel_aligned = true;
|
||||
e.warp_piece = true;
|
||||
e.clip_pieces = true;
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
@@ -71,11 +72,13 @@ fn extras_are_written_flat_in_order() {
|
||||
"envelope_edit_margin",
|
||||
"pixel_aligned",
|
||||
"warp_piece",
|
||||
"clip_pieces",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(v["shape_mode"], "exclude");
|
||||
assert_eq!(v["pixel_aligned"], true);
|
||||
assert_eq!(v["warp_piece"], true);
|
||||
assert_eq!(v["clip_pieces"], true);
|
||||
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
|
||||
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
|
||||
|
||||
@@ -57,6 +57,7 @@ impl Serialize for Node {
|
||||
is_default(&e.pixel_aligned),
|
||||
e.color_mask.is_none(),
|
||||
is_default(&e.warp_piece),
|
||||
is_default(&e.clip_pieces),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -102,6 +103,7 @@ impl Serialize for Node {
|
||||
field!("pixel_aligned", &e.pixel_aligned);
|
||||
field!("color_mask", &e.color_mask);
|
||||
field!("warp_piece", &e.warp_piece);
|
||||
field!("clip_pieces", &e.clip_pieces);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -249,6 +251,8 @@ pub(super) struct NodeWire {
|
||||
color_mask: Option<Box<crate::color_mask::ColorMask>>,
|
||||
#[serde(default)]
|
||||
warp_piece: bool,
|
||||
#[serde(default)]
|
||||
clip_pieces: bool,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -279,6 +283,7 @@ impl From<NodeWire> for Node {
|
||||
pixel_aligned: w.pixel_aligned,
|
||||
color_mask: w.color_mask,
|
||||
warp_piece: w.warp_piece,
|
||||
clip_pieces: w.clip_pieces,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -173,6 +173,10 @@ pub struct PatternDef {
|
||||
/// Size Tile to Art: the tile is the art bounds grown by the spacing.
|
||||
#[serde(default)]
|
||||
pub size_tile_to_art: bool,
|
||||
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by
|
||||
/// the same offset.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub move_tile_with_art: bool,
|
||||
#[serde(default)]
|
||||
pub h_spacing: f64,
|
||||
#[serde(default)]
|
||||
@@ -202,6 +206,7 @@ impl PatternDef {
|
||||
art,
|
||||
overlap: Overlap::default(),
|
||||
size_tile_to_art: false,
|
||||
move_tile_with_art: false,
|
||||
h_spacing: 0.0,
|
||||
v_spacing: 0.0,
|
||||
copies: 5,
|
||||
|
||||
@@ -49,6 +49,13 @@ pub struct Selection {
|
||||
/// it when no object is selected to align to it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
|
||||
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
|
||||
/// move the other selected points relative to it, and it stays in place. Never set with `key`
|
||||
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
|
||||
/// fewer than two points are selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_anchor: Option<(NodeId, AnchorRef)>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
@@ -98,6 +105,7 @@ impl Selection {
|
||||
self.slices.clear();
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.key_anchor = None;
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
}
|
||||
@@ -113,9 +121,15 @@ impl Selection {
|
||||
self.set([instance]);
|
||||
self.symbol_part = Some(SymbolPart { instance, path });
|
||||
}
|
||||
/// Is there a key for Align: an object or a guide?
|
||||
/// Is there a key for Align: an object, a guide or an anchor point?
|
||||
pub fn has_key(&self) -> bool {
|
||||
self.key.is_some() || self.key_guide.is_some()
|
||||
self.key.is_some() || self.key_guide.is_some() || self.key_anchor.is_some()
|
||||
}
|
||||
/// Where the key anchor ([`Self::key_anchor`]) is. `None` without one, or when the point is
|
||||
/// gone from its path.
|
||||
pub fn key_anchor_point(&self, doc: &Document) -> Option<vectorcraft_geom::Point> {
|
||||
let (id, (si, ai)) = self.key_anchor?;
|
||||
Some(doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai)?.p)
|
||||
}
|
||||
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
@@ -143,6 +157,9 @@ impl Selection {
|
||||
if self.key == Some(id) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
|
||||
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
@@ -162,6 +179,9 @@ impl Selection {
|
||||
if self.key.is_some_and(|k| ids.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| ids.contains(&k)) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
@@ -271,6 +291,40 @@ impl Selection {
|
||||
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
|
||||
self.key_guide = None;
|
||||
}
|
||||
// A key anchor needs its point on its path and selected as an anchor point (not as a
|
||||
// selected segment's end), with another point selected too: another anchor, or a path
|
||||
// selected whole (Align and Distribute act on path points only). It takes the place of a
|
||||
// key object or key guide.
|
||||
let path_of = |o: &NodeId| found.get(o).and_then(|p| doc.node_at(p)).and_then(|n| n.path_data());
|
||||
let whole_path = |o: &NodeId| !self.anchors.contains_key(o) && path_of(o).is_some_and(|path| path.anchors().next().is_some());
|
||||
// Selected anchor points that are on their paths, counted up to two.
|
||||
let points = || {
|
||||
self.anchors
|
||||
.iter()
|
||||
.flat_map(|(o, set)| {
|
||||
let path = path_of(o);
|
||||
set.iter().filter(move |&&(si, ai)| path.is_some_and(|p| p.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())))
|
||||
})
|
||||
.take(2)
|
||||
.count()
|
||||
};
|
||||
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
|
||||
self.objects.contains(&id)
|
||||
&& !self.segments.contains_key(&id)
|
||||
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
|
||||
&& found
|
||||
.get(&id)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
.and_then(|n| n.path_data())
|
||||
.is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len()))
|
||||
&& (points() >= 2 || self.objects.iter().any(whole_path))
|
||||
});
|
||||
if anchor_kept {
|
||||
self.key = None;
|
||||
self.key_guide = None;
|
||||
} else {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
|
||||
// and the object still in the symbol's art as a path, compound path or type, where neither
|
||||
// it nor a group or layer around it is hidden, locked or a template.
|
||||
@@ -348,6 +402,9 @@ impl Selection {
|
||||
if self.key.is_some_and(|k| gone.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| gone.contains(&k)) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected
|
||||
/// (the art of its sublayers too), anything else is selected itself.
|
||||
|
||||
@@ -162,6 +162,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
|
||||
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
|
||||
BuiltinStyleLibrary { id: "neon-glow", name: "Neon & Glow", make: neon_glow },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -619,6 +620,44 @@ fn status_effects() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Neon & Glow: original multi-layer procedural styles with neon tubes, laser beams, and glowing halos.
|
||||
fn neon_glow() -> Vec<GraphicStyle> {
|
||||
vec![
|
||||
style(
|
||||
"Cyan Neon",
|
||||
vec![S(StrokeLayer { opacity: 0.7, ..round("#00e5ff", 6.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.dropShadow", json!({"mode": "screen", "opacity": 85.0, "x": 0.0, "y": 0.0, "blur": 8.0, "color": "#00e5ff"}))],
|
||||
),
|
||||
GraphicStyle {
|
||||
blend: BlendMode::Screen,
|
||||
..style(
|
||||
"Magenta Laser",
|
||||
vec![S(StrokeLayer { blend: BlendMode::Screen, ..round("#ff007f", 5.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#ff007f"}))],
|
||||
)
|
||||
},
|
||||
style(
|
||||
"Amber Tube",
|
||||
vec![S(StrokeLayer { opacity: 0.8, ..round("#ff8c00", 6.0) }), S(round("#ffea00", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#ff8c00"}))],
|
||||
),
|
||||
style(
|
||||
"Electric Lime",
|
||||
vec![S(StrokeLayer { opacity: 0.75, ..round("#39ff14", 6.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#39ff14"}))],
|
||||
),
|
||||
style(
|
||||
"Pulse Violet",
|
||||
vec![S(StrokeLayer { opacity: 0.75, ..round("#7b2cbf", 5.0) }), S(round("#e0aaff", 1.5))],
|
||||
vec![
|
||||
fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 75.0, "blur": 6.0, "color": "#c77dff", "source": "edge"})),
|
||||
fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#7b2cbf"})),
|
||||
],
|
||||
),
|
||||
style("Cobalt Phosphor", vec![S(round("#0047ab", 6.0)), S(round("#ffffff", 1.5))], vec![fx("blur.gaussian", json!({"radius": 2.0}))]),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -750,4 +789,36 @@ mod tests {
|
||||
let Paint::Gradient(gp) = g.appearance.fill_paint() else { panic!("a gradient") };
|
||||
assert!(gp.swatch.is_none() && gp.gradient.stops.iter().all(|s| s.swatch.is_none() && s.tint == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neon_and_glow_styles_are_defined_with_multi_strokes_and_effects() {
|
||||
let lib = builtin_style_library("neon-glow").expect("neon-glow library exists");
|
||||
assert_eq!(lib.name, "Neon & Glow");
|
||||
assert_eq!(lib.len(), 6);
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Cyan Neon", "Magenta Laser", "Amber Tube", "Electric Lime", "Pulse Violet", "Cobalt Phosphor"]);
|
||||
for g in &lib.styles {
|
||||
let strokes = g.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
|
||||
assert!(strokes >= 2, "{} has {} strokes, expected >= 2", g.name, strokes);
|
||||
assert!(!g.appearance.effects.is_empty(), "{} has effects", g.name);
|
||||
}
|
||||
let cyan = lib.style("Cyan Neon").unwrap();
|
||||
assert_eq!(cyan.appearance.effects[0].id, "stylize.dropShadow");
|
||||
let magenta = lib.style("Magenta Laser").unwrap();
|
||||
assert_eq!(magenta.blend, BlendMode::Screen);
|
||||
let pulse = lib.style("Pulse Violet").unwrap();
|
||||
let pulse_fx: Vec<&str> = pulse.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(pulse_fx, ["stylize.innerGlow", "stylize.outerGlow"]);
|
||||
let cobalt = lib.style("Cobalt Phosphor").unwrap();
|
||||
assert_eq!(cobalt.appearance.effects[0].id, "blur.gaussian");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neon_glow_round_trips_through_vcstyles() {
|
||||
let lib = builtin_style_library("neon-glow").unwrap();
|
||||
let text = write(&lib);
|
||||
assert!(sniff(&text));
|
||||
let read_back = read(&text, "Fallback").unwrap();
|
||||
assert_eq!(*lib, read_back);
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,11 @@ pub(crate) struct ArtBox {
|
||||
/// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art
|
||||
/// holds one at any depth.
|
||||
pub(crate) sliced: bool,
|
||||
/// The box of the regions that the live geometry effects of the clipping paths in the art give
|
||||
/// them ([`crate::hit::set_clip_region`]), and of the instances in the art whose art has such
|
||||
/// regions, each measured by [`Node::reach_bounds_with`]. `None` when nothing in the art has
|
||||
/// one.
|
||||
pub(crate) reshaped: Option<Rect>,
|
||||
}
|
||||
|
||||
/// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`],
|
||||
@@ -562,7 +567,18 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced);
|
||||
}
|
||||
});
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced })
|
||||
let mut reshaped = None;
|
||||
if effects {
|
||||
art.walk(&mut |n| {
|
||||
let b = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if symbols.art(symbol).is_some_and(|a| a.reshaped.is_some()) => n.reach(Some(symbols)),
|
||||
_ if n.clips() => n.children().and_then(|c| c.first()).and_then(|c| crate::hit::reshaped_clip_box(c)),
|
||||
_ => None,
|
||||
};
|
||||
reshaped = vectorcraft_geom::union_opt(reshaped, b.filter(finite));
|
||||
});
|
||||
}
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced, reshaped })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -79,6 +79,21 @@ fn odd_text_reads_as_nothing_without_panicking() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing
|
||||
/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing.
|
||||
#[test]
|
||||
fn a_very_long_expression_reads_as_nothing() {
|
||||
let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1));
|
||||
assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0)));
|
||||
// Long text with no signs still reads.
|
||||
assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0));
|
||||
for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] {
|
||||
assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len());
|
||||
assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len());
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
|
||||
/// or as nothing and does not panic.
|
||||
|
||||
@@ -18,17 +18,18 @@ mod wrap;
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES,
|
||||
WARICHU_SCALE, WarichuAlign,
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
|
||||
CompositeParts,
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
};
|
||||
pub use runs::PATH_LEAD_MAX;
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
|
||||
pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
|
||||
@@ -180,6 +180,18 @@ pub struct CharStyle {
|
||||
/// these characters are drawn in, whatever digits were typed.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub digits: Digits,
|
||||
/// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's
|
||||
/// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points)
|
||||
/// move right by a positive value and left by a negative one, relative to their letters, in
|
||||
/// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`].
|
||||
/// Saved only when not 0.
|
||||
/// <https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549>
|
||||
#[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub diacritic_horizontal: f64,
|
||||
/// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by
|
||||
/// a negative one, as [`Self::diacritic_horizontal`] moves them across.
|
||||
#[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub diacritic_vertical: f64,
|
||||
/// Font height reference (Character panel menu › Show Font Height Options): the height of the
|
||||
/// font that [`Self::size`] measures, the em box by default.
|
||||
#[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -205,6 +217,108 @@ pub struct CharStyle {
|
||||
/// default glyph otherwise. Saved only when set.
|
||||
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
|
||||
pub glyph_alternate: Option<GlyphChoice>,
|
||||
/// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East
|
||||
/// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the
|
||||
/// font's default glyphs. The text keeps its characters. Saved only when set.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub glyph_form: GlyphForm,
|
||||
}
|
||||
|
||||
/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's
|
||||
/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GlyphForm {
|
||||
/// The font's default glyphs.
|
||||
#[default]
|
||||
Default,
|
||||
/// Traditional forms (`trad`).
|
||||
Traditional,
|
||||
/// Expert forms (`expt`).
|
||||
Expert,
|
||||
/// JIS 2004 forms (`jp04`).
|
||||
Jis04,
|
||||
/// JIS 90 forms (`jp90`).
|
||||
Jis90,
|
||||
/// JIS 78 forms (`jp78`).
|
||||
Jis78,
|
||||
/// JIS 83 forms (`jp83`).
|
||||
Jis83,
|
||||
/// Monospaced full-width forms (`fwid`).
|
||||
FullWidth,
|
||||
/// Monospaced half-width forms (`hwid`).
|
||||
HalfWidth,
|
||||
/// Monospaced third-width forms (`twid`).
|
||||
ThirdWidth,
|
||||
/// Monospaced quarter-width forms (`qwid`).
|
||||
QuarterWidth,
|
||||
}
|
||||
|
||||
impl GlyphForm {
|
||||
/// Every form, in menu order, the default last.
|
||||
pub const ALL: [GlyphForm; 11] = [
|
||||
GlyphForm::Traditional,
|
||||
GlyphForm::Expert,
|
||||
GlyphForm::Jis04,
|
||||
GlyphForm::Jis90,
|
||||
GlyphForm::Jis78,
|
||||
GlyphForm::Jis83,
|
||||
GlyphForm::FullWidth,
|
||||
GlyphForm::HalfWidth,
|
||||
GlyphForm::ThirdWidth,
|
||||
GlyphForm::QuarterWidth,
|
||||
GlyphForm::Default,
|
||||
];
|
||||
|
||||
/// The name files and commands give this form (as it is saved).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
GlyphForm::Default => "default",
|
||||
GlyphForm::Traditional => "traditional",
|
||||
GlyphForm::Expert => "expert",
|
||||
GlyphForm::Jis04 => "jis04",
|
||||
GlyphForm::Jis90 => "jis90",
|
||||
GlyphForm::Jis78 => "jis78",
|
||||
GlyphForm::Jis83 => "jis83",
|
||||
GlyphForm::FullWidth => "fullWidth",
|
||||
GlyphForm::HalfWidth => "halfWidth",
|
||||
GlyphForm::ThirdWidth => "thirdWidth",
|
||||
GlyphForm::QuarterWidth => "quarterWidth",
|
||||
}
|
||||
}
|
||||
|
||||
/// The form [`GlyphForm::id`] names; `None` for any other name.
|
||||
pub fn from_id(id: &str) -> Option<GlyphForm> {
|
||||
GlyphForm::ALL.into_iter().find(|f| f.id() == id)
|
||||
}
|
||||
|
||||
/// The OpenType feature that draws this form; `None` for the default glyphs.
|
||||
pub fn feature(self) -> Option<&'static [u8; 4]> {
|
||||
Some(match self {
|
||||
GlyphForm::Default => return None,
|
||||
GlyphForm::Traditional => b"trad",
|
||||
GlyphForm::Expert => b"expt",
|
||||
GlyphForm::Jis04 => b"jp04",
|
||||
GlyphForm::Jis90 => b"jp90",
|
||||
GlyphForm::Jis78 => b"jp78",
|
||||
GlyphForm::Jis83 => b"jp83",
|
||||
GlyphForm::FullWidth => b"fwid",
|
||||
GlyphForm::HalfWidth => b"hwid",
|
||||
GlyphForm::ThirdWidth => b"twid",
|
||||
GlyphForm::QuarterWidth => b"qwid",
|
||||
})
|
||||
}
|
||||
|
||||
/// Is this one of the monospaced width forms (`fwid`, `hwid`, `twid`, `qwid`)? A font may
|
||||
/// draw them with other glyphs (`GSUB`) or with other widths for the same glyphs (`GPOS`), and
|
||||
/// they set the characters on a fixed width, so Proportional Metrics (`palt`) is not applied
|
||||
/// with them.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/features_fj#tag-fwid>
|
||||
pub fn is_width(self) -> bool {
|
||||
matches!(self, GlyphForm::FullWidth | GlyphForm::HalfWidth | GlyphForm::ThirdWidth | GlyphForm::QuarterWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
@@ -451,6 +565,10 @@ pub const MAX_AKI: f64 = 1000.0;
|
||||
/// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink.
|
||||
pub const MAX_TSUME: f64 = 100.0;
|
||||
|
||||
/// The largest Adjust Horizontal or Vertical Diacritic Position either way
|
||||
/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em.
|
||||
pub const MAX_DIACRITIC_POSITION: f64 = 1000.0;
|
||||
|
||||
/// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]).
|
||||
pub const WARICHU_LINES: std::ops::RangeInclusive<u8> = 1..=6;
|
||||
|
||||
@@ -582,10 +700,13 @@ impl Default for CharStyle {
|
||||
warichu_align: WarichuAlign::Auto,
|
||||
small_caps: None,
|
||||
digits: Digits::Default,
|
||||
diacritic_horizontal: 0.0,
|
||||
diacritic_vertical: 0.0,
|
||||
font_height_reference: FontHeightReference::EmBox,
|
||||
no_break: false,
|
||||
language: None,
|
||||
glyph_alternate: None,
|
||||
glyph_form: GlyphForm::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,7 +725,8 @@ impl CharStyle {
|
||||
/// same way. The Warichu Settings Lines and Scale
|
||||
/// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to
|
||||
/// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its
|
||||
/// own units.
|
||||
/// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within
|
||||
/// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0.
|
||||
pub fn keep_dimensions_in_range(&mut self) {
|
||||
let default = Self::default();
|
||||
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
|
||||
@@ -620,6 +742,9 @@ impl CharStyle {
|
||||
self.aki_left = aki(self.aki_left);
|
||||
self.aki_right = aki(self.aki_right);
|
||||
self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) };
|
||||
let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) };
|
||||
self.diacritic_horizontal = diacritic(self.diacritic_horizontal);
|
||||
self.diacritic_vertical = diacritic(self.diacritic_vertical);
|
||||
self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end());
|
||||
self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) };
|
||||
self.warichu_scale =
|
||||
@@ -691,6 +816,15 @@ impl CharStyle {
|
||||
self.position = self.position.in_range();
|
||||
self.small_caps = self.small_caps.map(small_caps_in_range);
|
||||
}
|
||||
/// Sets the East Asian glyph form ([`CharStyle::glyph_form`]). A form other than the default
|
||||
/// also takes away the character's glyph choice ([`CharStyle::glyph_alternate`]), which would
|
||||
/// otherwise keep drawing its own glyph; the default form keeps it.
|
||||
pub fn set_glyph_form(&mut self, form: GlyphForm) {
|
||||
self.glyph_form = form;
|
||||
if form != GlyphForm::Default {
|
||||
self.glyph_alternate = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
|
||||
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
|
||||
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
|
||||
//! family; the layout sets each character in its class's font.
|
||||
//! of their own, sized, raised and scaled against it). Custom character sets give characters the
|
||||
//! user picks a font of their own too, ahead of their class; of two sets that list a character,
|
||||
//! the later one sets it. Type set in a composite font names it as its family; the layout sets each
|
||||
//! character in its set's or its class's font.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
//! Which characters fall in which class, the ranges, the limits and the defaults are VectorCraft's
|
||||
//! own.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -179,12 +184,76 @@ impl CompositeParts {
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom character set of a composite font: characters chosen by the user, set in a part of
|
||||
/// their own instead of their class's part.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CustomCharSet {
|
||||
/// The set's name, unique in its composite font in any case.
|
||||
pub name: String,
|
||||
/// The set's characters, each once, in the order they were added.
|
||||
#[serde(default)]
|
||||
pub characters: String,
|
||||
/// The font, style, size, baseline and scales its characters take.
|
||||
#[serde(flatten)]
|
||||
pub part: CompositePart,
|
||||
}
|
||||
|
||||
impl CustomCharSet {
|
||||
/// An empty set named `name`, its characters set in `part`.
|
||||
pub fn new(name: impl Into<String>, part: CompositePart) -> Self {
|
||||
Self { name: name.into(), characters: String::new(), part }
|
||||
}
|
||||
|
||||
/// Whether `c` can be in a custom character set: not a control character, and in the Basic
|
||||
/// Multilingual Plane (U+0000 to U+FFFF).
|
||||
pub fn takes(c: char) -> bool {
|
||||
!c.is_control() && (c as u32) <= 0xFFFF
|
||||
}
|
||||
|
||||
/// The character a Unicode code names: hexadecimal digits, optionally after `U+` or `0x`
|
||||
/// (`3042`, `U+3042`). `None` for anything else or a code [`Self::takes`] refuses.
|
||||
pub fn char_from_code(code: &str) -> Option<char> {
|
||||
let code = code.trim();
|
||||
let hex = ["U+", "u+", "0x", "0X"].iter().find_map(|p| code.strip_prefix(p)).unwrap_or(code);
|
||||
if hex.is_empty() || hex.len() > 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|&c| Self::takes(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a composite font sets a character: the part of one of its six classes, or the part of
|
||||
/// one of its custom character sets (an index into [`CompositeFont::custom`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum CompositeClass {
|
||||
Fixed(CharClass),
|
||||
Custom(usize),
|
||||
}
|
||||
|
||||
/// The custom character set each character of a composite font's sets falls in
|
||||
/// ([`CompositeFont::classes`]): the last set that lists it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CompositeClasses {
|
||||
custom: std::collections::HashMap<char, usize>,
|
||||
}
|
||||
|
||||
impl CompositeClasses {
|
||||
/// Where the composite font sets `c`: the last custom set that lists it, else its class.
|
||||
pub fn of(&self, c: char) -> CompositeClass {
|
||||
self.custom.get(&c).map_or(CompositeClass::Fixed(CharClass::of(c)), |&i| CompositeClass::Custom(i))
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
|
||||
/// that type set in it names.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CompositeFont {
|
||||
pub name: String,
|
||||
pub parts: CompositeParts,
|
||||
/// Custom character sets, checked before the classes. A character two sets list is set in the
|
||||
/// later set's part.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub custom: Vec<CustomCharSet>,
|
||||
}
|
||||
|
||||
/// The size a part can take, in percent of the type's size.
|
||||
@@ -197,11 +266,40 @@ pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
|
||||
pub const COMPOSITE_NAME_MAX: usize = 255;
|
||||
/// The most composite fonts a document or a file keeps.
|
||||
pub const COMPOSITE_FONTS_MAX: usize = 256;
|
||||
/// The most custom character sets a composite font keeps.
|
||||
pub const CUSTOM_SETS_MAX: usize = 64;
|
||||
/// The most characters a custom character set keeps.
|
||||
pub const CUSTOM_CHARS_MAX: usize = 8192;
|
||||
|
||||
impl CompositeFont {
|
||||
/// A composite font named `name` setting every class in `font` and `style`.
|
||||
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
|
||||
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
|
||||
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)), custom: Vec::new() }
|
||||
}
|
||||
|
||||
/// The part that sets the characters of `class`, `None` for a custom set the font doesn't have.
|
||||
pub fn part(&self, class: CompositeClass) -> Option<&CompositePart> {
|
||||
match class {
|
||||
CompositeClass::Fixed(c) => Some(self.parts.get(c)),
|
||||
CompositeClass::Custom(i) => self.custom.get(i).map(|s| &s.part),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where this font sets character `c`: the last custom set that lists it, else its class. For
|
||||
/// many characters, [`Self::classes`] looks each up faster.
|
||||
pub fn class_of(&self, c: char) -> CompositeClass {
|
||||
self.custom.iter().rposition(|s| s.characters.contains(c)).map_or(CompositeClass::Fixed(CharClass::of(c)), CompositeClass::Custom)
|
||||
}
|
||||
|
||||
/// The custom set each character of this font's sets falls in, to look up many characters.
|
||||
pub fn classes(&self) -> CompositeClasses {
|
||||
let mut custom = std::collections::HashMap::new();
|
||||
for (i, s) in self.custom.iter().enumerate() {
|
||||
for c in s.characters.chars() {
|
||||
custom.insert(c, i);
|
||||
}
|
||||
}
|
||||
CompositeClasses { custom }
|
||||
}
|
||||
|
||||
/// Do `a` and `b` name the same composite font: equal in any case?
|
||||
@@ -223,36 +321,50 @@ impl CompositeFont {
|
||||
}
|
||||
|
||||
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
|
||||
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
|
||||
/// that has none.
|
||||
/// part without a font, a value out of its range, a scale or Scale at Center on a class that
|
||||
/// has none, or a custom character set [`Self::check_custom`] refuses.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
|
||||
return Err(format!("`{}` can't name a composite font", self.name));
|
||||
}
|
||||
for class in CharClass::ALL {
|
||||
let p = self.parts.get(class);
|
||||
let k = class.key();
|
||||
if p.font.trim().is_empty() {
|
||||
return Err(format!("{k}: give a font"));
|
||||
check_part(self.parts.get(class), class.key(), class.scales(), class == CharClass::Kana)?;
|
||||
}
|
||||
self.check_custom()
|
||||
}
|
||||
|
||||
/// Why this font's custom character sets can't be used, if they can't: more than
|
||||
/// [`CUSTOM_SETS_MAX`], a name [`Self::clean_name`] refuses or two sets share (in any case), a
|
||||
/// character [`CustomCharSet::takes`] refuses or a set lists twice, more than
|
||||
/// [`CUSTOM_CHARS_MAX`] characters in a set, or a part [`Self::check`] would refuse. A set's
|
||||
/// characters can be scaled across and up; only kana are scaled at the center.
|
||||
pub fn check_custom(&self) -> Result<(), String> {
|
||||
if self.custom.len() > CUSTOM_SETS_MAX {
|
||||
return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for s in &self.custom {
|
||||
let name = &s.name;
|
||||
if Self::clean_name(name).as_deref() != Some(name.as_str()) {
|
||||
return Err(format!("`{name}` can't name a character set"));
|
||||
}
|
||||
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
|
||||
if !within(p.size, &COMPOSITE_SIZE) {
|
||||
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
|
||||
if !names.insert(name.to_lowercase()) {
|
||||
return Err(format!("two character sets are named `{name}`"));
|
||||
}
|
||||
if !within(p.baseline, &COMPOSITE_BASELINE) {
|
||||
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
|
||||
}
|
||||
for v in [p.h_scale, p.v_scale] {
|
||||
if !within(v, &COMPOSITE_SCALE) {
|
||||
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for (n, c) in s.characters.chars().enumerate() {
|
||||
if n == CUSTOM_CHARS_MAX {
|
||||
return Err(format!("`{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters"));
|
||||
}
|
||||
if v != 100.0 && !class.scales() {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
let code = c as u32;
|
||||
if !CustomCharSet::takes(c) {
|
||||
return Err(format!("`{name}`: U+{code:04X} is a control character or past U+FFFF"));
|
||||
}
|
||||
if !seen.insert(c) {
|
||||
return Err(format!("`{name}`: U+{code:04X} is listed twice"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && class != CharClass::Kana {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
check_part(&s.part, name, true, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -264,9 +376,41 @@ impl CompositeFont {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
let mut kept: Vec<CompositeFont> =
|
||||
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
|
||||
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
|
||||
kept.retain(|f| f.part_fonts().all(|font| !names.contains(&font.to_lowercase())));
|
||||
(kept.len() != fonts.len()).then_some(kept)
|
||||
}
|
||||
|
||||
/// The fonts of the parts, each class's then each custom set's.
|
||||
pub fn part_fonts(&self) -> impl Iterator<Item = &str> {
|
||||
CharClass::ALL.into_iter().map(|c| self.parts.get(c).font.as_str()).chain(self.custom.iter().map(|s| s.part.font.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why part `p` (of the class or set named `k`) can't be used, if it can't: no font, a value out
|
||||
/// of its range, a scale when `scales` is false, or Scale at Center when `center` is false.
|
||||
fn check_part(p: &CompositePart, k: &str, scales: bool, center: bool) -> Result<(), String> {
|
||||
if p.font.trim().is_empty() {
|
||||
return Err(format!("{k}: give a font"));
|
||||
}
|
||||
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
|
||||
if !within(p.size, &COMPOSITE_SIZE) {
|
||||
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
|
||||
}
|
||||
if !within(p.baseline, &COMPOSITE_BASELINE) {
|
||||
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
|
||||
}
|
||||
for v in [p.h_scale, p.v_scale] {
|
||||
if !within(v, &COMPOSITE_SCALE) {
|
||||
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
|
||||
}
|
||||
if v != 100.0 && !scales {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && !center {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -341,4 +485,81 @@ mod tests {
|
||||
spaced.name = " Mixed".into();
|
||||
assert!(spaced.check().is_err());
|
||||
}
|
||||
|
||||
/// A character a custom set lists falls in that set ahead of its class, the later of two sets
|
||||
/// that list it wins, and the quick lookup agrees with the one-character one.
|
||||
#[test]
|
||||
fn custom_sets_take_their_characters_before_the_classes() {
|
||||
let mut f = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
let mut a = CustomCharSet::new("Marks", CompositePart::new("Source Sans 3", "Bold"));
|
||||
a.characters = "※A".into();
|
||||
let mut b = CustomCharSet::new("Letters", CompositePart::new("Inter", "Italic"));
|
||||
b.characters = "AB".into();
|
||||
f.custom = vec![a, b];
|
||||
let classes = f.classes();
|
||||
for (c, want) in [
|
||||
('※', CompositeClass::Custom(0)),
|
||||
('A', CompositeClass::Custom(1)),
|
||||
('B', CompositeClass::Custom(1)),
|
||||
('C', CompositeClass::Fixed(CharClass::Roman)),
|
||||
('漢', CompositeClass::Fixed(CharClass::Kanji)),
|
||||
] {
|
||||
assert_eq!(f.class_of(c), want, "{c:?}");
|
||||
assert_eq!(classes.of(c), want, "{c:?}");
|
||||
}
|
||||
assert_eq!(f.part(CompositeClass::Custom(0)).map(|p| p.style.as_str()), Some("Bold"));
|
||||
assert_eq!(f.part(CompositeClass::Custom(2)), None);
|
||||
assert_eq!(f.check(), Ok(()));
|
||||
// Read and written with the part's fields beside the set's name and characters.
|
||||
let json = serde_json::to_value(&f).unwrap();
|
||||
assert_eq!(json["custom"][1]["characters"], "AB");
|
||||
assert_eq!(json["custom"][1]["style"], "Italic");
|
||||
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
|
||||
// A font without sets is written as before.
|
||||
assert!(serde_json::to_value(CompositeFont::new("Plain", "Inter", "Regular")).unwrap().get("custom").is_none());
|
||||
}
|
||||
|
||||
/// Set names, characters and limits are checked; sets scale like Roman letters.
|
||||
#[test]
|
||||
fn custom_sets_check_their_names_and_characters() {
|
||||
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
let with = |sets: Vec<(&str, &str)>, edit: fn(&mut CompositePart)| {
|
||||
let mut f = ok.clone();
|
||||
for (name, chars) in sets {
|
||||
let mut s = CustomCharSet::new(name, CompositePart::new("Inter", "Regular"));
|
||||
s.characters = chars.into();
|
||||
edit(&mut s.part);
|
||||
f.custom.push(s);
|
||||
}
|
||||
f.check()
|
||||
};
|
||||
let none = |_: &mut CompositePart| {};
|
||||
assert_eq!(with(vec![("Empty", "")], none), Ok(()));
|
||||
assert_eq!(with(vec![("Wide", "AB")], |p| p.h_scale = 80.0), Ok(()));
|
||||
assert!(with(vec![("Wide", "AB")], |p| p.scale_at_center = true).is_err());
|
||||
assert!(with(vec![("Big", "A")], |p| p.size = 401.0).is_err());
|
||||
assert!(with(vec![("Same", "A"), ("same", "B")], none).unwrap_err().contains("two character sets"));
|
||||
assert!(with(vec![(" Pad", "A")], none).is_err());
|
||||
assert!(with(vec![("Twice", "ABA")], none).unwrap_err().contains("U+0041 is listed twice"));
|
||||
assert!(with(vec![("Tab", "A\t")], none).unwrap_err().contains("U+0009"));
|
||||
assert!(with(vec![("Astral", "𠀋")], none).unwrap_err().contains("U+2000B"));
|
||||
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(CUSTOM_CHARS_MAX + 1).collect();
|
||||
let mut f = ok.clone();
|
||||
f.custom.push(CustomCharSet { name: "Many".into(), characters: many, part: CompositePart::new("Inter", "Regular") });
|
||||
assert!(f.check().unwrap_err().contains("at most"));
|
||||
let mut f = ok.clone();
|
||||
f.custom = (0..=CUSTOM_SETS_MAX).map(|i| CustomCharSet::new(format!("S{i}"), CompositePart::new("Inter", "Regular"))).collect();
|
||||
assert!(f.check().is_err());
|
||||
}
|
||||
|
||||
/// Codes are hexadecimal, with or without `U+` or `0x`, inside the Basic Multilingual Plane.
|
||||
#[test]
|
||||
fn custom_set_codes_name_characters() {
|
||||
assert_eq!(CustomCharSet::char_from_code("3042"), Some('あ'));
|
||||
assert_eq!(CustomCharSet::char_from_code(" U+203B "), Some('※'));
|
||||
assert_eq!(CustomCharSet::char_from_code("0x41"), Some('A'));
|
||||
for bad in ["", "U+", "zz", "20000B", "D800", "0009", "1F600", "1234567", "+41"] {
|
||||
assert_eq!(CustomCharSet::char_from_code(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -352,7 +352,10 @@ impl TextObject {
|
||||
}
|
||||
/// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its
|
||||
/// centre bracket dragged across the path): the path runs the other way and the brackets swap
|
||||
/// ends, so the type keeps its stretch of the path. False, changing nothing, for other type.
|
||||
/// ends, so the type keeps its stretch of the path. Type that starts before an open path's start
|
||||
/// ([`TextKind::path_text_start`]) starts at its start bracket after the flip: the part of its
|
||||
/// span before the path's start would come after the path's end. False, changing nothing, for
|
||||
/// other type.
|
||||
pub fn flip_on_path(&mut self) -> bool {
|
||||
let Some((s, e)) = self.kind.path_span() else { return false };
|
||||
let TextKind::OnPath { path, start, end } = &mut self.kind else { return false };
|
||||
@@ -508,6 +511,8 @@ impl crate::Document {
|
||||
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
|
||||
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
|
||||
st.tsume = num("tsume").unwrap_or(st.tsume);
|
||||
st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal);
|
||||
st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical);
|
||||
st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap);
|
||||
st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale);
|
||||
st.keep_dimensions_in_range();
|
||||
@@ -534,6 +539,8 @@ impl crate::Document {
|
||||
("akiLeft", Some(st.aki_left)),
|
||||
("akiRight", Some(st.aki_right)),
|
||||
("tsume", Some(st.tsume)),
|
||||
("diacriticHorizontal", Some(st.diacritic_horizontal)),
|
||||
("diacriticVertical", Some(st.diacritic_vertical)),
|
||||
("leading", st.leading),
|
||||
];
|
||||
for (k, v) in kept {
|
||||
|
||||
@@ -17,22 +17,52 @@ pub enum Justify {
|
||||
JustifyAll,
|
||||
}
|
||||
|
||||
/// Paragraph composer (Paragraph panel menu): how lines are broken.
|
||||
/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts
|
||||
/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South
|
||||
/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set
|
||||
/// here, and are what documents saved before the four composers existed use. The `Standard`
|
||||
/// composers break lines the same way but set a complex script glyph by glyph as the font maps its
|
||||
/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's
|
||||
/// glyphs on Latin character codes (legacy ANSI Indic fonts) need.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Composer {
|
||||
/// Break each line as soon as it is full.
|
||||
/// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full.
|
||||
SingleLine,
|
||||
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
|
||||
/// spacing, ragged lines an even rag.
|
||||
/// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph
|
||||
/// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag.
|
||||
#[default]
|
||||
EveryLine,
|
||||
/// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped.
|
||||
StandardSingleLine,
|
||||
/// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped.
|
||||
StandardEveryLine,
|
||||
}
|
||||
|
||||
impl Composer {
|
||||
fn is_default(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
/// Does this composer break lines one at a time (as opposed to a total fit)?
|
||||
pub fn is_single_line(self) -> bool {
|
||||
matches!(self, Self::SingleLine | Self::StandardSingleLine)
|
||||
}
|
||||
|
||||
/// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])?
|
||||
pub fn shapes_complex_scripts(self) -> bool {
|
||||
matches!(self, Self::SingleLine | Self::EveryLine)
|
||||
}
|
||||
|
||||
/// The same shaping with the other line breaking (`single_line`: one line at a time).
|
||||
pub fn with_breaking(self, single_line: bool) -> Self {
|
||||
match (single_line, self.shapes_complex_scripts()) {
|
||||
(true, true) => Self::SingleLine,
|
||||
(true, false) => Self::StandardSingleLine,
|
||||
(false, true) => Self::EveryLine,
|
||||
(false, false) => Self::StandardEveryLine,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic
|
||||
|
||||
@@ -93,8 +93,10 @@ pub enum TextKind {
|
||||
/// Area type flowed inside `frame` (document coordinates, untransformed by `xf`).
|
||||
Area { frame: PathData },
|
||||
/// Type on a path, flowing from its start bracket `start` to its end bracket `end` (0..1 of the
|
||||
/// path length; no `end`: the end of the path, or once round a closed path). See
|
||||
/// [`TextKind::path_span`].
|
||||
/// path length; no `end`: the end of the path, or once round a closed path). On an open path
|
||||
/// `start` may be below 0: the type starts that far before the path's start, and the characters
|
||||
/// whose middle falls before the path's start are not drawn ([`TextKind::path_text_start`]).
|
||||
/// See [`TextKind::path_span`].
|
||||
OnPath {
|
||||
path: PathData,
|
||||
start: f64,
|
||||
@@ -117,8 +119,22 @@ impl TextKind {
|
||||
(s, end.map_or(1.0, |e| fraction(e).max(s)))
|
||||
})
|
||||
}
|
||||
/// Where type on a path's text starts, as a fraction of its path's length: its start bracket
|
||||
/// ([`Self::path_span`]), or on an open path a start before the path's start (below 0, at most
|
||||
/// [`PATH_LEAD_MAX`] path lengths before it). None for other type.
|
||||
pub fn path_text_start(&self) -> Option<f64> {
|
||||
let TextKind::OnPath { path, start, .. } = self else { return None };
|
||||
if !path.is_closed() && start.is_finite() && *start < 0.0 { Some(start.max(-PATH_LEAD_MAX)) } else { self.path_span().map(|(s, _)| s) }
|
||||
}
|
||||
/// Does type on an open path start before its path's start ([`Self::path_text_start`])?
|
||||
pub fn starts_before_path(&self) -> bool {
|
||||
self.path_text_start().is_some_and(|s| s < 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far before its path's start type on an open path may start, in lengths of the path.
|
||||
pub const PATH_LEAD_MAX: f64 = 1e6;
|
||||
|
||||
/// Move anchors `refs` of `path`, in text space, by `d` in document space (`to_text`: the
|
||||
/// document → text map). False when an anchor doesn't exist.
|
||||
pub(super) fn move_anchors(path: &mut PathData, to_text: Affine, refs: &[(usize, usize)], d: Vec2) -> bool {
|
||||
|
||||
@@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() {
|
||||
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
|
||||
}
|
||||
|
||||
/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0,
|
||||
/// each on its own; styles written before them read as 0, and a value out of range from a file is
|
||||
/// kept within one em either way.
|
||||
#[test]
|
||||
fn diacritic_positions_are_saved_only_when_set() {
|
||||
let st = CharStyle::default();
|
||||
assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0));
|
||||
let saved = serde_json::to_value(&st).unwrap();
|
||||
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
|
||||
for set in [
|
||||
CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() },
|
||||
] {
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal);
|
||||
assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical);
|
||||
assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0);
|
||||
assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0);
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
|
||||
}
|
||||
let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION));
|
||||
let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION));
|
||||
// A character style from a file is kept in range the same way.
|
||||
let mut d = crate::Document::new(100.0, 100.0);
|
||||
let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000});
|
||||
d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
|
||||
d.keep_type_values_in_range();
|
||||
let kept = |key: &str| d.char_styles[0].attrs[key].as_f64();
|
||||
assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION)));
|
||||
}
|
||||
|
||||
/// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a
|
||||
/// value out of range from a file, in a run or a character style, is kept from 0 to 100.
|
||||
#[test]
|
||||
@@ -563,6 +599,33 @@ fn area_anchors_move_in_document_space() {
|
||||
assert_eq!(t, before);
|
||||
}
|
||||
|
||||
/// Type on an open path may start before the path's start: the start is kept, saved and read back,
|
||||
/// while the start bracket stays at the path's start. On a closed path, and for a start that is not
|
||||
/// finite, the start is the start bracket as before.
|
||||
#[test]
|
||||
fn type_on_an_open_path_starts_before_the_path() {
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0)];
|
||||
let on = |closed: bool, start: f64| TextKind::OnPath {
|
||||
path: PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, closed)]),
|
||||
start,
|
||||
end: None,
|
||||
};
|
||||
let open = on(false, -0.25);
|
||||
assert_eq!(open.path_text_start(), Some(-0.25));
|
||||
assert!(open.starts_before_path());
|
||||
assert_eq!(open.path_span(), Some((0.0, 1.0)));
|
||||
let saved = serde_json::to_value(&open).unwrap();
|
||||
assert_eq!(saved["start"], -0.25);
|
||||
assert_eq!(serde_json::from_value::<TextKind>(saved).unwrap(), open);
|
||||
assert_eq!(on(false, -1e9).path_text_start(), Some(-PATH_LEAD_MAX));
|
||||
assert_eq!(on(false, f64::NEG_INFINITY).path_text_start(), Some(0.0));
|
||||
assert_eq!(on(false, 0.25).path_text_start(), Some(0.25));
|
||||
assert!(!on(false, 0.0).starts_before_path());
|
||||
assert_eq!(on(true, -0.25).path_text_start(), Some(0.0));
|
||||
assert!(!on(true, -0.25).starts_before_path());
|
||||
assert_eq!(TextKind::Point.path_text_start(), None);
|
||||
}
|
||||
|
||||
/// Builds from before [`Justify::Auto`] read new type's alignment as Left or Right (and ignore
|
||||
/// `justify_auto`); this build reads Auto back.
|
||||
#[test]
|
||||
|
||||
@@ -156,7 +156,12 @@ impl Unit {
|
||||
/// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away
|
||||
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
|
||||
/// percentage on its own (`50%`) reads as nothing.
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs reads as nothing.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(s, self).filter(|v| v.is_finite())
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
@@ -207,6 +212,9 @@ impl Unit {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
|
||||
const MAX_MEASURE_OPERATORS: usize = 128;
|
||||
|
||||
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
|
||||
|
||||
+55
-13
@@ -27,7 +27,9 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
|
||||
|
||||
use crate::distort::{transform_move, transform_offsets};
|
||||
use crate::group::{has_own_paint, paints};
|
||||
use crate::reshape::{as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
|
||||
use crate::reshape::{
|
||||
as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
|
||||
};
|
||||
use crate::{
|
||||
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape,
|
||||
@@ -199,8 +201,19 @@ fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option<u64> {
|
||||
}
|
||||
|
||||
/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art
|
||||
/// holds an instance of one of them at any depth.
|
||||
/// holds an instance of one of them at any depth, in the art of enabled opacity masks too.
|
||||
fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
fn used(n: &Node, names: &mut Vec<String>) {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) {
|
||||
used(&m.art, names);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
used(c, names);
|
||||
}
|
||||
}
|
||||
let mut out: HashSet<String> = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect();
|
||||
if out.is_empty() {
|
||||
return out;
|
||||
@@ -211,11 +224,7 @@ fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
.filter(|s| !out.contains(&s.name))
|
||||
.map(|s| {
|
||||
let mut names = vec![];
|
||||
s.art.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
used(&s.art, &mut names);
|
||||
(s.name.as_str(), names)
|
||||
})
|
||||
.collect();
|
||||
@@ -233,14 +242,22 @@ fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces
|
||||
/// by its placed art? False outside it, and for objects the export does not write ([`unwritten`]).
|
||||
/// by its placed art, in the art of its enabled opacity masks too? False outside it, and for
|
||||
/// objects the export does not write ([`unwritten`]).
|
||||
fn holds_placed_symbol(n: &Node) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>) -> bool {
|
||||
placed_symbol_in(n, true)
|
||||
}
|
||||
|
||||
/// [`holds_placed_symbol`], with the art of `n`'s own opacity mask left out unless `own_mask`
|
||||
/// (the art of the masks inside `n` is always looked into).
|
||||
fn placed_symbol_in(n: &Node, own_mask: bool) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>, own_mask: bool) -> bool {
|
||||
!unwritten(n)
|
||||
&& (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols))))
|
||||
|| (own_mask && !n.is_ruler_guide() && n.extras().mask.as_ref().is_some_and(|m| !m.disabled && walk(&m.art, symbols, true)))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols, true))))
|
||||
}
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols)))
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols, own_mask)))
|
||||
}
|
||||
|
||||
/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it
|
||||
@@ -278,8 +295,29 @@ fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> {
|
||||
Some((g, most))
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged).
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged), and the art of its enabled opacity
|
||||
/// mask baked one level deeper when it holds instances that [`bake_document_placing_symbols`]
|
||||
/// places ([`holds_placed_symbol`]), so the mask masks with the art the instances draw. The art is
|
||||
/// baked only while the object baked from `n` still carries `n`'s mask art; art already baked
|
||||
/// with `n`'s recolored or placed form is not baked again. A ruler guide's mask stays as it is.
|
||||
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let out = bake_object(d, n);
|
||||
let Some(mask) = n.extras().mask.as_ref().filter(|m| !m.disabled && !n.is_ruler_guide() && !unwritten(n) && holds_placed_symbol(&m.art)) else {
|
||||
return out;
|
||||
};
|
||||
let changed = out.is_some();
|
||||
let mut out = out.unwrap_or_else(|| n.clone());
|
||||
let Some(slot) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|s| Arc::ptr_eq(&s.art, &mask.art)) else {
|
||||
return changed.then_some(out);
|
||||
};
|
||||
let Some(art) = one_deeper(|| bake_node(d, &mask.art)) else { return changed.then_some(out) };
|
||||
slot.art = Arc::new(art);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged); its opacity mask is left to
|
||||
/// [`bake_node`].
|
||||
fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// Inside an object the export leaves out, effects are baked but no instance is placed.
|
||||
if !UNWRITTEN.with(|c| c.get()) && unwritten(n) {
|
||||
UNWRITTEN.with(|c| c.set(true));
|
||||
@@ -289,7 +327,8 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
|
||||
// A ruler guide draws nothing and stays as it is, last in its layer.
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || holds_placed_symbol(n)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
// An object whose own mask's art alone holds placed instances stays as it is here.
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || placed_symbol_in(n, false)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
|
||||
@@ -652,6 +691,9 @@ fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
/// them. `None` when no type stays type.
|
||||
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
|
||||
if !clipping {
|
||||
paint_type_clip(Some(d), n);
|
||||
}
|
||||
let clips = n.clips();
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for (i, c) in ch.iter_mut().enumerate() {
|
||||
|
||||
@@ -1169,6 +1169,74 @@ fn placing_symbols_reaches_the_art_of_nested_instances() {
|
||||
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900));
|
||||
}
|
||||
|
||||
/// A 10 pt square with id `id`, masked by `art` (the mask enabled unless `disabled`).
|
||||
fn masked_square(id: u64, art: Node, disabled: bool) -> Node {
|
||||
let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(art, false);
|
||||
mask.disabled = disabled;
|
||||
n.extras_mut().mask = Some(Box::new(mask));
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether the art of `n`'s opacity mask is still a symbol instance, and its bounds when it is not.
|
||||
fn mask_art(n: &Node) -> (bool, Option<Rect>) {
|
||||
let art = &n.extras().mask.as_ref().unwrap_or_else(|| panic!("node {:?} has a mask", n.id)).art;
|
||||
(matches!(art.kind, NodeKind::SymbolInstance { .. }), art.geometric_bounds())
|
||||
}
|
||||
|
||||
/// An instance in the art of an enabled opacity mask is placed and baked like any other, so the
|
||||
/// mask masks with the art the instance draws, and the masked object stays as it is (a clipping
|
||||
/// path stays one); one in a disabled mask, in the mask of an object the export leaves out, or in
|
||||
/// a ruler guide's mask, stays as it is.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_instances_in_opacity_masks() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(masked_square(700, instance(900, "S", Affine::IDENTITY), false));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 1, masked_square(701, instance(901, "S", Affine::IDENTITY), true)).unwrap();
|
||||
let mut hidden = masked_square(702, instance(902, "S", Affine::IDENTITY), false);
|
||||
hidden.visible = false;
|
||||
d.insert(Some(layer), 2, hidden).unwrap();
|
||||
let mut clipping = masked_square(703, instance(903, "S", Affine::IDENTITY), false);
|
||||
if let NodeKind::Path { clipping: c, .. } = &mut clipping.kind {
|
||||
*c = true;
|
||||
}
|
||||
d.insert(Some(layer), 3, Node::group(NodeId(704), vec![Arc::new(clipping)])).unwrap();
|
||||
let mut guide = Node::new(NodeId(705), NodeKind::RulerGuide { vertical: false, pos: 5.0, artboard: None });
|
||||
guide.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(instance(905, "S", Affine::IDENTITY), false)));
|
||||
d.insert(Some(layer), 4, guide).unwrap();
|
||||
add_symbol(&mut d, "S", moved_square(800));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
for id in [700, 703] {
|
||||
let (still, b) = mask_art(out.node(NodeId(id)).unwrap());
|
||||
assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{id}: {b:?}");
|
||||
}
|
||||
assert!(matches!(out.node(NodeId(703)).unwrap().kind, NodeKind::Path { clipping: true, .. }), "the clipping path stays one");
|
||||
assert!(mask_art(out.node(NodeId(701)).unwrap()).0, "a disabled mask's instance stays");
|
||||
assert!(mask_art(out.node(NodeId(702)).unwrap()).0, "a hidden object's mask's instance stays");
|
||||
assert!(mask_art(out.node(NodeId(705)).unwrap()).0, "a ruler guide's mask's instance stays");
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance only in an opacity mask's art is placed too, and the
|
||||
/// instance in its mask is placed with it.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_instances_in_the_masks_of_symbol_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "Inner", moved_square(800));
|
||||
add_symbol(&mut d, "Outer", masked_square(803, instance(802, "Inner", Affine::IDENTITY), false));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
assert!(!is_instance(&out, 900), "the outer instance is placed");
|
||||
let mut found = None;
|
||||
out.node(NodeId(900)).unwrap().walk(&mut |n| {
|
||||
if n.id == NodeId(803) {
|
||||
found = Some(mask_art(n));
|
||||
}
|
||||
});
|
||||
let (still, b) = found.unwrap_or_else(|| panic!("the masked square is in the placed art"));
|
||||
assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{b:?}");
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export
|
||||
/// ends.
|
||||
#[test]
|
||||
|
||||
@@ -182,50 +182,50 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[]}),
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}),
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
"Rotate (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
"convertToShape.rectangle",
|
||||
@@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.transform",
|
||||
"Transform…",
|
||||
DT,
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
|
||||
),
|
||||
g(
|
||||
@@ -417,7 +417,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"artistic.roughPastels",
|
||||
"Rough Pastels…",
|
||||
ARTISTIC,
|
||||
"{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.",
|
||||
"{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\"|\"loaded\" (\"canvas\"; \"loaded\" draws the image in textureImage and draws Canvas when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.",
|
||||
json!({
|
||||
"strokeLength": 6.0,
|
||||
"strokeDetail": 10.0,
|
||||
@@ -468,8 +468,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"blur.radial",
|
||||
"Radial Blur…",
|
||||
BLUR,
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good"}),
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples), centerX: 0..1 (0.5; the Blur Center across the object's bounds, 0 their left edge), centerY: 0..1 (0.5; the Blur Center down the object's bounds, 0 their top edge)} blurs around the Blur Center, which moves and scales with the object. A centerX or centerY outside 0..1 is refused",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}),
|
||||
),
|
||||
r(
|
||||
"blur.smart",
|
||||
@@ -859,7 +859,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
crate::SVG_FILTER,
|
||||
"SVG Filter",
|
||||
&["Effect", "SVG Filters"],
|
||||
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
|
||||
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document), axes?: [a, b, c, d] (absent or [1, 0, 0, 1]: the document's axes, and not null; the document directions of one unit along the filter's x axis [a, b] and y axis [c, d] before scale, each -1000..1000, with a·d - b·c at least 0.001 from 0; a turned, skewed or unevenly scaled user space, as SVG import gives a filtered element under a rotate, skew or uneven scale; the filter's offsets, blurs and region run along these axes; moving, turning or skewing the object moves origin and leaves axes)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
|
||||
json!({"scale": 1.0, "origin": [0.0, 0.0]}),
|
||||
));
|
||||
v
|
||||
|
||||
+26
-12
@@ -31,9 +31,10 @@ pub fn reshaped_clip_outline(clip: &Node) -> Option<Option<(BezPath, FillRule)>>
|
||||
/// become a path of their reshaped region. A path or compound path whose fills or strokes have
|
||||
/// geometry effects becomes a group of one path per fill and stroke, reshaped by the path's effects
|
||||
/// and then by that fill's or stroke's, as an export bakes it; [`clip_outline`] clips by their
|
||||
/// union. A clipping path that paints ([`Node::clip_paint`], which a group does not) keeps the
|
||||
/// geometry effects of its own fills and strokes live instead. `None` when nothing in it has a
|
||||
/// geometry effect. Effects on the clip group or around it then reshape the result, after its own.
|
||||
/// union, and the group is marked as such pieces
|
||||
/// ([`vectorcraft_doc::NodeExtras::clip_pieces`]), so a clipping path that paints still paints
|
||||
/// them ([`Node::clip_paint`]). `None` when nothing in it has a geometry effect. Effects on the
|
||||
/// clip group or around it then reshape the result, after its own.
|
||||
pub(crate) fn with_clip_effects_applied(n: &Node) -> Option<Node> {
|
||||
with_clip_effects_applied_while(n, || true)
|
||||
}
|
||||
@@ -42,18 +43,20 @@ pub(crate) fn with_clip_effects_applied(n: &Node) -> Option<Node> {
|
||||
/// or compound path in `n`, at every depth: once `take` returns `false`, that member and the
|
||||
/// members after it are not visited. The members of a group or layer that are not visited stay as
|
||||
/// they are, with their effects. A compound path with geometry effects of its own still becomes a
|
||||
/// path of its reshaped geometry. In a clipping path that does not paint, one whose fills or
|
||||
/// strokes have geometry effects still becomes a group of one path per fill and stroke. In both
|
||||
/// cases the paths in it that are not visited go
|
||||
/// into that geometry as they are, and their own effects are not applied.
|
||||
/// path of its reshaped geometry. A path or compound path whose fills or strokes have geometry
|
||||
/// effects still becomes a group of one path per fill and stroke. In both cases the paths in it
|
||||
/// that are not visited go into that geometry as they are, and their own effects are not applied.
|
||||
pub(crate) fn with_clip_effects_applied_while(n: &Node, take: fn() -> bool) -> Option<Node> {
|
||||
let paint = n.clip_paint();
|
||||
clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none(), take)
|
||||
let mut m = clip_effects_applied(n, true, take)?;
|
||||
if matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) && matches!(m.kind, NodeKind::Group { clip: false, .. }) {
|
||||
m.extras_mut().clip_pieces = true;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// [`with_clip_effects_applied_while`]; with `items` unset (a clipping path that paints, and the
|
||||
/// paths of a compound path, which draw with the compound path's fills and strokes), the geometry
|
||||
/// effects of `n`'s own fills and strokes are left out.
|
||||
/// [`with_clip_effects_applied_while`]; with `items` unset (the paths of a compound path, which
|
||||
/// draw with the compound path's fills and strokes), the geometry effects of `n`'s own fills and
|
||||
/// strokes are left out.
|
||||
fn clip_effects_applied(n: &Node, items: bool, take: fn() -> bool) -> Option<Node> {
|
||||
let mut m: Option<Node> = None;
|
||||
let members: &[std::sync::Arc<Node>] = match &n.kind {
|
||||
@@ -88,6 +91,17 @@ fn clip_effects_applied(n: &Node, items: bool, take: fn() -> bool) -> Option<Nod
|
||||
.iter()
|
||||
.zip(&p.appearance.items)
|
||||
.map(|(item, carried)| {
|
||||
// A fill or stroke whose Transform effect scales strokes or moves patterns is drawn
|
||||
// through its art, as an export bakes such a path ([`crate::reshape`]).
|
||||
let mut whole = Node::path(n.id, g.clone(), Appearance { items: vec![carried.clone()], ..Default::default() });
|
||||
if let NodeKind::Path { rule: r, .. } = &mut whole.kind {
|
||||
*r = rule;
|
||||
}
|
||||
if crate::has_transform_art(&whole)
|
||||
&& let Some(art) = crate::reshape(None, &whole, None)
|
||||
{
|
||||
return std::sync::Arc::new(art);
|
||||
}
|
||||
let (ig, mut it) = crate::bake::apply_item(item, carried, &g, &ctx);
|
||||
crate::bake::clear_item_effects(&mut it);
|
||||
let mut piece = Node::path(n.id, ig, Appearance { items: vec![it], ..Default::default() });
|
||||
|
||||
+35
-46
@@ -742,45 +742,28 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)],
|
||||
}
|
||||
|
||||
/// The members of a container that [`take_held_guides`] visits, by index, each with the same for
|
||||
/// its own members. A ruler guide's entry is empty; a container's is not.
|
||||
/// its own members. A ruler guide's entry is empty, whether its container is a layer or a group; a
|
||||
/// container's is not.
|
||||
#[derive(Default)]
|
||||
struct HeldGuides(Vec<(usize, HeldGuides)>);
|
||||
|
||||
/// The members of `n` holding or leading to the ruler guides of sublayers, found by looking at each
|
||||
/// member at every depth once: the ruler guides (`is_guide`) of `n` when it is a layer, each
|
||||
/// sublayer holding one directly or in its sublayers, and each member of another kind with such a
|
||||
/// sublayer among its members or its groups' members. With them, whether `n` is a layer holding a
|
||||
/// ruler guide directly or in its sublayers. The other members of a layer holding none are not
|
||||
/// looked into, unless the layer is the one whose sublayers are gathered (`top`).
|
||||
fn held_guides(n: &Node, top: bool, is_guide: &impl Fn(&Node) -> bool) -> (bool, HeldGuides) {
|
||||
let layer = n.is_layer();
|
||||
let (mut holds, mut held, mut other) = (false, vec![], vec![]);
|
||||
/// The members of `n` that are ruler guides (`is_guide`), and those holding one at any depth, in
|
||||
/// order. Every member at every depth is looked at once: a sublayer or group with no guide of its
|
||||
/// own is still looked into, and a guide directly in a group counts as one in a layer does. A
|
||||
/// member holding no guide gets no entry.
|
||||
fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> HeldGuides {
|
||||
let mut held = vec![];
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
if is_guide(c) {
|
||||
if layer {
|
||||
holds = true;
|
||||
held.push((i, HeldGuides::default()));
|
||||
}
|
||||
} else if c.is_layer() {
|
||||
let (sub_holds, inner) = held_guides(c, false, is_guide);
|
||||
if sub_holds {
|
||||
holds = true;
|
||||
held.push((i, inner));
|
||||
}
|
||||
} else {
|
||||
other.push((i, c));
|
||||
held.push((i, HeldGuides::default()));
|
||||
continue;
|
||||
}
|
||||
let inner = held_guides(c, is_guide);
|
||||
if !inner.0.is_empty() {
|
||||
held.push((i, inner));
|
||||
}
|
||||
}
|
||||
if !layer || holds || top {
|
||||
for (i, c) in other {
|
||||
let (_, inner) = held_guides(c, false, is_guide);
|
||||
if !inner.0.is_empty() {
|
||||
held.push((i, inner));
|
||||
}
|
||||
}
|
||||
held.sort_unstable_by_key(|(i, _)| *i);
|
||||
}
|
||||
(layer && holds, HeldGuides(held))
|
||||
HeldGuides(held)
|
||||
}
|
||||
|
||||
/// Move the ruler guides of `n` and of its members that [`held_guides`] found (`held`) to `out`:
|
||||
@@ -818,15 +801,14 @@ fn take_held_guides(n: &mut Node, held: HeldGuides, out: &mut Vec<Arc<Node>>, hi
|
||||
out.append(&mut deeper);
|
||||
}
|
||||
|
||||
/// Move the ruler guides of the sublayers among the members of `n`, and among its groups'
|
||||
/// members, to `out`, in order: a sublayer's own guides, then those of its members. A guide taken
|
||||
/// from a hidden or locked sublayer, or from one inside such a sublayer or group, is hidden or
|
||||
/// locked itself. Each member at every depth is looked at once at most (`is_guide`), and only
|
||||
/// containers holding one are copied.
|
||||
/// Move the ruler guides of `n` and those held at any depth by the sublayers and groups among its
|
||||
/// members to `out`, in order: a container's own guides, then those of its members. A sublayer or
|
||||
/// group with no guide of its own still gives up those of its members. A guide taken from a hidden
|
||||
/// or locked sublayer or group, or from one inside such a container, is hidden or locked itself.
|
||||
/// Each member at every depth is looked at once (`is_guide`), and only containers holding a guide
|
||||
/// are copied.
|
||||
fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl Fn(&Node) -> bool) {
|
||||
let (_, mut held) = held_guides(n, true, is_guide);
|
||||
// The ruler guides of `n` itself stay where they are.
|
||||
held.0.retain(|(_, inner)| !inner.0.is_empty());
|
||||
let held = held_guides(n, is_guide);
|
||||
take_held_guides(n, held, out, false, false);
|
||||
}
|
||||
|
||||
@@ -850,12 +832,15 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
// A layer's ruler guides take no part: they go back above the evaluated art at the end.
|
||||
let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default();
|
||||
// So do its sublayers' guides, which would otherwise go with the art the effects replace or
|
||||
// copy: they stay on this layer, hidden and locked as their sublayers were.
|
||||
if m.is_layer() && (pathfinder || !fx.is_empty()) {
|
||||
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
|
||||
// that replace or copy the art, so do its guides among the art and those in its sublayers and
|
||||
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
|
||||
// locked as their containers were.
|
||||
let mut guides = vec![];
|
||||
if pathfinder || !fx.is_empty() {
|
||||
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
|
||||
} else if let Some(ch) = m.children_mut() {
|
||||
guides = ch.split_off(Node::guide_run_start(ch));
|
||||
}
|
||||
if pathfinder {
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
@@ -868,7 +853,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
members_as_drawn(doc, &mut m);
|
||||
{
|
||||
// The members' raster effects then follow the group's own Transform effects as well.
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut m);
|
||||
}
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
|
||||
@@ -1808,7 +1808,7 @@ fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked()
|
||||
}
|
||||
|
||||
/// Gathering the ruler guides of nested sublayers, and of a sublayer inside nested groups, looks
|
||||
/// at each member at every depth once at most, and takes the same guides, in the same order and
|
||||
/// at each member at every depth once, and takes the same guides, in the same order and
|
||||
/// state, as a layer's effects keep.
|
||||
#[test]
|
||||
fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
@@ -1840,7 +1840,7 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
groups.locked = depth == 3;
|
||||
}
|
||||
let free = Arc::new(Node::group(NodeId(500), vec![sq(501, 0.0, Color::BLACK), sq(502, 5.0, Color::BLACK)]));
|
||||
// A sublayer with no guide: the art in its group is not looked at.
|
||||
// A sublayer with no guide, its group holding none either.
|
||||
let quiet = Node::group(NodeId(601), vec![sq(602, 0.0, Color::BLACK), sq(603, 5.0, Color::BLACK)]);
|
||||
let quiet = Arc::new(layer(600, vec![Arc::new(quiet)]));
|
||||
let mut root = layer(10, vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(chain), Arc::new(groups), free.clone(), quiet.clone(), guide(20)]);
|
||||
@@ -1858,15 +1858,16 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
};
|
||||
let mut taken = vec![];
|
||||
take_sublayer_guides(&mut m, &mut taken, &is_guide);
|
||||
assert_eq!(looked.get(), members(&root) - 2, "each member is looked at once, none in the quiet sublayer's group");
|
||||
assert_eq!(state(&taken), expected, "a sublayer's own guides, then its sublayers', each once");
|
||||
assert!(Arc::ptr_eq(&taken[0], &first_guide), "a guide with nothing to change is not copied");
|
||||
assert!(!Arc::ptr_eq(&taken[1], &second_guide), "a guide made hidden is copied");
|
||||
assert_eq!(looked.get(), members(&root), "each member is looked at once, those of guide-free containers included");
|
||||
assert_eq!(taken[0].id, NodeId(20), "the layer's own guide comes first");
|
||||
assert_eq!(state(&taken[1..]), expected, "a sublayer's own guides, then its sublayers', each once");
|
||||
assert!(Arc::ptr_eq(&taken[1], &first_guide), "a guide with nothing to change is not copied");
|
||||
assert!(!Arc::ptr_eq(&taken[2], &second_guide), "a guide made hidden is copied");
|
||||
assert!(second_guide.visible, "the guide as it was stays as it was");
|
||||
let ch = m.children().unwrap();
|
||||
assert_eq!(ch.len(), 5, "the layer's own guide is taken");
|
||||
assert!(Arc::ptr_eq(&ch[3], &free), "a member with no sublayer guide is not copied");
|
||||
assert!(Arc::ptr_eq(&ch[4], &quiet), "a sublayer with no guide is not copied");
|
||||
assert!(ch[5].is_ruler_guide(), "the layer's own guide stays where it is");
|
||||
let ids = |n: &Node| n.children().into_iter().flatten().map(|c| c.id).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&ch[1]), [NodeId(102), NodeId(301)], "the sublayer's art stays, in order");
|
||||
assert_eq!(ids(&root.children().unwrap()[1]), [NodeId(102), NodeId(301), NodeId(201)], "the source keeps its guides");
|
||||
@@ -1892,6 +1893,140 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each ruler guide in `n` is, at every depth, with its position, visibility and lock.
|
||||
fn ruler_guides_in(n: &Node, out: &mut Vec<(NodeId, NodeKind, bool, bool)>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_ruler_guide() {
|
||||
out.push((c.id, c.kind.clone(), c.visible, c.locked));
|
||||
}
|
||||
ruler_guides_in(c, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// A ruler guide in a layer inside a group inside a sublayer that holds no guide of its own, at
|
||||
/// any depth of that pattern, survives its layer's Pathfinder effect or Transform copies once, last
|
||||
/// in the layer, hidden or locked when any container on its way was.
|
||||
#[test]
|
||||
fn a_ruler_guide_below_a_guide_free_sublayer_and_a_group_survives_its_layers_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let layer = |id, children: Vec<Arc<Node>>, (hidden, locked): (bool, bool)| {
|
||||
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
(l.visible, l.locked) = (!hidden, locked);
|
||||
Arc::new(l)
|
||||
};
|
||||
let group = |id, children: Vec<Arc<Node>>, (hidden, locked): (bool, bool)| {
|
||||
let mut g = Node::group(NodeId(id), children);
|
||||
(g.visible, g.locked) = (!hidden, locked);
|
||||
Arc::new(g)
|
||||
};
|
||||
let kind = NodeKind::RulerGuide { vertical: false, pos: 7.0, artboard: None };
|
||||
let states = [(false, false), (true, false), (false, true)];
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
for depth in 1..=3_u64 {
|
||||
for sub in states {
|
||||
for grp in states {
|
||||
for inner in states {
|
||||
// Layer 10 → sublayer → group → … → layer holding the guide, the pattern
|
||||
// repeated `depth` times; only the innermost layer holds a guide.
|
||||
let mut n = layer(900, vec![sq(901, 0.0, Color::BLACK), Arc::new(Node::new(NodeId(20), kind.clone()))], inner);
|
||||
for d in (0..depth).rev() {
|
||||
let (s, g) = if d == 0 { (sub, grp) } else { ((false, false), (false, false)) };
|
||||
n = group(700 + d, vec![sq(710 + d, 5.0, Color::BLACK), n], g);
|
||||
n = layer(800 + d, vec![n, sq(810 + d, 2.0, Color::BLACK)], s);
|
||||
}
|
||||
let mut root = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = root.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), n];
|
||||
}
|
||||
root.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true });
|
||||
let art = evaluate_container(None, &root).unwrap();
|
||||
let (hidden, locked) = (sub.0 || grp.0 || inner.0, sub.1 || grp.1 || inner.1);
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
let case = format!("{effect}, depth {depth}, sublayer {sub:?}, group {grp:?}, layer {inner:?}");
|
||||
assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged");
|
||||
let last = art.children().and_then(|c| c.last()).unwrap();
|
||||
assert_eq!(last.id, NodeId(20), "{case}: last in the layer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A ruler guide directly in a group, in a layer or in a group with a Pathfinder effect or
|
||||
/// Transform copies, survives that effect once, last in the container, hidden or locked as its
|
||||
/// groups were. So does one among a group's art rather than after it.
|
||||
#[test]
|
||||
fn a_ruler_guide_in_a_group_survives_its_containers_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let kind = NodeKind::RulerGuide { vertical: true, pos: 4.0, artboard: None };
|
||||
let guide = || Arc::new(Node::new(NodeId(20), kind.clone()));
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
for (hidden, locked) in [(false, false), (true, false), (false, true)] {
|
||||
let mut inner = Node::group(NodeId(12), vec![sq(2, 5.0, Color::BLACK), guide(), sq(3, 8.0, Color::BLACK)]);
|
||||
(inner.visible, inner.locked) = (!hidden, locked);
|
||||
let outer = Arc::new(Node::group(NodeId(11), vec![Arc::new(inner)]));
|
||||
let fx = Effect { id: effect.into(), params: params.clone(), visible: true };
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer.clone()];
|
||||
}
|
||||
l.appearance.effects.push(fx.clone());
|
||||
let mut g = Node::group(NodeId(13), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer]);
|
||||
g.appearance.effects.push(fx.clone());
|
||||
for (what, n) in [("layer", l), ("group", g)] {
|
||||
let art = evaluate_container(None, &n).unwrap();
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
let case = format!("{effect} on a {what}, hidden {hidden}, locked {locked}");
|
||||
assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged");
|
||||
assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{case}: last");
|
||||
}
|
||||
}
|
||||
// A group's guide placed before its art.
|
||||
let mut g = Node::group(NodeId(13), vec![guide(), sq(1, 0.0, Color::BLACK), sq(2, 5.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
assert_eq!(all, [(NodeId(20), kind.clone(), true, false)], "{effect}: a group's leading guide, once");
|
||||
assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{effect}: moved last");
|
||||
}
|
||||
}
|
||||
|
||||
/// The ruler guides of a layer or group with a Pathfinder effect or Transform copies, one among
|
||||
/// its art and one after it, go after the evaluated art in the order they were in.
|
||||
#[test]
|
||||
fn a_containers_ruler_guides_keep_their_order_through_its_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None }));
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
let members = || vec![sq(1, 0.0, Color::BLACK), guide(20), sq(2, 5.0, Color::BLACK), guide(21)];
|
||||
let fx = Effect { id: effect.into(), params: params.clone(), visible: true };
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = members();
|
||||
}
|
||||
l.appearance.effects.push(fx.clone());
|
||||
let mut g = Node::group(NodeId(11), members());
|
||||
g.appearance.effects.push(fx);
|
||||
for (what, n) in [("layer", l), ("group", g)] {
|
||||
let art = evaluate_container(None, &n).unwrap();
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
let ids = all.iter().map(|(id, ..)| *id).collect::<Vec<_>>();
|
||||
assert_eq!(ids, [NodeId(20), NodeId(21)], "{effect} on a {what}: the guides, in order");
|
||||
let ch = art.children().unwrap();
|
||||
let tail = ch[ch.len() - 2..].iter().map(|c| c.id).collect::<Vec<_>>();
|
||||
assert_eq!(tail, [NodeId(20), NodeId(21)], "{effect} on a {what}: last, in order");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's own Fill + Offset Path below its contents follows the outline of a clip group among
|
||||
/// its members, its clipping path, not the clipped art it hides outside that path (#7289).
|
||||
#[test]
|
||||
|
||||
@@ -81,7 +81,10 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
|
||||
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
|
||||
@@ -91,12 +94,13 @@ pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
};
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES,
|
||||
ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds,
|
||||
graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes,
|
||||
three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in,
|
||||
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
|
||||
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
|
||||
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
|
||||
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
|
||||
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
|
||||
with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
|
||||
|
||||
+135
-18
@@ -29,8 +29,10 @@ mod sketch_ink;
|
||||
mod texture;
|
||||
mod video;
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
@@ -155,12 +157,14 @@ pub enum PixelFx {
|
||||
/// `texture_coverage` (0..40) says.
|
||||
Underpainting { brush_size: f64, texture_coverage: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
|
||||
/// Artistic › Rough Pastels: diagonal pastel strokes `length` (0..40) long, bristle detail
|
||||
/// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as
|
||||
/// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over.
|
||||
/// (1..20), then a [`Texture`] surface (a loaded one included) scaled by `scaling` (0.5..2), in
|
||||
/// relief as strong as `relief` (0..50) and lit from `light`; `invert` turns the surface's
|
||||
/// heights over.
|
||||
RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
|
||||
/// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or
|
||||
/// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32 },
|
||||
/// Blur › Radial Blur around its Blur Center, `center` (0..1 across and down the object's
|
||||
/// bounds; (0.5, 0.5) the object's centre): along arcs (spin, an arc of `amount`°) or along
|
||||
/// rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32, center: [f64; 2] },
|
||||
/// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius`
|
||||
/// whose colour differs from its own by no more than `threshold` levels, over a grid of
|
||||
/// `samples` × `samples` neighbours at most.
|
||||
@@ -314,9 +318,12 @@ pub struct PixelSpace {
|
||||
pub to_doc: Affine,
|
||||
/// The size of a pixel in document units.
|
||||
pub px: f64,
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around, and where the
|
||||
/// Pixelate filters' patterns are anchored (so they move with the object).
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around by default, and
|
||||
/// where the Pixelate filters' patterns are anchored (so they move with the object).
|
||||
pub center: Point,
|
||||
/// The width and height of the object's bounds (document units), centred on `center`: Radial
|
||||
/// Blur's Blur Center lies at a share of them.
|
||||
pub size: Vec2,
|
||||
/// What the colour channels hold.
|
||||
pub channels: Channels,
|
||||
/// The height of a line of the document's raster grid (document units: 72 / Document Raster
|
||||
@@ -327,6 +334,9 @@ pub struct PixelSpace {
|
||||
pub extent: f64,
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angle parameters with their defaults (degrees).
|
||||
const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)];
|
||||
|
||||
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
|
||||
pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
let quality = |levels: [(&str, u32); 3], default: u32| {
|
||||
@@ -381,7 +391,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
"artistic.roughPastels" => PixelFx::RoughPastels {
|
||||
length: num(p, "strokeLength", 6.0).clamp(0.0, 40.0),
|
||||
detail: num(p, "strokeDetail", 10.0).clamp(1.0, 20.0),
|
||||
texture: Texture::parse(text(p, "texture", "canvas")),
|
||||
texture: Texture::parse_with(text(p, "texture", "canvas"), p.get(TEXTURE_IMAGE).and_then(Value::as_str)),
|
||||
scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0,
|
||||
relief: num(p, "relief", 4.0).clamp(0.0, 50.0),
|
||||
light: Light::parse(text(p, "lightDirection", "top")),
|
||||
@@ -421,6 +431,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
amount: num(p, "amount", 10.0).clamp(1.0, 100.0),
|
||||
zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"),
|
||||
passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6),
|
||||
center: [num(p, "centerX", 0.5).clamp(0.0, 1.0), num(p, "centerY", 0.5).clamp(0.0, 1.0)],
|
||||
},
|
||||
"blur.smart" => PixelFx::SmartBlur {
|
||||
radius: num(p, "radius", 3.0).clamp(0.1, 100.0),
|
||||
@@ -559,8 +570,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
},
|
||||
"pixelate.colorHalftone" => PixelFx::ColorHalftone {
|
||||
max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0),
|
||||
angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]
|
||||
.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
},
|
||||
"pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) },
|
||||
"pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) },
|
||||
@@ -608,13 +618,13 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
impl PixelFx {
|
||||
/// How far beyond `bounds` (the content's, document units) the effect can paint.
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
// From the centre to the farthest corner, and to the nearest side.
|
||||
let far = 0.5 * bounds.width().hypot(bounds.height());
|
||||
let near = 0.5 * bounds.width().min(bounds.height());
|
||||
match *self {
|
||||
// A rotated corner reaches the circle through the corners.
|
||||
PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0),
|
||||
PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
// A rotated corner reaches the circle about the Blur Center through the farthest corner.
|
||||
PixelFx::RadialBlur { zoom: false, center, .. } => {
|
||||
let (far, near) = blur::center_reach(bounds, center);
|
||||
(far - near).max(0.0)
|
||||
}
|
||||
PixelFx::RadialBlur { amount, zoom: true, center, .. } => blur::center_reach(bounds, center).0 * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
PixelFx::SmartBlur { radius, .. } => radius,
|
||||
PixelFx::AccentedEdges { .. } => 0.0,
|
||||
// Strokes reach out of the object as far as they reach into it.
|
||||
@@ -786,7 +796,7 @@ impl PixelFx {
|
||||
PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => {
|
||||
artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert)
|
||||
}
|
||||
PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes),
|
||||
PixelFx::RadialBlur { amount, zoom, passes, center } => blur::radial(px, w, h, space, amount, zoom, passes, center),
|
||||
PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => {
|
||||
blur::smart(px, w, h, to_px(radius), threshold, samples)
|
||||
}
|
||||
@@ -849,6 +859,113 @@ fn pick<T: Clone>(table: &[(&str, &str)], all: &[T], value: &str, default: T) ->
|
||||
table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone())
|
||||
}
|
||||
|
||||
/// The shortest that a direction's unit vector may become under a Transform effect and still give
|
||||
/// a direction ([`turned_directions`]).
|
||||
const MIN_TURNED: f64 = 1e-9;
|
||||
|
||||
/// How close (radians) two directions' angles to a turned direction must be to count as equally
|
||||
/// near ([`nearest`]).
|
||||
const TIE: f64 = 1e-9;
|
||||
|
||||
/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction
|
||||
/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the
|
||||
/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke
|
||||
/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are
|
||||
/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn,
|
||||
/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal)
|
||||
/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays
|
||||
/// as it is. Empty for filters with no such parameter.
|
||||
pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> {
|
||||
enum Kind {
|
||||
Light(&'static str),
|
||||
Stroke,
|
||||
Screens,
|
||||
}
|
||||
let kind = match id {
|
||||
"sketch.basRelief" => Kind::Light("bottom"),
|
||||
"artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"),
|
||||
"brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke,
|
||||
"pixelate.colorHalftone" => Kind::Screens,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let p = crate::merged_params(id, p);
|
||||
match kind {
|
||||
Kind::Light(default) => {
|
||||
let light = Light::parse(text(&p, "lightDirection", default));
|
||||
snapped(&Light::ALL, Light::toward, light, a, later, false)
|
||||
.and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t))
|
||||
.map(|name| vec![("lightDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
Kind::Stroke => {
|
||||
let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal"));
|
||||
snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true)
|
||||
.and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t))
|
||||
.map(|name| vec![("strokeDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
// A screen at θ° runs along (cos θ, −sin θ) on the page (y down).
|
||||
Kind::Screens => SCREEN_ANGLES
|
||||
.iter()
|
||||
.filter_map(|&(key, default)| {
|
||||
let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians();
|
||||
let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?;
|
||||
let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6;
|
||||
Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0)))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction.
|
||||
fn mapped(a: Affine, v: Vec2) -> Option<Vec2> {
|
||||
let w = (a * v.to_point()) - (a * Point::ORIGIN);
|
||||
(w.is_finite() && w.hypot() > MIN_TURNED).then_some(w)
|
||||
}
|
||||
|
||||
/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to
|
||||
/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and
|
||||
/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to
|
||||
/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is
|
||||
/// rounded once. `None` when `a` takes `from` to no direction.
|
||||
fn snapped<T: Copy + PartialEq>(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option<T> {
|
||||
let v = mapped(a, dir(from))?;
|
||||
let turned = nearest(all, dir, v, axis)?;
|
||||
if later == Affine::IDENTITY {
|
||||
return Some(turned);
|
||||
}
|
||||
let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) };
|
||||
let fits: Vec<T> = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect();
|
||||
nearest(&fits, dir, v, axis).or(Some(turned))
|
||||
}
|
||||
|
||||
/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle,
|
||||
/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one
|
||||
/// clockwise of `v` on the page.
|
||||
fn nearest<T: Copy>(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option<T> {
|
||||
let period = if axis { PI } else { TAU };
|
||||
let at = v.atan2();
|
||||
let mut best: Option<(T, f64)> = None;
|
||||
for &t in all {
|
||||
// How far clockwise of `v` the entry lies, within half a period either way.
|
||||
let d = (dir(t).atan2() - at).rem_euclid(period);
|
||||
let d = if d > period / 2.0 { d - period } else { d };
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b),
|
||||
};
|
||||
if better {
|
||||
best = Some((t, d));
|
||||
}
|
||||
}
|
||||
best.map(|(t, _)| t)
|
||||
}
|
||||
|
||||
/// The value in `table` of entry `t` of `all` (the same order).
|
||||
fn name_of<T: PartialEq>(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> {
|
||||
table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v)
|
||||
}
|
||||
|
||||
/// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty).
|
||||
fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> {
|
||||
let (px, rest) = data.as_chunks_mut::<4>();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Blur › Radial Blur and Smart Blur (Normal, Edge Only and Overlay Edge).
|
||||
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use super::{PixelSpace, Px16, box_blur, pick, to8, to16};
|
||||
|
||||
@@ -29,13 +29,31 @@ fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] {
|
||||
std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd)
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over
|
||||
/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself
|
||||
/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two
|
||||
/// lookups a pixel each.
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) {
|
||||
/// How far Radial Blur's Blur Center `center` (0..1 across and down `bounds`) lies from the
|
||||
/// farthest corner of `bounds`, and from its nearest side.
|
||||
pub(super) fn center_reach(bounds: Rect, center: [f64; 2]) -> (f64, f64) {
|
||||
// The share of the width (height) on the far side of the center, doubled: 1 at the middle.
|
||||
let far = |f: f64| 1.0 + (2.0 * f - 1.0).abs();
|
||||
let (w, h) = (bounds.width(), bounds.height());
|
||||
let near = ((2.0 - far(center[0])) * w).min((2.0 - far(center[1])) * h);
|
||||
(0.5 * (far(center[0]) * w).hypot(far(center[1]) * h), 0.5 * near)
|
||||
}
|
||||
|
||||
/// Where Radial Blur's Blur Center `center` (0..1 across and down the object's bounds) lies in the
|
||||
/// document: the object's centre at (0.5, 0.5).
|
||||
pub(super) fn blur_center(space: &PixelSpace, center: [f64; 2]) -> Point {
|
||||
let shift = Vec2::new((center[0] - 0.5) * space.size.x, (center[1] - 0.5) * space.size.y);
|
||||
if shift.x.is_finite() && shift.y.is_finite() { space.center + shift } else { space.center }
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the Blur Center
|
||||
/// (`center`, [`blur_center`]) over evenly spaced steps spanning `amount`. Each pass averages the
|
||||
/// previous result with itself turned both ways by half the last step, so `passes` passes average
|
||||
/// 2^`passes` samples at two lookups a pixel each.
|
||||
#[allow(clippy::too_many_arguments)] // the effect's four options
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32, center: [f64; 2]) {
|
||||
// The centre in pixel index coordinates (pixel centres at whole numbers).
|
||||
let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5);
|
||||
let c = space.to_doc.inverse() * blur_center(space, center) - Vec2::new(0.5, 0.5);
|
||||
if !(c.x.is_finite() && c.y.is_finite()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ pub enum StrokeDirection {
|
||||
}
|
||||
|
||||
impl StrokeDirection {
|
||||
const ALL: [StrokeDirection; 4] =
|
||||
pub(super) const ALL: [StrokeDirection; 4] =
|
||||
[StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical];
|
||||
|
||||
/// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal
|
||||
@@ -53,7 +53,7 @@ impl StrokeDirection {
|
||||
}
|
||||
|
||||
/// The unit vector along the strokes (document axes, y down).
|
||||
fn along(self) -> Vec2 {
|
||||
pub(super) fn along(self) -> Vec2 {
|
||||
match self {
|
||||
StrokeDirection::RightDiagonal => RIGHT,
|
||||
StrokeDirection::Horizontal => Vec2::new(1.0, 0.0),
|
||||
|
||||
@@ -12,6 +12,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
@@ -479,12 +480,16 @@ fn film_grain_leaves_invalid_coordinate_spaces_alone() {
|
||||
|
||||
#[test]
|
||||
fn params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6, center: [0.5, 0.5] });
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 }
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best", "centerX": 0.25, "centerY": 1})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8, center: [0.25, 1.0] }
|
||||
);
|
||||
// A saved center outside the bounds (the commands refuse one) draws at the nearest edge.
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": -5, "quality": "nonsense", "centerX": -3, "centerY": 7})),
|
||||
PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6, center: [0.0, 1.0] }
|
||||
);
|
||||
assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7, mode: SmartBlurMode::Normal });
|
||||
assert_eq!(
|
||||
fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low", "blurMode": "EDGEONLY"})),
|
||||
@@ -519,6 +524,11 @@ fn outsets_follow_the_object() {
|
||||
let far = 0.5 * 100f64.hypot(50.0);
|
||||
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
|
||||
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
|
||||
// About a corner the spin reaches the circle through the opposite corner, the whole diagonal out.
|
||||
let corner = fx("blur.radial", json!({"centerX": 0, "centerY": 0}));
|
||||
assert!((corner.outset(b) - 100f64.hypot(50.0)).abs() < 1e-9, "{}", corner.outset(b));
|
||||
let zoom = |center: f64| fx("blur.radial", json!({"method": "zoom", "amount": 100, "centerX": center, "centerY": center})).outset(b);
|
||||
assert!((zoom(1.0) - 2.0 * zoom(0.5)).abs() < 1e-9, "a zoom about a corner reaches twice as far");
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0));
|
||||
// The edge modes also read the copy blurred over a wide radius's samples.
|
||||
@@ -633,6 +643,40 @@ fn spin_blur_smears_along_arcs_and_keeps_the_centre() {
|
||||
assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it");
|
||||
}
|
||||
|
||||
/// The Blur Center moves the point the blur turns about: a dot on it stays sharp, a dot on the
|
||||
/// object's centre then spreads, and the center follows the object when it moves or is scaled.
|
||||
#[test]
|
||||
fn radial_blur_turns_about_its_blur_center() {
|
||||
let (w, h) = (41, 41);
|
||||
// A dot on pixel (10, 30), whose centre (10.5, 30.5) is the Blur Center below, and one on the
|
||||
// object's centre.
|
||||
let src = image(w, h, |x, y| if (x == 10 && y == 30) || (x == 20 && y == 20) { grey(255) } else { [0, 0, 0, 0] });
|
||||
let blur = |p: serde_json::Value, s: &PixelSpace, src: &[u8]| {
|
||||
let mut d = src.to_vec();
|
||||
fx("blur.radial", p).apply(&mut d, w, h, s);
|
||||
d
|
||||
};
|
||||
let off = json!({"amount": 60, "quality": "best", "centerX": 10.5 / 41.0, "centerY": 30.5 / 41.0});
|
||||
let d = blur(off.clone(), &space(w, h), &src);
|
||||
assert!(at(&d, w, 10, 30)[3] > 100, "the dot on the Blur Center barely moves: {:?}", at(&d, w, 10, 30));
|
||||
assert!(at(&d, w, 20, 20)[3] < 100, "the dot on the object's centre spreads: {:?}", at(&d, w, 20, 20));
|
||||
// The default center is the object's centre, the same as no center at all.
|
||||
assert_eq!(blur(json!({"amount": 60, "centerX": 0.5, "centerY": 0.5}), &space(w, h), &src), blur(json!({"amount": 60}), &space(w, h), &src));
|
||||
// Moved 7 pt right and 3 pt down, the object draws the same pixels.
|
||||
let moved =
|
||||
PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: space(w, h).center + vectorcraft_geom::Vec2::new(7.0, 3.0), ..space(w, h) };
|
||||
assert_eq!(blur(off.clone(), &moved, &src), d, "the center moves with the object");
|
||||
// Drawn at twice the size (two points a pixel), the center lies on the same pixels.
|
||||
let big = PixelSpace {
|
||||
to_doc: Affine::scale(2.0),
|
||||
px: 2.0,
|
||||
center: Point::new(41.0, 41.0),
|
||||
size: vectorcraft_geom::Vec2::new(82.0, 82.0),
|
||||
..space(w, h)
|
||||
};
|
||||
assert_eq!(blur(off, &big, &src), d, "the center scales with the object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
let (w, h) = (40, 20);
|
||||
@@ -862,6 +906,7 @@ fn lengths_are_document_units() {
|
||||
to_doc: Affine::scale(1.0 / scale as f64),
|
||||
px: 1.0 / scale as f64,
|
||||
center: Point::ZERO,
|
||||
size: vectorcraft_geom::Vec2::ZERO,
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
@@ -916,7 +961,15 @@ fn linear_light_blur_mixes_light_not_values() {
|
||||
fn pixel_timings() {
|
||||
let (w, h) = (2000, 2000);
|
||||
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
|
||||
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0, extent: 0.0 };
|
||||
let s = PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1000.0, 1000.0),
|
||||
size: vectorcraft_geom::Vec2::new(2000.0, 2000.0),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
};
|
||||
let cases = [
|
||||
("blur.radial", json!({"quality": "draft"})),
|
||||
("blur.radial", json!({"quality": "good"})),
|
||||
@@ -1494,6 +1547,42 @@ fn texturizer_draws_a_loaded_texture_as_relief() {
|
||||
assert_eq!(fx("texture.texturizer", json!({"texture": "LOADED", "textureImage": "not a texture"})), fx("texture.texturizer", json!({})));
|
||||
}
|
||||
|
||||
/// Rough Pastels draws a loaded texture as its surface, and Scaling, Relief, Light Direction and
|
||||
/// Invert act on it as on the built-in ones.
|
||||
#[test]
|
||||
fn rough_pastels_draws_a_loaded_texture_as_its_surface() {
|
||||
let w = 64;
|
||||
let mid = grey(150);
|
||||
let rings = stored(12, 10, |x, y| {
|
||||
let v = ((x as f64 - 5.5).hypot(y as f64 - 4.5) * 0.9).sin().abs();
|
||||
let g = (v * 255.0).round() as u8;
|
||||
[g, g, g, 255]
|
||||
});
|
||||
let run = |mut p: serde_json::Value| {
|
||||
p["strokeLength"] = json!(0);
|
||||
let mut d = flat(w, mid);
|
||||
fx("artistic.roughPastels", p).apply(&mut d, w, w, &space(w, w));
|
||||
d
|
||||
};
|
||||
let relief = run(json!({"texture": "loaded", "textureImage": rings, "relief": 20}));
|
||||
assert_ne!(relief, flat(w, mid));
|
||||
for (_, builtin) in TEXTURES {
|
||||
assert_ne!(relief, run(json!({"texture": builtin, "relief": 20})), "{builtin}");
|
||||
}
|
||||
for (key, value) in [("invert", json!(true)), ("scaling", json!(200)), ("lightDirection", json!("bottomRight")), ("relief", json!(5))] {
|
||||
let mut p = json!({"texture": "loaded", "textureImage": rings, "relief": 20});
|
||||
p[key] = value;
|
||||
assert_ne!(run(p), relief, "{key}");
|
||||
}
|
||||
assert_eq!(run(json!({"texture": "loaded", "textureImage": rings, "relief": 0})), flat(w, mid));
|
||||
let parsed = fx("artistic.roughPastels", json!({"texture": "Loaded", "textureImage": rings}));
|
||||
assert!(matches!(parsed, PixelFx::RoughPastels { texture: Texture::Loaded(_), .. }), "{parsed:?}");
|
||||
// Without a stored texture, or with one that isn't, Loaded draws Canvas.
|
||||
for p in [json!({"texture": "loaded"}), json!({"texture": "loaded", "textureImage": "not a texture"})] {
|
||||
assert_eq!(fx("artistic.roughPastels", p), fx("artistic.roughPastels", json!({})));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Texture filters' patterns lie in document space around the object's centre: the same at
|
||||
/// twice the resolution, and moving with the object.
|
||||
#[test]
|
||||
|
||||
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
|
||||
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
|
||||
@@ -137,7 +137,7 @@ pub enum Light {
|
||||
}
|
||||
|
||||
impl Light {
|
||||
const ALL: [Light; 8] =
|
||||
pub(super) const ALL: [Light; 8] =
|
||||
[Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight];
|
||||
|
||||
/// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise.
|
||||
|
||||
+103
-10
@@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
|
||||
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
|
||||
let list = out.get_or_insert_with(|| effects.to_vec());
|
||||
if let Some(e) = list.get_mut(i) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
out.map_or(Cow::Borrowed(effects), Cow::Owned)
|
||||
@@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
|
||||
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
|
||||
let mut changed = false;
|
||||
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
@@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine)
|
||||
let det = b.determinant();
|
||||
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
|
||||
if c.is_finite() {
|
||||
follow_transform(e, c);
|
||||
follow_transform(e, c, b);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -606,18 +606,104 @@ fn transform_step(e: &Effect) -> Option<Affine> {
|
||||
(copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO))
|
||||
}
|
||||
|
||||
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
|
||||
/// instead of the art it is made from: the indices of the visible Transform effects listed after
|
||||
/// it that move the art, when from the first visible Transform effect after it on every visible
|
||||
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
|
||||
/// in the order they are listed, so the image is made of the art before those Transform effects
|
||||
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
|
||||
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
|
||||
/// on.
|
||||
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
|
||||
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
|
||||
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
|
||||
let mut at = vec![];
|
||||
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
|
||||
if e.id != "distort.transform" || transform_step(e).is_none() {
|
||||
return None;
|
||||
}
|
||||
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
|
||||
at.push(i);
|
||||
}
|
||||
}
|
||||
(!at.is_empty()).then_some(at)
|
||||
}
|
||||
|
||||
/// `effects` with the Transform effects at `at` hidden ([`rasterize_stage`]): what the image of
|
||||
/// the Rasterize effect before them is made from.
|
||||
pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
|
||||
let mut out = effects.to_vec();
|
||||
for &i in at {
|
||||
if let Some(e) = out.get_mut(i) {
|
||||
e.visible = false;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
|
||||
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
|
||||
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
|
||||
/// last one outermost. `None` when `staged` is empty or the map is not a number.
|
||||
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
|
||||
let mut cur = staged.clone();
|
||||
let mut b = staged.bounds()?;
|
||||
let mut map = Affine::IDENTITY;
|
||||
for &i in at {
|
||||
let e = effects.get(i)?;
|
||||
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
|
||||
map = m * map;
|
||||
cur = cur.transformed(m);
|
||||
b = cur.bounds().unwrap_or(b);
|
||||
}
|
||||
map.is_finite().then_some(map)
|
||||
}
|
||||
|
||||
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
|
||||
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
|
||||
/// around the art.
|
||||
/// around the art: the image moves with those Transform effects instead ([`rasterize_stage`]).
|
||||
pub(crate) fn follows(id: &str) -> bool {
|
||||
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The linear part of the Transform effects of the groups and layers whose members are being
|
||||
/// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once
|
||||
/// the members are evaluated: the members' light and stroke directions are rounded for them as
|
||||
/// well ([`follow_transform`]).
|
||||
static LATER_GROUPS: std::cell::Cell<Affine> = const { std::cell::Cell::new(Affine::IDENTITY) };
|
||||
}
|
||||
|
||||
/// The Transform effects of a group or layer whose members are being evaluated before the group's
|
||||
/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped.
|
||||
pub(crate) struct LaterGroups(Affine);
|
||||
|
||||
impl LaterGroups {
|
||||
/// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]),
|
||||
/// to those the members will still go through.
|
||||
pub(crate) fn enter(owner: &[Effect]) -> Self {
|
||||
let was = LATER_GROUPS.with(|l| l.get());
|
||||
if let Some(step) = contents_step(owner) {
|
||||
LATER_GROUPS.with(|l| l.set(was * step));
|
||||
}
|
||||
LaterGroups(was)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LaterGroups {
|
||||
fn drop(&mut self) {
|
||||
LATER_GROUPS.with(|l| l.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
|
||||
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
|
||||
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
|
||||
/// `a`. Effects that [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`,
|
||||
/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with
|
||||
/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn,
|
||||
/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that
|
||||
/// [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine, later: Affine) {
|
||||
if !follows(&e.id) {
|
||||
return;
|
||||
}
|
||||
@@ -625,15 +711,22 @@ fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
|
||||
});
|
||||
let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later);
|
||||
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
|
||||
crate::scale_effect(e, k);
|
||||
}
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
let mut set = |key: &str, value: Value| {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
}
|
||||
e.params["x"] = json!(o.x);
|
||||
e.params["y"] = json!(o.y);
|
||||
e.params[key] = value;
|
||||
};
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
set("x", json!(o.x));
|
||||
set("y", json!(o.y));
|
||||
}
|
||||
for (key, value) in turned {
|
||||
set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -515,18 +515,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::Bez
|
||||
/// gradient fitted across the whole layout, and the transform also scales its stroke weights and
|
||||
/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and
|
||||
/// move with the type.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) {
|
||||
///
|
||||
/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give
|
||||
/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill,
|
||||
/// and the returned path is the area the run's stroke paints around `piece` in text space
|
||||
/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and
|
||||
/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run
|
||||
/// without a stroke.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option<Node> {
|
||||
let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() };
|
||||
let mut ap = style.appearance();
|
||||
ap.pin_gradients(bounds);
|
||||
let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) };
|
||||
piece.appearance = ap.into();
|
||||
piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() });
|
||||
piece.transform(xf, scaling);
|
||||
stroke.map(|mut s| {
|
||||
s.transform(xf, scaling);
|
||||
s
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a
|
||||
/// reflection), without flattening?
|
||||
fn is_similarity(xf: Affine) -> bool {
|
||||
let [a, b, c, d, ..] = xf.as_coeffs();
|
||||
let (x, y) = (a.hypot(b), c.hypot(d));
|
||||
let tol = 1e-9 * x.max(y);
|
||||
x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y)
|
||||
}
|
||||
|
||||
/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space),
|
||||
/// and returns the area it paints there as a path filled with its paint, opacity, blend mode,
|
||||
/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing.
|
||||
fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option<Node> {
|
||||
let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?;
|
||||
let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None };
|
||||
let path = PathData::from_bezpath(&piece.stroke_path()?);
|
||||
let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st);
|
||||
if region.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fill = vectorcraft_doc::FillLayer {
|
||||
opacity: st.opacity,
|
||||
blend: st.blend,
|
||||
effects: st.effects.clone(),
|
||||
overprint: st.overprint,
|
||||
..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill())
|
||||
};
|
||||
Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Type as glyph outlines in document space: one path per run with the run's fill and stroke,
|
||||
/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole
|
||||
/// outline with the object's items below the characters under them and the others over them, as
|
||||
/// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke
|
||||
/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to
|
||||
/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts
|
||||
/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to
|
||||
/// the layout's bounds in text space. The object's own unplaced gradients are fixed to the
|
||||
/// bounding box of those bounds in the document. The group is marked as type's outlines
|
||||
/// ([`vectorcraft_doc::NodeExtras::type_outlines`]).
|
||||
@@ -542,8 +586,9 @@ pub fn outline_text(n: &Node) -> Option<Node> {
|
||||
continue;
|
||||
}
|
||||
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default());
|
||||
paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
children.push(Arc::new(piece));
|
||||
children.extend(stroke.map(Arc::new));
|
||||
}
|
||||
if !n.appearance.items.is_empty() && !all.elements().is_empty() {
|
||||
let (below, above) = n.appearance.split_contents();
|
||||
@@ -746,9 +791,13 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option<Node> {
|
||||
|
||||
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
|
||||
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
|
||||
/// its outlines with its visibility and effects ([`clipping_text_outline`]). The swatches and
|
||||
/// patterns that live-effect plug-ins painting their pieces name are looked up in `doc`.
|
||||
/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and
|
||||
/// strokes become art of their own ([`paint_type_clip`]). The swatches and patterns that
|
||||
/// live-effect plug-ins painting their pieces name are looked up in `doc`.
|
||||
pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping: bool) {
|
||||
if !clipping {
|
||||
paint_type_clip(doc, n);
|
||||
}
|
||||
let clips = n.clips();
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for (i, c) in ch.iter_mut().enumerate() {
|
||||
@@ -766,6 +815,36 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
|
||||
}
|
||||
}
|
||||
|
||||
/// When `n` is a clip group or clipping layer whose clipping path is type that paints
|
||||
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip
|
||||
/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside
|
||||
/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes
|
||||
/// (keeping its id, name and transparency) with the clip group inside. The other members stay as
|
||||
/// they are. Hidden type paints nothing.
|
||||
pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) {
|
||||
let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return };
|
||||
if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
|
||||
return;
|
||||
}
|
||||
let paint = first.clip_paint();
|
||||
if paint.fill.is_none() && paint.stroke.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(clip) = clipping_text_outline(first) else { return };
|
||||
let art = |part: Option<Node>| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new);
|
||||
let members: Vec<Arc<Node>> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect();
|
||||
let stroke = art(paint.stroke);
|
||||
let id = n.id;
|
||||
match (&mut n.kind, stroke) {
|
||||
(NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members,
|
||||
(NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => {
|
||||
*children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke];
|
||||
*clip = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied:
|
||||
/// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped
|
||||
/// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own
|
||||
|
||||
+127
-27
@@ -8,7 +8,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, N
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::WireFace;
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
use crate::solids::{
|
||||
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
|
||||
};
|
||||
@@ -154,7 +154,12 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
let b = union_bounds(&shapes).ok_or(EMPTY)?;
|
||||
let options = shared_options(&shapes, options_of(id, p))?;
|
||||
let mut copies = 0;
|
||||
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?;
|
||||
// In wireframe mode the edges are drawn with no paint copies, graphics or shadow.
|
||||
let wire = wireframe_params(id, p);
|
||||
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items).filter(|_| !wire), &mut copies))?;
|
||||
if wire {
|
||||
return Ok(());
|
||||
}
|
||||
// Without graphics, or without the document they draw from, no member is measured for them.
|
||||
if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) {
|
||||
match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) {
|
||||
@@ -166,7 +171,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
|
||||
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity)));
|
||||
return check_shadow(p, casting.map(|s| &s.path), b, options);
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
@@ -176,7 +181,11 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
let path = geometry(&path, before, &GeomContext::of(n));
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let paints = solid_paints(n);
|
||||
check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?;
|
||||
let wire = wireframe_params(id, p);
|
||||
check_surface(&path, b, options_of(id, p), surface_item(&paints).filter(|_| !wire), &mut 0)?;
|
||||
if wire {
|
||||
return Ok(());
|
||||
}
|
||||
check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?;
|
||||
check_shadow(p, [&path], b, options_of(id, p))
|
||||
}
|
||||
@@ -261,7 +270,11 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V
|
||||
let options = options_of(kind, ¶ms);
|
||||
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
|
||||
let b = path.bounds().ok_or(EMPTY)?;
|
||||
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
|
||||
let wire = wireframe_params(kind, ¶ms);
|
||||
check_surface(&path, b, options, (crate::paints(item) && !wire).then_some(item), &mut copies)?;
|
||||
if wire {
|
||||
continue;
|
||||
}
|
||||
// The graphics of every item add their paints' copies to the graphics' budget, as they
|
||||
// are drawn; only the edited item's graphics are refused here.
|
||||
let graphics = check_graphics(doc, kind, &path, b, options, ¶ms, &mut graphic_copies);
|
||||
@@ -324,6 +337,7 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
|
||||
pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_revolve_params(p)?;
|
||||
crate::solids::graphics::validate(id, p)?;
|
||||
crate::solids::wireframe::validate_render(id, p)?;
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::validate(p)?;
|
||||
}
|
||||
@@ -336,8 +350,8 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
|
||||
/// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of
|
||||
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
|
||||
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
|
||||
/// the surface it is cast from is past the limits.
|
||||
/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when
|
||||
/// it casts nothing, and an error when the surface it is cast from is past the limits.
|
||||
///
|
||||
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
|
||||
/// surface is swept again for its shadow alone.
|
||||
@@ -352,7 +366,7 @@ fn shadow_of(
|
||||
) -> Result<Option<Node>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
|
||||
let (_, opacity, blend) = paint_of(item);
|
||||
if opacity <= 0.0 {
|
||||
if !crate::solids::shadow::casts(opacity) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
@@ -363,7 +377,7 @@ fn shadow_of(
|
||||
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
|
||||
/// its shadow is cast from ([`surface`])?
|
||||
fn casts(fx: &Effect, opacity: f32) -> bool {
|
||||
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
|
||||
crate::solids::shadow::casts(opacity) && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
|
||||
}
|
||||
|
||||
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
|
||||
@@ -406,9 +420,9 @@ fn group_shadow(
|
||||
for s in shapes {
|
||||
let kept = kept.next().flatten();
|
||||
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
|
||||
// A member whose surface is fully transparent casts nothing.
|
||||
// A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing.
|
||||
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
|
||||
if ink.opacity <= 0.0 {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
@@ -728,14 +742,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
/// or stroke's Revolve are looked up in `doc`. Each face carries the width of the stroke the canvas
|
||||
/// draws around it ([`surface`]).
|
||||
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<crate::solids::wireframe::FacesAndShadow, String> {
|
||||
let faces = |path: &PathData, b: Rect, fx: &Effect, options: Revolve| -> Result<Vec<WireFace>, String> {
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options)?;
|
||||
return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect());
|
||||
}
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
};
|
||||
let faces = wire_faces;
|
||||
if is_container(n) {
|
||||
let index = n
|
||||
.appearance
|
||||
@@ -752,7 +759,9 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, fx, options)?);
|
||||
}
|
||||
return Ok((out, group_shadow(n.id, fx, &shapes, b, options, vec![])?));
|
||||
// In wireframe mode the canvas draws no shadow.
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
|
||||
return Ok((out, shadow));
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
@@ -763,7 +772,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&path, b, fx, fx_options(fx))?;
|
||||
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
|
||||
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -781,6 +790,28 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
Ok((out, vec![]))
|
||||
}
|
||||
|
||||
/// The faces Revolve or Revolve (Classic) `fx` sweeps from `path` about the bounds `b` with
|
||||
/// `options`, each with the width of the stroke the canvas draws around it.
|
||||
fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result<Vec<WireFace>, String> {
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options)?;
|
||||
return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect());
|
||||
}
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
}
|
||||
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
|
||||
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
|
||||
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
let mut faces = vec![];
|
||||
for path in paths {
|
||||
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
|
||||
}
|
||||
crate::solids::wireframe::wire_art(id, &faces)
|
||||
}
|
||||
|
||||
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
|
||||
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let index = n
|
||||
@@ -824,13 +855,18 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of the faces, with no shadow.
|
||||
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
|
||||
} else {
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
children.push(Arc::new(surface));
|
||||
}
|
||||
children.push(Arc::new(surface));
|
||||
// Later geometry acts on the projected art as a whole through container evaluation.
|
||||
remaining = past_effect(&n.appearance.effects, index);
|
||||
remaining.retain(|e| !is_revolve(&e.id));
|
||||
@@ -850,6 +886,13 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
|
||||
Arc::make_mut(&mut art).appearance.effects =
|
||||
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
children.push(art);
|
||||
continue;
|
||||
}
|
||||
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
@@ -999,6 +1042,14 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let b = union_bounds(&shapes)?;
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of every member's faces, with no shadow.
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
|
||||
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
|
||||
return Some(art);
|
||||
}
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut copies = Copies::default();
|
||||
let mut surfaces = vec![];
|
||||
@@ -1810,6 +1861,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one
|
||||
/// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the
|
||||
/// member beside it still casts its part.
|
||||
#[test]
|
||||
fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
|
||||
let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap();
|
||||
let group = |opacity: f32| {
|
||||
let mut other = profile_node();
|
||||
other.id = NodeId(2);
|
||||
other.transform(Affine::translate((120.0, 0.0)), false);
|
||||
other.opacity = opacity;
|
||||
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
|
||||
g.appearance.effects.push(fx.clone());
|
||||
g
|
||||
};
|
||||
let group_shadows = |g: &Node| {
|
||||
let shapes = members(g, "").unwrap();
|
||||
let b = union_bounds(&shapes).unwrap();
|
||||
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
|
||||
let kept: Vec<Option<SolidFaces>> = shapes
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
[group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()]
|
||||
.map(|art| format!("{art:?}"))
|
||||
};
|
||||
let expected = group_shadows(&group(0.0));
|
||||
for bad in [f32::NAN, f32::INFINITY] {
|
||||
let mut n = profile_node();
|
||||
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
|
||||
f.opacity = bad;
|
||||
}
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
|
||||
let shadows = group_shadows(&group(bad));
|
||||
assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts");
|
||||
assert_eq!(shadows, expected, "{bad}: only the opaque member casts");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -23,7 +23,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 2] = ["cap", "lightBehind"];
|
||||
const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"];
|
||||
|
||||
/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge,
|
||||
/// rotation and perspective, built unshaded, since the classic surfaces light its faces.
|
||||
@@ -118,6 +118,52 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Preserve Spot Colors, a fill linked to a spot swatch stays linked on every face: the
|
||||
/// highlight lowers its tint, and the shadow is black multiplied and overprinting over it.
|
||||
#[test]
|
||||
fn preserve_spot_colors_keeps_the_swatch_on_every_face() {
|
||||
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2);
|
||||
let spot = |params: Value| {
|
||||
let mut n = profile();
|
||||
*n.appearance = Appearance::basic(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 0.5 }, Paint::None, 0.0);
|
||||
n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, ¶ms).unwrap());
|
||||
crate::revolve_art(&n).unwrap()
|
||||
};
|
||||
let art = spot(json!({"preserveSpotColors": true}));
|
||||
let mut darkened = 0;
|
||||
for face in faces(&art) {
|
||||
let mut fills = face.appearance.items.iter().filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
match fills.next().map(|f| &f.paint) {
|
||||
Some(Paint::Solid { color, swatch: Some(name), tint }) => {
|
||||
assert_eq!(name, "Ink");
|
||||
assert!(*tint > 0.0 && *tint <= 0.5, "{tint}");
|
||||
assert_eq!(*color, ink.tinted(*tint / 0.5), "the color is the swatch at the face's tint");
|
||||
}
|
||||
other => panic!("the face keeps its swatch: {other:?}"),
|
||||
}
|
||||
if let Some(shadow) = fills.next() {
|
||||
assert!(matches!(shadow.paint.color(), Some(Color::Gray { .. })), "{:?}", shadow.paint);
|
||||
assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true));
|
||||
darkened += 1;
|
||||
}
|
||||
}
|
||||
assert!(darkened > 0, "faces turned from the light are darkened");
|
||||
// Off, and with a custom shading color, the faces are process mixes again.
|
||||
for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#336699"})] {
|
||||
let art = spot(params.clone());
|
||||
let linked = faces(&art)
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if matches!(f.paint, Paint::Solid { swatch: Some(_), .. })))
|
||||
})
|
||||
.count();
|
||||
assert!(linked < faces(&art).len(), "{params}: shaded faces lose the swatch");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_offset_edge_and_cap_shape_the_surface() {
|
||||
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
|
||||
@@ -207,6 +253,7 @@ mod tests {
|
||||
(json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"),
|
||||
(json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"),
|
||||
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
|
||||
(json!({"preserveSpotColors": "on"}), "`preserveSpotColors` must be true or false"),
|
||||
(json!({"surface": "glossy"}), "`surface` must be one of"),
|
||||
(json!({"shadingColor": "white"}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
|
||||
@@ -36,7 +36,7 @@ pub use graphics::{
|
||||
pub(crate) mod shadow;
|
||||
|
||||
pub(crate) mod wireframe;
|
||||
pub use wireframe::three_d_wireframe_in;
|
||||
pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in};
|
||||
|
||||
pub const EXTRUDE: &str = "threeD.extrude";
|
||||
pub const INFLATE: &str = "threeD.inflate";
|
||||
@@ -274,6 +274,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
crate::lighting::validate(p)?;
|
||||
shadow::validate(p)?;
|
||||
graphics::validate(id, p)?;
|
||||
wireframe::validate_render(id, p)?;
|
||||
if let Some(v) = p.get("bevel")
|
||||
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
|
||||
{
|
||||
@@ -323,8 +324,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
return cast_shadow(id, p, &shapes).map(|_| ());
|
||||
return check_solids(id, p, &shapes);
|
||||
}
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let anchors = || format!("{label} requires a shape with at least two anchors");
|
||||
@@ -341,29 +341,68 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let b = path.bounds().ok_or_else(anchors)?;
|
||||
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
cast_shadow(id, p, &shapes).map(|_| ())
|
||||
check_solids(id, p, &shapes)
|
||||
}
|
||||
|
||||
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
|
||||
/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn casts_shadow(id: &str, p: &Value) -> bool {
|
||||
!is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p)
|
||||
}
|
||||
|
||||
/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow?
|
||||
fn visible(item: &AppearanceItem, member: f32) -> bool {
|
||||
paint_of(item, member).1 > 0.0
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: every
|
||||
/// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill,
|
||||
/// whose solids are its strokes' outlines or none. A filled shape's profile is its fill's solid,
|
||||
/// which [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
|
||||
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
|
||||
/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids
|
||||
/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which
|
||||
/// [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|s| is_plane(id) || !s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))))
|
||||
.try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
let cast = casts_shadow(id, p);
|
||||
let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity)));
|
||||
shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes`
|
||||
/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not
|
||||
/// counted.
|
||||
/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does
|
||||
/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as
|
||||
/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the
|
||||
/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its
|
||||
/// shadow Rotate builds no plane here.
|
||||
fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) };
|
||||
let Some(b) = union_bounds(shapes) else { return Ok(()) };
|
||||
let cast = casts_shadow(id, p);
|
||||
if is_plane(id) {
|
||||
if !cast {
|
||||
return Ok(());
|
||||
}
|
||||
let mut built = vec![];
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
if !visible(item, s.opacity) {
|
||||
built.push(None);
|
||||
continue;
|
||||
}
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1);
|
||||
}
|
||||
}
|
||||
return cast_built(id, p, shapes, built).map(|_| ());
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()))
|
||||
if !cast {
|
||||
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
|
||||
}
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
|
||||
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
cast_built(id, p, shapes, built).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
|
||||
@@ -723,7 +762,8 @@ thread_local! {
|
||||
/// surfaces count too.
|
||||
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
|
||||
/// [`built_solids`] have built on this thread, for the tests.
|
||||
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
|
||||
/// ([`cast_shadow`]) count too.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
@@ -1420,8 +1460,12 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
|
||||
/// surface of the object, and the surfaces.
|
||||
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
|
||||
// In wireframe mode the effect draws the edges of the faces it builds, with no shadow.
|
||||
if wireframe::renders_wireframe(fx) {
|
||||
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
|
||||
let cast = casts_shadow(&fx.id, &p);
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
@@ -1434,8 +1478,11 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) ->
|
||||
}
|
||||
|
||||
/// The shadow [`art_for`] draws for effect `fx` on `shapes` behind the surfaces of object `id`:
|
||||
/// none with the shadow off, and an error when it is past the limits.
|
||||
/// none with the shadow off or in wireframe mode, and an error when it is past the limits.
|
||||
pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<Vec<Arc<Node>>, String> {
|
||||
if wireframe::renders_wireframe(fx) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
Ok(match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes)? {
|
||||
Some((caster, settings, cast)) => shadow::scoped_art(id, &caster, settings, cast, has_masks(shapes)),
|
||||
None => vec![],
|
||||
@@ -1457,8 +1504,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
|
||||
// and blending mode), in order. A fully transparent fill or stroke (or member) casts nothing
|
||||
// and does not place the plane.
|
||||
// and blending mode), in order. A fill or stroke (or member) that is fully transparent, or whose
|
||||
// opacity is not a finite number, casts nothing and does not place the plane ([`shadow::Ink::casts`]).
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
let (_, opacity, blend) = paint_of(item, member);
|
||||
@@ -1466,7 +1513,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
};
|
||||
if id == ROTATE {
|
||||
for s in shapes {
|
||||
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
|
||||
for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
@@ -1480,21 +1527,25 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
// Inflate's eye is placed for every shape together, as the solids are.
|
||||
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.casts()).collect();
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count()));
|
||||
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
|
||||
} else {
|
||||
let mut added = vec![];
|
||||
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
|
||||
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
}
|
||||
added
|
||||
};
|
||||
for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) {
|
||||
if ink.opacity <= 0.0 {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for
|
||||
@@ -1512,16 +1563,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
|
||||
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
|
||||
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
|
||||
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
|
||||
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
|
||||
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
|
||||
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
|
||||
/// each shape, otherwise each part ([`solid_parts`]). No solid is built here: an entry with no faces
|
||||
/// (a stroke's solid left out of the art, past its own limits) casts nothing, as it draws nothing.
|
||||
/// Only `built` of another length than the solids is cast as [`cast_shadow`] casts it.
|
||||
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
@@ -1535,42 +1584,25 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
|
||||
}
|
||||
for ((s, item), kept) in items.into_iter().zip(built) {
|
||||
let ink = ink(item, s.opacity);
|
||||
if ink.opacity <= 0.0 {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept)?,
|
||||
None => {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.plane(&area, rule, b, view)?
|
||||
}
|
||||
};
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
let Some(kept) = kept else { continue };
|
||||
cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?));
|
||||
}
|
||||
return Ok(Some((caster, settings, cast)));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
|
||||
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
|
||||
let (parts, _) = solid_parts(shapes, b);
|
||||
if parts.len() != built.len() {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.extrude(area, *rule, bounds, extrude_options(p), view)
|
||||
}
|
||||
};
|
||||
for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) {
|
||||
let ink = ink(item, *member);
|
||||
// A fully transparent solid, or a stroke's solid left out of the art, casts nothing.
|
||||
let Some(kept) = kept.filter(|_| ink.casts()) else { continue };
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
|
||||
// the solids together, the shadow is refused.
|
||||
let faces = match faces {
|
||||
let faces = match caster.add_solid(kept) {
|
||||
Ok(faces) => faces,
|
||||
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
|
||||
Err(e) => return Err(e),
|
||||
|
||||
@@ -102,7 +102,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"];
|
||||
const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"];
|
||||
|
||||
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
|
||||
/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and
|
||||
@@ -127,7 +127,7 @@ const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [
|
||||
/// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude &
|
||||
/// Bevel (Classic)'s, with `surface` No Shading or Diffuse only.
|
||||
pub fn validate_rotate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?;
|
||||
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind", "preserveSpotColors"])?;
|
||||
if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) {
|
||||
return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", ")));
|
||||
}
|
||||
@@ -192,6 +192,35 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
|
||||
Color::rgb(r, g, b)
|
||||
}
|
||||
|
||||
/// Whether Preserve Spot Colors applies with parameters `p`: `preserveSpotColors` is on and the
|
||||
/// shading color is not Custom, which cannot keep a spot color.
|
||||
fn preserves_spot_colors(p: &Value) -> bool {
|
||||
flag(p, "preserveSpotColors", false) && text(p, "shadingColor", "black") != "custom"
|
||||
}
|
||||
|
||||
/// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower
|
||||
/// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where
|
||||
/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`,
|
||||
/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam
|
||||
/// stroke each layer draws around the face.
|
||||
fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option<Color>, seam: f64) -> Vec<AppearanceItem> {
|
||||
let Paint::Solid { color, swatch, tint } = paint else { return vec![] };
|
||||
let keep = (1.0 - spec).clamp(0.0, 1.0) as f32;
|
||||
let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep };
|
||||
let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))];
|
||||
if shade.is_some() && tone < 1.0 {
|
||||
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
|
||||
let mut layer = FillLayer::new(black.clone());
|
||||
layer.blend = BlendMode::Multiply;
|
||||
layer.overprint = true;
|
||||
let mut edge = crate::lighting::seam_stroke(black, seam);
|
||||
edge.blend = BlendMode::Multiply;
|
||||
edge.overprint = true;
|
||||
items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]);
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
|
||||
/// Wireframe, else the seam between faces.
|
||||
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
@@ -200,12 +229,14 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
|
||||
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
|
||||
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage.
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
|
||||
let paint = &paint;
|
||||
@@ -229,6 +260,10 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
|
||||
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
|
||||
]
|
||||
}
|
||||
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
|
||||
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
|
||||
linked_face(paint, tone, spec, shade, seam)
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
|
||||
|
||||
@@ -50,6 +50,19 @@ pub(crate) struct Ink {
|
||||
pub(crate) blend: BlendMode,
|
||||
}
|
||||
|
||||
impl Ink {
|
||||
/// Whether art in this ink casts part of a shadow ([`casts`]).
|
||||
pub(crate) fn casts(self) -> bool {
|
||||
casts(self.opacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero.
|
||||
/// Art at zero, negative, NaN or infinite opacity casts nothing.
|
||||
pub(crate) fn casts(opacity: f32) -> bool {
|
||||
opacity.is_finite() && opacity > 0.0
|
||||
}
|
||||
|
||||
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
|
||||
/// `None` when it casts nothing.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Document, NodeId, StrokeLayer};
|
||||
use vectorcraft_doc::{Document, FillLayer, NodeId, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Shape};
|
||||
|
||||
use super::*;
|
||||
@@ -1082,7 +1082,8 @@ fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result
|
||||
|
||||
/// The check builds each solid the effect draws once, about the bounds it draws it about: one for
|
||||
/// a fill and one for each stroke, on an object, on a group's members and on an appearance item,
|
||||
/// with the shadow on or off.
|
||||
/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds
|
||||
/// kept, so no solid is built again for it.
|
||||
#[test]
|
||||
fn the_check_builds_each_drawn_solid_once() {
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
@@ -1098,6 +1099,11 @@ fn the_check_builds_each_drawn_solid_once() {
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill");
|
||||
let shadow = json!({"shadow": true});
|
||||
assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on");
|
||||
let mut other = square_node();
|
||||
other.id = NodeId(2);
|
||||
let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]);
|
||||
assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on");
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1115,6 +1121,44 @@ fn the_check_builds_the_profile_of_a_shape_with_no_fill() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled shape is checked about the bounds the effect draws its solid about, which take in the
|
||||
/// strokes beside it. A shape of many small curves is too complex for Extrude & Bevel about the
|
||||
/// shapes' own bounds, where its curves are sampled more finely, and passes about the bounds of a
|
||||
/// wide stroke in its group, as its solid draws there.
|
||||
#[test]
|
||||
fn the_check_builds_a_filled_shape_about_the_bounds_its_solid_draws_about() {
|
||||
// 900 curves about (100, 100), each bulging 1 pt out from a side of a polygon 80 pt across.
|
||||
let corners = 900;
|
||||
let center = Point::new(100.0, 100.0);
|
||||
let corner = |k: usize| {
|
||||
let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos();
|
||||
Point::new(center.x + 40.0 * c, center.y + 40.0 * s)
|
||||
};
|
||||
let mut b = BezPath::new();
|
||||
b.move_to(corner(0));
|
||||
for k in 0..corners {
|
||||
let (p0, p3) = (corner(k), corner(k + 1));
|
||||
let out = p0.midpoint(p3) - center;
|
||||
let out = out / out.hypot();
|
||||
b.curve_to(p0 + (p3 - p0) / 3.0 + out, p0 + (p3 - p0) * (2.0 / 3.0) + out, p3);
|
||||
}
|
||||
b.close_path();
|
||||
let filled = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((80.0, 100.0));
|
||||
line.line_to((120.0, 100.0));
|
||||
let mut wide = Node::path(NodeId(2), PathData::from_bezpath(&line), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2000.0));
|
||||
wide.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_)));
|
||||
let p = json!({"bevel": "rounded", "bevelRepeat": 6});
|
||||
let (path, rule) = profile(&filled).unwrap();
|
||||
let own = path.bounds().unwrap().union(wide.path_data().unwrap().bounds().unwrap());
|
||||
assert_eq!(facets(EXTRUDE, &path, rule, own, &p).map(|_| ()), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()), "about its own bounds");
|
||||
let mut g = Node::group(NodeId(9999), vec![Arc::new(filled), Arc::new(wide)]);
|
||||
assert_eq!(validate_solid(&g, EXTRUDE, &p), Ok(()));
|
||||
g.appearance.effects.push(fx(EXTRUDE, p));
|
||||
assert!(solid_art(&g).is_some(), "the solid draws");
|
||||
}
|
||||
|
||||
/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke.
|
||||
fn polygon_node(id: u64, corners: usize) -> Node {
|
||||
let points: Vec<Point> = (0..corners)
|
||||
@@ -1977,6 +2021,62 @@ fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills of each face of `art`: the first is the face's paint, a second the shadow over it.
|
||||
fn face_fills(art: &Node) -> Vec<Vec<FillLayer>> {
|
||||
faces(art)
|
||||
.iter()
|
||||
.map(|f| {
|
||||
f.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f.clone()),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_preserve_spot_colors_keeps_a_linked_fill_on_every_face() {
|
||||
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2);
|
||||
let art = |params: Value| {
|
||||
let mut n = classic(params);
|
||||
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 1.0 }))];
|
||||
solid_art(&n).unwrap()
|
||||
};
|
||||
let lit = json!({"preserveSpotColors": true, "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
|
||||
let (mut highlighted, mut shaded) = (false, false);
|
||||
for layers in face_fills(&art(lit)) {
|
||||
let Paint::Solid { color, swatch: Some(name), tint } = &layers[0].paint else { panic!("the swatch is kept: {layers:?}") };
|
||||
assert_eq!(name, "Ink");
|
||||
assert_eq!(*color, ink.tinted(*tint), "the color is the swatch at the face's tint");
|
||||
highlighted |= *tint < 1.0;
|
||||
if let Some(shadow) = layers.get(1) {
|
||||
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
|
||||
assert!(k > 0.0 && k <= 1.0, "{k}");
|
||||
assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0));
|
||||
shaded = true;
|
||||
}
|
||||
assert!(layers.len() <= 2, "{layers:?}");
|
||||
}
|
||||
assert!(highlighted && shaded, "the highlight lowers the tint and the shadow adds black");
|
||||
// No shading color: the highlight only, as tints of the swatch.
|
||||
for layers in face_fills(&art(json!({"preserveSpotColors": true, "shadingColor": "none"}))) {
|
||||
assert!(matches!(&layers[..], [f] if matches!(&f.paint, Paint::Solid { swatch: Some(_), .. })), "{layers:?}");
|
||||
}
|
||||
// Off, or with a custom shading color, shaded faces are process mixes, as before.
|
||||
for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#3366cc"})] {
|
||||
let unlinked = face_fills(&art(params.clone())).iter().filter(|l| matches!(l[0].paint, Paint::Solid { swatch: None, .. })).count();
|
||||
assert!(unlinked > 0, "{params}");
|
||||
}
|
||||
// An unlinked fill is shaded as it is with the option off.
|
||||
let off: Vec<[f32; 3]> = classic_faces(json!({})).iter().map(fill_rgb).collect();
|
||||
let on: Vec<[f32; 3]> = classic_faces(json!({"preserveSpotColors": true})).iter().map(fill_rgb).collect();
|
||||
assert_eq!(off, on);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_parameters_are_checked() {
|
||||
let n = classic(json!({}));
|
||||
@@ -1996,6 +2096,7 @@ fn classic_parameters_are_checked() {
|
||||
(json!({"highlightSize": "big"}), "`highlightSize` must be a number"),
|
||||
(json!({"cap": "yes"}), "`cap` must be true or false"),
|
||||
(json!({"drawHiddenFaces": 1}), "`drawHiddenFaces` must be true or false"),
|
||||
(json!({"preserveSpotColors": "yes"}), "`preserveSpotColors` must be true or false"),
|
||||
(json!({"bevel": "fancy"}), "bevel must be none or one of"),
|
||||
(json!({"twist": 10}), "unknown parameter `twist`"),
|
||||
(json!({"lights": []}), "lights must contain one to ten lights"),
|
||||
@@ -2072,6 +2173,7 @@ fn classic_rotate_parameters_are_checked() {
|
||||
(json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"),
|
||||
(json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"),
|
||||
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
|
||||
(json!({"preserveSpotColors": null}), "`preserveSpotColors` must be true or false"),
|
||||
(json!({"highlightSize": 50}), "unknown parameter `highlightSize`"),
|
||||
(json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"),
|
||||
(json!({"shadow": true}), "unknown parameter `shadow`"),
|
||||
|
||||
@@ -312,3 +312,125 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast
|
||||
/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws
|
||||
/// nothing, and the fill's solid still casts.
|
||||
#[test]
|
||||
fn a_stroke_left_out_of_the_art_casts_no_shadow() {
|
||||
for id in [EXTRUDE, INFLATE] {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, &json!({"shadow": true}));
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut built: Vec<Option<SolidFaces>> =
|
||||
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
|
||||
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
|
||||
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
|
||||
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
|
||||
assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast");
|
||||
built[stroke] = None;
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap();
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow");
|
||||
assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing");
|
||||
assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the
|
||||
/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing.
|
||||
#[test]
|
||||
fn the_check_accepts_the_shadowed_objects_that_draw() {
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for params in shadow_settings(id) {
|
||||
for n in shadowed(id, ¶ms) {
|
||||
let mut drawn = 0;
|
||||
art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some()));
|
||||
assert!(drawn > 0, "{id} {params}");
|
||||
assert_eq!(validate_solid(&n, id, ¶ms), Ok(()), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let shadow = json!({"shadow": true});
|
||||
for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] {
|
||||
let n = stroked_square(1, 0.0, stroke);
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no
|
||||
/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off.
|
||||
#[test]
|
||||
fn the_check_casts_no_shadow_in_wireframe_mode() {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let wire = json!({"shadow": true, "render": {"mode": "wireframe"}});
|
||||
for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] {
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art,
|
||||
/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts
|
||||
/// it from the faces the solids drawn kept.
|
||||
fn cast_parts(n: &Node) -> [(Vec<f32>, String); 2] {
|
||||
let (_, fx) = solid(&n.appearance.effects).unwrap();
|
||||
let shapes = if is_container(n) {
|
||||
members(n, "").unwrap()
|
||||
} else {
|
||||
let (path, rule) = profile(n).unwrap();
|
||||
vec![Profile { path, rule, items: solid_paint_sources(n).1, opacity: 1.0, scopes: vec![] }]
|
||||
};
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap();
|
||||
[cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| {
|
||||
let (caster, settings, cast) = c.unwrap().unwrap();
|
||||
let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect();
|
||||
(inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes))))
|
||||
})
|
||||
}
|
||||
|
||||
/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one
|
||||
/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the
|
||||
/// art beside it still casts its part.
|
||||
#[test]
|
||||
fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
|
||||
// The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second
|
||||
// member, and a group's second member.
|
||||
let objects = |opacity: f32| {
|
||||
let mut fill = square_node(2, 200.0);
|
||||
for item in &mut fill.appearance.items {
|
||||
if let AppearanceItem::Fill(f) = item {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
}
|
||||
let mut member = square_node(2, 200.0);
|
||||
member.opacity = opacity;
|
||||
[
|
||||
stroked_square(1, 0.0, opacity),
|
||||
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]),
|
||||
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]),
|
||||
]
|
||||
};
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for bad in [f32::NAN, f32::INFINITY] {
|
||||
for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() {
|
||||
n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
|
||||
clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
|
||||
let expected = cast_parts(&clear);
|
||||
for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() {
|
||||
assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts");
|
||||
assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}");
|
||||
}
|
||||
let mut opacities = vec![];
|
||||
art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c)));
|
||||
assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,91 @@
|
||||
//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that
|
||||
//! can be edited on their own.
|
||||
//! can be edited on their own. Also the 3D and Materials panel's Render Settings › Wireframe, which
|
||||
//! draws those edges in place of the shaded faces while the effect stays live.
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, StrokeLayer};
|
||||
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
|
||||
use vectorcraft_three_d::Facet;
|
||||
|
||||
use super::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of,
|
||||
members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane,
|
||||
is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts,
|
||||
union_bounds,
|
||||
};
|
||||
use crate::{GeomContext, is_geometry};
|
||||
|
||||
/// The most distinct edges one object's wireframe may have.
|
||||
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
|
||||
|
||||
/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of
|
||||
/// [`RENDER_MODES`].
|
||||
pub const RENDER: &str = "render";
|
||||
|
||||
/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every
|
||||
/// face ([`renders_wireframe`]).
|
||||
pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"];
|
||||
|
||||
/// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve,
|
||||
/// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface.
|
||||
const TAKES_RENDER: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE];
|
||||
|
||||
/// The weight of a rendered wireframe edge, in points: the weight Expand as Wireframes strokes its
|
||||
/// edges with (VectorCraft's own).
|
||||
pub(crate) const WIRE_WEIGHT: f64 = 0.5;
|
||||
|
||||
/// Does effect `fx` draw as a wireframe: is it one of the effects that take [`RENDER`], with its
|
||||
/// `render.mode` set to `wireframe`?
|
||||
pub fn renders_wireframe(fx: &Effect) -> bool {
|
||||
wireframe_params(&fx.id, &fx.params)
|
||||
}
|
||||
|
||||
/// Do 3D effect `id`'s parameters `p` set it to draw as a wireframe ([`renders_wireframe`])? A
|
||||
/// command that sets them is checked against the art that mode draws: the faces' edges, with no
|
||||
/// shadow, graphics or paint copies.
|
||||
pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool {
|
||||
TAKES_RENDER.contains(&id) && p.get(RENDER).and_then(|r| r.get("mode")).and_then(Value::as_str) == Some("wireframe")
|
||||
}
|
||||
|
||||
/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the
|
||||
/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a
|
||||
/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take.
|
||||
pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> {
|
||||
let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) };
|
||||
let valid = render
|
||||
.as_object()
|
||||
.is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m))));
|
||||
if !valid {
|
||||
return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group
|
||||
/// of the edges of `faces`, each edge once ([`edges`]), stroked [`WIRE_WEIGHT`] black with round
|
||||
/// joins and no fill, as Expand as Wireframes strokes them. Like Expand as Wireframes and the
|
||||
/// Outline view, the mesh shows every edge whatever the opacity, blending mode or opacity mask of
|
||||
/// the fills, strokes and group members it is built from; the object's own transparency applies to
|
||||
/// the art as a whole. `None` past [`MAX_WIRE_EDGES`] edges, when the canvas draws the source art,
|
||||
/// as it does for a solid past its limits.
|
||||
pub(crate) fn wire_art(id: NodeId, faces: &[PathData]) -> Option<Arc<Node>> {
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), WIRE_WEIGHT);
|
||||
stroke.join = LineJoin::Round;
|
||||
let appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
|
||||
let children = edges(faces).ok()?.into_iter().map(|path| Arc::new(Node::path(id, path, appearance.clone()))).collect();
|
||||
Some(Arc::new(Node::group(id, children)))
|
||||
}
|
||||
|
||||
/// The art 3D effect `fx` in wireframe mode draws for object `id` from `shapes`: the edges of the
|
||||
/// faces it builds ([`wire_art`]). `None` when a solid can't be built or past the edge limit, when
|
||||
/// the canvas draws the source art.
|
||||
pub(crate) fn wire_surfaces(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let faces: Vec<PathData> = facet_paths(fx, shapes).ok()?.into_iter().map(|f| f.path).collect();
|
||||
Some(vec![wire_art(id, &faces)?])
|
||||
}
|
||||
|
||||
/// The grid points are rounded to before edges are compared, in points: two faces that share an
|
||||
/// edge give it once.
|
||||
const GRID: f64 = 1.0 / 1024.0;
|
||||
@@ -171,7 +240,7 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<FacesAndShadow,
|
||||
/// as it is left out of the drawn art; past the limits of the object's solids together, the result
|
||||
/// is an error, as the canvas draws the source art. Each facet carries the width of the stroke the
|
||||
/// canvas draws around it.
|
||||
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, String> {
|
||||
pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, String> {
|
||||
let label = label_of(&fx.id);
|
||||
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
|
||||
@@ -281,6 +281,210 @@ fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() {
|
||||
assert_eq!(both, alone);
|
||||
}
|
||||
|
||||
/// The leaves `art` draws: each path with its fill and stroke.
|
||||
fn leaves(art: &Node) -> Vec<(PathData, bool, Option<StrokeLayer>)> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
out.push((p.clone(), c.appearance.fill().is_some(), c.appearance.stroke().cloned()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'.
|
||||
fn drawn(n: &Node) -> Node {
|
||||
crate::revolve_art(n).or_else(|| super::super::solid_art(n)).unwrap_or_else(|| panic!("no art for {n:?}"))
|
||||
}
|
||||
|
||||
const WIRE: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, ROTATE];
|
||||
|
||||
/// Render Settings › Wireframe: each of the panel's four effects draws the edges Expand as
|
||||
/// Wireframes gives, each a 0.5 pt black stroke with round joins and no fill, in place of its
|
||||
/// shaded faces; shaded again, it draws filled faces.
|
||||
#[test]
|
||||
fn wireframe_mode_draws_the_expanded_edges_as_strokes() {
|
||||
for id in WIRE {
|
||||
let n = solid_square(id, json!({"render": {"mode": "wireframe"}}));
|
||||
let art = leaves(&drawn(&n));
|
||||
let wire = three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
assert_eq!(art.len(), wire.len(), "{id}");
|
||||
for ((path, filled, stroke), edge) in art.iter().zip(&wire) {
|
||||
assert!(!filled, "{id}: an edge has no fill");
|
||||
let stroke = stroke.as_ref().unwrap_or_else(|| panic!("{id}: an edge is stroked"));
|
||||
assert_eq!((stroke.width, stroke.join, &stroke.paint), (WIRE_WEIGHT, LineJoin::Round, &Paint::solid(Color::BLACK)), "{id}");
|
||||
assert_eq!(segments(std::slice::from_ref(path)), segments(std::slice::from_ref(edge)), "{id}");
|
||||
}
|
||||
let shaded = leaves(&drawn(&solid_square(id, json!({"render": {"mode": "shaded"}}))));
|
||||
assert!(shaded.iter().any(|(_, filled, _)| *filled), "{id}: shaded faces are filled");
|
||||
}
|
||||
// The box turned off axis shows the nine edges of its three faces.
|
||||
let n = solid_square(super::super::EXTRUDE, json!({"render": {"mode": "wireframe"}}));
|
||||
let paths: Vec<PathData> = leaves(&drawn(&n)).into_iter().map(|(p, ..)| p).collect();
|
||||
assert_eq!(segments(&paths).len(), 9);
|
||||
}
|
||||
|
||||
/// The wireframe stays live: a deeper extrusion and a turned view redraw the edges.
|
||||
#[test]
|
||||
fn wireframe_mode_follows_the_effects_settings() {
|
||||
let paths = |p: Value| -> Vec<PathData> { leaves(&drawn(&solid_square(super::super::EXTRUDE, p))).into_iter().map(|(p, ..)| p).collect() };
|
||||
let flat = bounds(&paths(json!({"render": {"mode": "wireframe"}, "depth": 10.0})));
|
||||
let deep = bounds(&paths(json!({"render": {"mode": "wireframe"}, "depth": 200.0})));
|
||||
assert!(deep.width() > flat.width() + 1.0 || deep.height() > flat.height() + 1.0, "{flat:?} {deep:?}");
|
||||
let turned = paths(json!({"render": {"mode": "wireframe"}, "rotationY": 60.0}));
|
||||
assert_ne!(segments(&turned), segments(&paths(json!({"render": {"mode": "wireframe"}}))));
|
||||
}
|
||||
|
||||
/// In wireframe mode no shadow and no graphic is drawn: only the edges.
|
||||
#[test]
|
||||
fn wireframe_mode_draws_no_shadow() {
|
||||
for id in WIRE {
|
||||
let n = solid_square(id, json!({"render": {"mode": "wireframe"}, "shadow": true}));
|
||||
let art = leaves(&drawn(&n));
|
||||
assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode works where the effect is on a fill and on a group: the fill's solid and every member's
|
||||
/// solid draw as edges, and the geometry effects after a fill's effect still apply to them.
|
||||
#[test]
|
||||
fn wireframe_mode_on_a_fill_and_on_a_group() {
|
||||
for id in WIRE {
|
||||
let mut n = solid_square(id, json!({}));
|
||||
let mut fx = n.appearance.effects.remove(0);
|
||||
fx.params["render"] = json!({"mode": "wireframe"});
|
||||
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
fill.effects_mut().push(fx.clone());
|
||||
fill.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 500.0})).unwrap());
|
||||
let art = leaves(&drawn(&n));
|
||||
assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id} on a fill");
|
||||
|
||||
let member = |x: f64, id: u64| {
|
||||
Arc::new(Node::path(NodeId(id), square(x, 100.0, 50.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)))
|
||||
};
|
||||
let mut g = Node::group(NodeId(1), vec![member(100.0, 2), member(200.0, 3)]);
|
||||
g.appearance.effects.push(fx);
|
||||
let art = leaves(&drawn(&g));
|
||||
assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id} on a group");
|
||||
// Both members' edges are drawn.
|
||||
let paths: Vec<PathData> = art.into_iter().map(|(p, ..)| p).collect();
|
||||
assert!(bounds(&paths).width() > 100.0, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh shows every edge, as Expand as Wireframes gives them, whatever the opacity of the fill
|
||||
/// and the opacity masks of the group's members; the object's own opacity stays on the art. Two
|
||||
/// members that touch, one at 50% and one masked, draw their shared edge once: seven edges.
|
||||
#[test]
|
||||
fn the_mesh_shows_every_edge_whatever_the_members_transparency() {
|
||||
let member = |x: f64, id: u64, opacity: f32| {
|
||||
let mut n = Node::path(NodeId(id), square(x, 100.0, 50.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
n
|
||||
};
|
||||
let mut masked = member(150.0, 3, 1.0);
|
||||
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(0.0, 900, 1.0), true)));
|
||||
let mut g = Node::group(NodeId(1), vec![Arc::new(member(100.0, 2, 0.5)), Arc::new(masked)]);
|
||||
g.opacity = 0.75;
|
||||
g.appearance.effects.push(crate::new_effect(ROTATE, &json!({"render": {"mode": "wireframe"}})).unwrap());
|
||||
let art = drawn(&g);
|
||||
assert_eq!(art.opacity, 0.75);
|
||||
let paths: Vec<PathData> = leaves(&art).into_iter().map(|(p, ..)| p).collect();
|
||||
assert_eq!(segments(&paths).len(), 7, "{paths:?}");
|
||||
assert_eq!(segments(&paths).len(), segments(&three_d_wireframe_in(None, &g).unwrap()).len());
|
||||
let mut scoped = 0;
|
||||
for c in art.children().into_iter().flatten() {
|
||||
c.walk(&mut |c| scoped += usize::from(c.extras().mask.is_some() || c.opacity < 1.0));
|
||||
}
|
||||
assert_eq!(scoped, 0, "no part of the mesh is masked or faded");
|
||||
// A fill at 0% still shows its mesh.
|
||||
for id in WIRE {
|
||||
let mut n = solid_square(id, json!({"render": {"mode": "wireframe"}}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.opacity = 0.0;
|
||||
}
|
||||
assert!(!leaves(&drawn(&n)).is_empty(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand Appearance of a Revolve in wireframe mode gives the stroked edges, not the shaded faces.
|
||||
#[test]
|
||||
fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() {
|
||||
let n = solid_square(crate::REVOLVE, json!({"render": {"mode": "wireframe"}}));
|
||||
let art = leaves(&crate::revolve::expand_revolve_art(&n).unwrap());
|
||||
assert_eq!(art.len(), three_d_wireframe_in(None, &n).unwrap().len());
|
||||
assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT)));
|
||||
}
|
||||
|
||||
/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and
|
||||
/// only on the panel's four effects.
|
||||
#[test]
|
||||
fn render_settings_are_validated() {
|
||||
for id in WIRE {
|
||||
for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] {
|
||||
assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}");
|
||||
}
|
||||
for bad in [
|
||||
json!({"render": "wireframe"}),
|
||||
json!({"render": null}),
|
||||
json!({"render": {"mode": "raytrace"}}),
|
||||
json!({"render": {"mode": true}}),
|
||||
json!({"render": {"mode": "wireframe", "quality": "high"}}),
|
||||
] {
|
||||
let e = crate::validate_three_d_params(id, &bad).unwrap_err();
|
||||
assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}");
|
||||
}
|
||||
// The command check on the object refuses it too.
|
||||
let n = solid_square(id, json!({}));
|
||||
assert!(crate::validate_three_d(&n, id, &json!({"render": {"mode": "x"}})).is_err(), "{id}");
|
||||
}
|
||||
for id in [super::super::CLASSIC_EXTRUDE, crate::CLASSIC_REVOLVE, super::super::CLASSIC_ROTATE] {
|
||||
let e = crate::validate_three_d_params(id, &json!({"render": {"mode": "wireframe"}})).unwrap_err();
|
||||
assert!(e.contains("`render`"), "{id}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Revolve whose shaded surface is past the budget of paint copies (a gradient with many stops) is
|
||||
/// refused shaded, but in wireframe mode, which draws only the black edges, it is accepted and drawn:
|
||||
/// on the object and on a fill.
|
||||
#[test]
|
||||
fn wireframe_mode_is_checked_against_the_edges_it_draws() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let n = solid_square(crate::REVOLVE, json!({}));
|
||||
let path = n.path_data().unwrap().clone();
|
||||
let faces = vectorcraft_three_d::revolve(&path, path.bounds().unwrap(), crate::revolve::revolve_options(&json!({}))).unwrap().len();
|
||||
let stops = crate::revolve::MAX_PAINT_COPIES / (faces * 4) / std::mem::size_of::<GradientStop>() + 1;
|
||||
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut n = n;
|
||||
n.appearance = Appearance::basic(gradient, Paint::None, 0.0).into();
|
||||
let shaded = json!({});
|
||||
let wire = json!({"render": {"mode": "wireframe"}});
|
||||
let refused = crate::validate_revolve(&n, &shaded).unwrap_err();
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
assert_eq!(crate::validate_revolve(&n, &wire), Ok(()));
|
||||
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap());
|
||||
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
|
||||
// On the fill.
|
||||
let fx = n.appearance.effects.remove(0);
|
||||
let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err());
|
||||
assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(()));
|
||||
n.appearance.items[at].effects_mut().push(fx);
|
||||
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
|
||||
}
|
||||
|
||||
/// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before.
|
||||
#[test]
|
||||
fn a_classic_effect_is_not_drawn_as_a_render_wireframe() {
|
||||
let mut n = solid_square(super::super::CLASSIC_EXTRUDE, json!({}));
|
||||
n.appearance.effects[0].params["render"] = json!({"mode": "wireframe"});
|
||||
assert!(!renders_wireframe(&n.appearance.effects[0]));
|
||||
assert!(leaves(&drawn(&n)).iter().any(|(_, filled, _)| *filled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_without_a_visible_3d_effect_is_an_error() {
|
||||
let mut n = solid_square(super::super::EXTRUDE, json!({}));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Effect › SVG Filters (`svg.filter`): an SVG `<filter>` element applied as a live raster effect.
|
||||
//! The filter runs on the object's pixels as SVG 1.1 describes it
|
||||
//! (<https://www.w3.org/TR/SVG11/filters.html>), drawn by resvg. Its lengths are in points times
|
||||
//! the effect's `scale`, its user space starts at the effect's `origin`, its object bounding box is the box of the drawn pixels, and it runs at the
|
||||
//! the effect's `scale`, its user space starts at the effect's `origin`, its axes point as the effect's `axes` say (a turned or
|
||||
//! skewed user space), its object bounding box is the box of the drawn pixels, and it runs at the
|
||||
//! Document Raster Effects resolution when the view shows the object at a finer one.
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -16,6 +17,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2};
|
||||
use crate::pixel::PixelSpace;
|
||||
use crate::util::{num, text};
|
||||
|
||||
pub mod defaults;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -1223,13 +1225,16 @@ fn region_length(v: Option<&str>, default: f64, user: bool) -> Length {
|
||||
}
|
||||
|
||||
/// An SVG filter effect: the filter's XML, how many points one of its units is, where its user
|
||||
/// space's origin lies in the document, and its region.
|
||||
/// space's origin lies in the document, which way its axes point, and its region.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SvgFilterFx {
|
||||
/// The filter as it is drawn and written ([`rebuilt`]).
|
||||
xml: Arc<str>,
|
||||
scale: f64,
|
||||
origin: Vec2,
|
||||
/// The directions of the user space's axes in the document, before `scale` ([`axes_param`]):
|
||||
/// the identity unless the user space is turned, skewed or scaled unevenly.
|
||||
axes: Affine,
|
||||
/// Its region (filter effects region): x, y, width, height.
|
||||
region: [Length; 4],
|
||||
/// Is the region in user space with a length measured against the object's box? It is then
|
||||
@@ -1249,11 +1254,92 @@ fn origin_param(p: &Value) -> Vec2 {
|
||||
Vec2::new(at(0), at(1))
|
||||
}
|
||||
|
||||
/// The largest magnitude of an entry of an SVG filter effect's `axes`.
|
||||
pub const MAX_AXIS: f64 = 1000.0;
|
||||
|
||||
/// The smallest magnitude of the determinant of an SVG filter effect's `axes`.
|
||||
pub const MIN_AXES_DET: f64 = 0.001;
|
||||
|
||||
/// The `axes` of an SVG filter effect's parameters `p`: `[a, b, c, d]`, the document directions
|
||||
/// of one unit along the filter's x axis (`[a, b]`) and its y axis (`[c, d]`), before `scale`.
|
||||
/// The identity when absent; `None` when it isn't four numbers from -[`MAX_AXIS`] to [`MAX_AXIS`]
|
||||
/// whose determinant is at least [`MIN_AXES_DET`] across ([`valid_axes`]).
|
||||
fn axes_param(p: &Value) -> Option<Affine> {
|
||||
match p.get("axes") {
|
||||
None | Some(Value::Null) => Some(Affine::IDENTITY),
|
||||
Some(v) => valid_axes(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as the linear map of an SVG filter effect's `axes` ([`axes_param`]), when it is one.
|
||||
pub fn valid_axes(v: &Value) -> Option<Affine> {
|
||||
let n: Vec<f64> = v.as_array()?.iter().map(Value::as_f64).collect::<Option<_>>()?;
|
||||
axes_of(<[f64; 4]>::try_from(n).ok()?)
|
||||
}
|
||||
|
||||
/// `[a, b, c, d]` as the linear map of an SVG filter effect's `axes`, when the effect takes it ([`valid_axes`]).
|
||||
fn axes_of([a, b, c, d]: [f64; 4]) -> Option<Affine> {
|
||||
let det = a * d - b * c;
|
||||
([a, b, c, d].iter().all(|v| v.is_finite() && v.abs() <= MAX_AXIS) && det.abs() >= MIN_AXES_DET).then(|| Affine::new([a, b, c, d, 0.0, 0.0]))
|
||||
}
|
||||
|
||||
/// A filter's user space as the SVG filter effect stores it ([`user_space`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct UserSpace {
|
||||
/// The effect's `scale`.
|
||||
pub scale: f64,
|
||||
/// The effect's `origin`.
|
||||
pub origin: [f64; 2],
|
||||
/// The effect's `axes`; `None` when the axes are the document's.
|
||||
pub axes: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// `ts`, a user space mapped to the document, as the SVG filter effect's `scale` (the square root
|
||||
/// of its area scale), `origin` and, when it turns, skews or scales unevenly, `axes`. `None` when
|
||||
/// it can't be stored: not finite, `scale` outside 0.001..1000, or `axes` the effect refuses
|
||||
/// ([`valid_axes`]).
|
||||
pub fn user_space(ts: Affine) -> Option<UserSpace> {
|
||||
let [a, b, c, d, e, f] = ts.as_coeffs();
|
||||
if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let scale = ts.determinant().abs().sqrt();
|
||||
if !(0.001..=1000.0).contains(&scale) {
|
||||
return None;
|
||||
}
|
||||
let even = b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= 1e-9 * a.max(1.0);
|
||||
if even {
|
||||
return Some(UserSpace { scale: a, origin: [e, f], axes: None });
|
||||
}
|
||||
let axes = [a, b, c, d].map(|v| v / scale);
|
||||
axes_of(axes)?;
|
||||
Some(UserSpace { scale, origin: [e, f], axes: Some(axes) })
|
||||
}
|
||||
|
||||
/// The longest a unit vector becomes under the linear part of `a` (its largest singular value).
|
||||
fn stretch(a: Affine) -> f64 {
|
||||
let [a, b, c, d, _, _] = a.as_coeffs();
|
||||
let sum = a * a + b * b + c * c + d * d;
|
||||
let det = a * d - b * c;
|
||||
(0.5 * (sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt())).sqrt()
|
||||
}
|
||||
|
||||
/// The share of a raster pixel, `space.px` points wide, that a pixel of the Document Raster Effects
|
||||
/// resolution is (at most 1).
|
||||
fn raster_resolution(space: &PixelSpace) -> f64 {
|
||||
if space.line.is_finite() && space.line > 0.0 && space.px.is_finite() && space.px > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// How many times the raster's pixels a turned filter's canvas may hold ([`SvgFilterFx::turned_canvas`]).
|
||||
const TURNED_ROOM: f64 = 4.0;
|
||||
|
||||
impl SvgFilterFx {
|
||||
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`
|
||||
/// and `origin`. `None` when `xml` isn't a filter [`check`] takes, however the effect came to
|
||||
/// hold it (an opened file, a script): the object is then drawn, printed and exported without it.
|
||||
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`,
|
||||
/// `origin` and `axes`. `None` when `xml` isn't a filter [`check`] takes, or `axes` isn't
|
||||
/// valid ([`axes_param`]), however the effect came to hold it (an opened file, a script): the
|
||||
/// object is then drawn, printed and exported without it.
|
||||
pub(crate) fn parse(p: &Value) -> Option<Self> {
|
||||
let axes = axes_param(p)?;
|
||||
let xml = checked(text(p, "xml", ""))?;
|
||||
let (wrapped, _) = wrap(&xml);
|
||||
let doc = roxmltree::Document::parse(&wrapped).ok()?;
|
||||
@@ -1272,7 +1358,17 @@ impl SvgFilterFx {
|
||||
let (window, blur) = (largest(&["radius", "kernelUnitLength"]), largest(&["stdDeviation"]));
|
||||
let box_units = f.attribute("primitiveUnits").is_some_and(|u| u.trim() == "objectBoundingBox");
|
||||
let scale = num(p, "scale", 1.0).clamp(1e-3, 1e3);
|
||||
Some(Self { xml, scale, origin: origin_param(p), region, measured, window, blur, box_units })
|
||||
Some(Self { xml, scale, origin: origin_param(p), axes, region, measured, window, blur, box_units })
|
||||
}
|
||||
|
||||
/// The filter's user space → the document: moved to `origin`, scaled by `scale`, along `axes`.
|
||||
pub fn to_doc(&self) -> Affine {
|
||||
Affine::translate(self.origin) * Affine::scale(self.scale) * self.axes
|
||||
}
|
||||
|
||||
/// The box of `bounds` (document units) in the filter's user space.
|
||||
fn user_box(&self, bounds: Rect) -> Rect {
|
||||
self.to_doc().inverse().transform_rect_bbox(bounds)
|
||||
}
|
||||
|
||||
/// The filter's region in its user space for an object whose box there is `b`: lengths in user
|
||||
@@ -1307,11 +1403,11 @@ impl SvgFilterFx {
|
||||
with_attributes(xml, &[("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())])
|
||||
}
|
||||
|
||||
/// The filter as SVG output writes it (one unit a point, [`Self::in_points`]) for an object
|
||||
/// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1
|
||||
/// can't hold it ([`Self::writes_as_svg11`]).
|
||||
pub fn written_xml(&self, bounds: Rect) -> Option<String> {
|
||||
let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?;
|
||||
/// The filter as SVG output writes it, in its user space ([`Self::to_doc`]), for an object
|
||||
/// whose box in that user space is `user_box`: in its SVG 1.1 form ([`svg11`]), `None` when SVG
|
||||
/// 1.1 can't hold it ([`Self::writes_as_svg11`]).
|
||||
pub fn written_xml(&self, user_box: Rect) -> Option<String> {
|
||||
let out = self.with_region(&self.svg11_form()?, user_box)?;
|
||||
(written_len(&out) <= MAX_WRITTEN_XML).then_some(out)
|
||||
}
|
||||
|
||||
@@ -1344,10 +1440,11 @@ impl SvgFilterFx {
|
||||
if !(space.px.is_finite() && space.px > 0.0) {
|
||||
return 1.0;
|
||||
}
|
||||
let mut s: f64 = if space.line.is_finite() && space.line > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 };
|
||||
// A length spans length × scale / px raster pixels, or a fraction of the box.
|
||||
let mut s = raster_resolution(space);
|
||||
// A length spans at most length × scale × the axes' stretch / px raster pixels, or a fraction of the box.
|
||||
let reach = self.scale * stretch(self.axes);
|
||||
for (length, most) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
|
||||
let px = if self.box_units { length * box_px.max(0.0) } else { length * self.scale / space.px };
|
||||
let px = if self.box_units { length * box_px.max(0.0) } else { length * reach / space.px };
|
||||
if px * s > most {
|
||||
s = most / px;
|
||||
}
|
||||
@@ -1373,15 +1470,21 @@ impl SvgFilterFx {
|
||||
self.measured
|
||||
}
|
||||
|
||||
/// Does one unit of the filter's user space measure one point (its `scale` is 1)?
|
||||
pub fn in_points(&self) -> bool {
|
||||
self.scale == 1.0
|
||||
/// Is the filter's user space the document's, only moved: one unit a point, its axes the
|
||||
/// document's (`scale` 1, no `axes`)?
|
||||
pub fn moves_only(&self) -> bool {
|
||||
self.scale == 1.0 && self.axes == Affine::IDENTITY
|
||||
}
|
||||
|
||||
/// Can SVG import store the filter's user space ([`Self::to_doc`]) again ([`user_space`])? Its
|
||||
/// `scale` and `axes` together can scale it past what one of them holds alone.
|
||||
pub fn opens_again(&self) -> bool {
|
||||
user_space(self.to_doc()).is_some()
|
||||
}
|
||||
|
||||
/// How far beyond `bounds` (document units) the filter can draw: its region's reach past them.
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
let b = (bounds - self.origin).scale_from_origin(1.0 / self.scale);
|
||||
let region = self.region_in(b).scale_from_origin(self.scale) + self.origin;
|
||||
let region = self.to_doc().transform_rect_bbox(self.region_in(self.user_box(bounds)));
|
||||
let reach = [bounds.x0 - region.x0, bounds.y0 - region.y0, region.x1 - bounds.x1, region.y1 - bounds.y1].into_iter().fold(0.0, f64::max);
|
||||
if reach.is_finite() { reach.min(MAX_OUTSET) } else { 0.0 }
|
||||
}
|
||||
@@ -1396,20 +1499,40 @@ impl SvgFilterFx {
|
||||
}
|
||||
// Art that draws no pixels still has a box: the whole raster stands for it.
|
||||
let (x0, y0, x1, y1) = drawn_box(data, w, h).unwrap_or((0, 0, w, h));
|
||||
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
|
||||
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
|
||||
let Some(png) = png_of(data, w, x0, y0, x1, y1).map(Arc::new) else { return };
|
||||
let k = self.scale;
|
||||
// Filter user space → the small canvas, and the image's pixels → filter user space.
|
||||
let outer = Affine::scale(s) * space.to_doc.inverse() * Affine::translate(self.origin) * Affine::scale(k);
|
||||
let place = Affine::scale(1.0 / k) * Affine::translate(-self.origin) * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
|
||||
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, (x1 - x0) as f64, (y1 - y0) as f64));
|
||||
let user = self.to_doc();
|
||||
// Filter user space → the small canvas, and the small canvas → the raster's pixels.
|
||||
let (sw, sh, outer, back) = if self.axes == Affine::IDENTITY {
|
||||
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
|
||||
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
|
||||
(sw, sh, Affine::scale(s) * space.to_doc.inverse() * user, Affine::scale(1.0 / s))
|
||||
} else {
|
||||
// The canvas measures the costly lengths in its own pixels.
|
||||
let drawn = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64);
|
||||
let Some(canvas) = self.turned_canvas(w, h, raster_resolution(space), drawn, space) else { return };
|
||||
canvas
|
||||
};
|
||||
// The source as an image, its size, and the map from its pixels to filter user space. The
|
||||
// object's box in user space is the image's box there, which resvg measures the region and
|
||||
// a primitive's lengths in the object's box against. In a turned or skewed user space the
|
||||
// source is first drawn onto the canvas's pixels, whose rows and columns run along the user
|
||||
// space's axes, and cut to the pixels it draws there: the image then lies along those axes,
|
||||
// and its box is the box of the art in the user space, not of the raster's box turned into it.
|
||||
let source = if self.axes == Affine::IDENTITY {
|
||||
let place = user.inverse() * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
|
||||
png_of(data, w, x0, y0, x1, y1).map(|png| (png, x1 - x0, y1 - y0, place))
|
||||
} else {
|
||||
on_canvas(data, w, h, sw, sh, outer * user.inverse() * space.to_doc)
|
||||
.map(|(png, cx, cy, iw, ih)| (png, iw, ih, outer.inverse() * Affine::translate(Vec2::new(cx as f64, cy as f64))))
|
||||
};
|
||||
let Some((png, iw, ih, place)) = source else { return };
|
||||
let png = Arc::new(png);
|
||||
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, iw as f64, ih as f64));
|
||||
let Some(drawn) = self.drawn_xml(b).and_then(|xml| with_id(&xml, DRAWN_ID)) else { return };
|
||||
let svg = format!(
|
||||
"<svg xmlns=\"{SVG_NS}\" xmlns:xlink=\"{XLINK_NS}\" width=\"{sw}\" height=\"{sh}\" viewBox=\"0 0 {sw} {sh}\"><defs>{drawn}</defs><g transform=\"{}\"><g filter=\"url(#{DRAWN_ID})\"><image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" transform=\"{}\" xlink:href=\"data:image/png;base64,{}\"/></g></g></svg>",
|
||||
matrix(outer),
|
||||
x1 - x0,
|
||||
y1 - y0,
|
||||
iw,
|
||||
ih,
|
||||
matrix(place),
|
||||
base64(&png)
|
||||
);
|
||||
@@ -1419,19 +1542,65 @@ impl SvgFilterFx {
|
||||
}
|
||||
let Some(mut small) = tiny_skia::Pixmap::new(sw, sh) else { return };
|
||||
resvg::render(&tree, tiny_skia::Transform::identity(), &mut small.as_mut());
|
||||
let out = if s < 1.0 {
|
||||
let out = if back == Affine::IDENTITY {
|
||||
small
|
||||
} else {
|
||||
let Some(mut full) = tiny_skia::Pixmap::new(w as u32, h as u32) else { return };
|
||||
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
|
||||
let up = (1.0 / s) as f32;
|
||||
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_scale(up, up), None);
|
||||
let [a, b, c, d, e, f] = back.as_coeffs().map(|v| v as f32);
|
||||
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
|
||||
full
|
||||
} else {
|
||||
small
|
||||
};
|
||||
if out.data().len() == data.len() {
|
||||
data.copy_from_slice(out.data());
|
||||
}
|
||||
}
|
||||
|
||||
/// The canvas a filter whose user space is turned, skewed or scaled unevenly runs on, for a
|
||||
/// `w` × `h` raster lying in the document as `space` says, at resolution `s`
|
||||
/// ([`raster_resolution`]), whose art draws within `drawn` (raster pixels): its axes are the user
|
||||
/// space's, so the filter's offsets, blurs and other lengths run along them as SVG 1.1 measures
|
||||
/// them, and it covers what the raster shows. Along each of its axes its pixels are about as
|
||||
/// large as the raster's at `s`, and coarser when it would hold more than [`TURNED_ROOM`] times
|
||||
/// as many pixels as the raster does at `s`, and when a morphology radius or kernel unit would
|
||||
/// span more than 32 of its pixels or a blur's standard deviation more than 512 (a length in the
|
||||
/// object's box measured against the art's box on the canvas). Returns its size, the map from
|
||||
/// user space to it, and the map from it to the raster's pixels; `None` when the spaces can't
|
||||
/// be measured.
|
||||
fn turned_canvas(&self, w: usize, h: usize, s: f64, drawn: Rect, space: &PixelSpace) -> Option<(u32, u32, Affine, Affine)> {
|
||||
let to_px = space.to_doc.inverse() * self.to_doc();
|
||||
let from_px = to_px.inverse();
|
||||
let ub = from_px.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
|
||||
let most = ((w as f64 * s).ceil().max(1.0) * (h as f64 * s).ceil().max(1.0) * TURNED_ROOM).max(1.0);
|
||||
// Canvas pixels a unit along each axis of the user space: as many as the raster's at `s`.
|
||||
let [a, b, c, d, _, _] = to_px.as_coeffs();
|
||||
let (mut qx, mut qy) = (s * a.hypot(b), s * c.hypot(d));
|
||||
let pixels = ub.width() * qx * ub.height() * qy;
|
||||
if pixels > most {
|
||||
let k = (most / pixels).sqrt();
|
||||
(qx, qy) = (qx * k, qy * k);
|
||||
}
|
||||
// A length along an axis spans length × q canvas pixels, or length × the art's box on the
|
||||
// canvas along that axis: both shrink with q.
|
||||
let art = from_px.transform_rect_bbox(drawn);
|
||||
for (length, cap) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
|
||||
let px = if self.box_units { length * (art.width() * qx).max(art.height() * qy) } else { length * qx.max(qy) };
|
||||
if px > cap {
|
||||
let k = cap / px;
|
||||
(qx, qy) = (qx * k, qy * k);
|
||||
}
|
||||
}
|
||||
if !(qx.is_finite() && qx > 0.0 && qy.is_finite() && qy > 0.0 && ub.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (cw, ch) = ((ub.width() * qx).ceil().max(1.0), (ub.height() * qy).ceil().max(1.0));
|
||||
// Rounding up adds at most a row and a column.
|
||||
if cw * ch > most + cw + ch + 1.0 {
|
||||
return None;
|
||||
}
|
||||
let outer = Affine::scale_non_uniform(qx, qy) * Affine::translate(Vec2::new(-ub.x0, -ub.y0));
|
||||
Some((cw as u32, ch as u32, outer, to_px * outer.inverse()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The farthest a filter's region reaches beyond the object, in points.
|
||||
@@ -1449,6 +1618,22 @@ fn drawn_box(data: &[u8], w: usize, h: usize) -> Option<(usize, usize, usize, us
|
||||
(x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1))
|
||||
}
|
||||
|
||||
/// The pixels of `data` (premultiplied RGBA8, `w` × `h`) drawn onto a `cw` × `ch` canvas through
|
||||
/// `to_canvas` (the raster's pixels → the canvas's), cut to the box of the canvas pixels that aren't
|
||||
/// transparent (the whole canvas when all are): a PNG of them, the box's corner on the canvas, and
|
||||
/// its size.
|
||||
fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affine) -> Option<(Vec<u8>, usize, usize, usize, usize)> {
|
||||
let size = tiny_skia::IntSize::from_wh(u32::try_from(w).ok()?, u32::try_from(h).ok()?)?;
|
||||
let raster = tiny_skia::Pixmap::from_vec(data.to_vec(), size)?;
|
||||
let mut canvas = tiny_skia::Pixmap::new(cw, ch)?;
|
||||
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
|
||||
let [a, b, c, d, e, f] = to_canvas.as_coeffs().map(|v| v as f32);
|
||||
canvas.draw_pixmap(0, 0, raster.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
|
||||
let (cw, ch) = (cw as usize, ch as usize);
|
||||
let (x0, y0, x1, y1) = drawn_box(canvas.data(), cw, ch).unwrap_or((0, 0, cw, ch));
|
||||
Some((png_of(canvas.data(), cw, x0, y0, x1, y1)?, x0, y0, x1 - x0, y1 - y0))
|
||||
}
|
||||
|
||||
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
|
||||
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
|
||||
use image::ImageEncoder;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every
|
||||
//! document. The set, the names and the values are VectorCraft's own, written with the filter
|
||||
//! primitives of SVG 1.1 (<https://www.w3.org/TR/SVG11/filters.html>). A default is not part of a
|
||||
//! document until it is applied or edited there: the document then holds a copy under the
|
||||
//! default's name, and that copy stands in the default's place in the lists. Every default computes
|
||||
//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors.
|
||||
|
||||
use vectorcraft_doc::SvgFilter;
|
||||
|
||||
/// A default SVG filter: its name (the `<filter>` element's `id`) and the element's XML.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DefaultFilter {
|
||||
pub name: &'static str,
|
||||
pub xml: &'static str,
|
||||
}
|
||||
|
||||
/// The default filters, in the order the lists show them.
|
||||
pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [
|
||||
DefaultFilter {
|
||||
name: "Soft Blur",
|
||||
xml: r#"<filter id="Soft Blur" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="2"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Heavy Blur",
|
||||
xml: r#"<filter id="Heavy Blur" x="-50%" y="-50%" width="200%" height="200%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="6"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Soft Shadow",
|
||||
xml: r#"<filter id="Soft Shadow" x="-30%" y="-30%" width="170%" height="170%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="3"/><feOffset dx="4" dy="4"/><feComponentTransfer><feFuncA type="linear" slope="0.5"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Hard Shadow",
|
||||
xml: r#"<filter id="Hard Shadow" x="-20%" y="-20%" width="150%" height="150%" color-interpolation-filters="sRGB"><feOffset in="SourceAlpha" dx="3" dy="3"/><feComponentTransfer><feFuncA type="linear" slope="0.6"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Glow",
|
||||
xml: r##"<filter id="Glow" x="-40%" y="-40%" width="180%" height="180%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="4" result="spread"/><feFlood flood-color="#ffd24a"/><feComposite in2="spread" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"##,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Bevel",
|
||||
xml: r##"<filter id="Bevel" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="2" result="height"/><feSpecularLighting in="height" surfaceScale="4" specularConstant="0.8" specularExponent="16" lighting-color="#ffffff" result="light"><feDistantLight azimuth="225" elevation="45"/></feSpecularLighting><feComposite in="light" in2="SourceAlpha" operator="in" result="lit"/><feComposite in="SourceGraphic" in2="lit" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"/></filter>"##,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Emboss",
|
||||
xml: r#"<filter id="Emboss" color-interpolation-filters="sRGB"><feConvolveMatrix order="3" kernelMatrix="-2 -1 0 -1 1 1 0 1 2" preserveAlpha="true"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Thicken",
|
||||
xml: r#"<filter id="Thicken" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feMorphology operator="dilate" radius="1.5"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Thin",
|
||||
xml: r#"<filter id="Thin" color-interpolation-filters="sRGB"><feMorphology operator="erode" radius="1.5"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Rough Edges",
|
||||
xml: r#"<filter id="Rough Edges" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feTurbulence type="turbulence" baseFrequency="0.05" numOctaves="2" result="waves"/><feDisplacementMap in="SourceGraphic" in2="waves" scale="6" xChannelSelector="R" yChannelSelector="G"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Grain",
|
||||
xml: r#"<filter id="Grain" color-interpolation-filters="sRGB"><feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.35 0"/><feComposite in2="SourceAlpha" operator="in" result="specks"/><feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="specks"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Grayscale",
|
||||
xml: r#"<filter id="Grayscale" color-interpolation-filters="sRGB"><feColorMatrix type="saturate" values="0"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Invert",
|
||||
xml: r#"<filter id="Invert" color-interpolation-filters="sRGB"><feComponentTransfer><feFuncR type="table" tableValues="1 0"/><feFuncG type="table" tableValues="1 0"/><feFuncB type="table" tableValues="1 0"/></feComponentTransfer></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Hue Shift",
|
||||
xml: r#"<filter id="Hue Shift" color-interpolation-filters="sRGB"><feColorMatrix type="hueRotate" values="180"/></filter>"#,
|
||||
},
|
||||
];
|
||||
|
||||
/// The default filter named `name`.
|
||||
pub fn default_filter(name: &str) -> Option<DefaultFilter> {
|
||||
DEFAULT_FILTERS.iter().copied().find(|f| f.name == name)
|
||||
}
|
||||
|
||||
impl DefaultFilter {
|
||||
/// The filter as a document holds it once it is applied or edited there.
|
||||
pub fn to_filter(self) -> SvgFilter {
|
||||
SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Listed {
|
||||
pub filter: SvgFilter,
|
||||
/// A default the document has no filter named for: applying or editing it adds a copy.
|
||||
pub default: bool,
|
||||
}
|
||||
|
||||
/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`,
|
||||
/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the
|
||||
/// document's filter of that name in its place), then the document's other filters in their order.
|
||||
pub fn listed(held: &[SvgFilter]) -> (Vec<Listed>, usize) {
|
||||
let mut out: Vec<Listed> = DEFAULT_FILTERS
|
||||
.iter()
|
||||
.map(|d| match held.iter().find(|f| f.name == d.name) {
|
||||
Some(f) => Listed { filter: f.clone(), default: false },
|
||||
None => Listed { filter: d.to_filter(), default: true },
|
||||
})
|
||||
.collect();
|
||||
let defaults = out.len();
|
||||
out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false }));
|
||||
(out, defaults)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::*;
|
||||
use crate::pixel::{Channels, PixelSpace};
|
||||
use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id};
|
||||
use crate::{PixelFx, RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `w` raster whose pixels are one point wide.
|
||||
fn space(w: usize) -> PixelSpace {
|
||||
let wd = w as f64;
|
||||
PixelSpace {
|
||||
to_doc: Affine::scale(1.0),
|
||||
px: 1.0,
|
||||
center: Point::new(wd / 2.0, wd / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wd, wd),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * wd.hypot(wd),
|
||||
}
|
||||
}
|
||||
|
||||
/// The default named `name` as the renderer reads it.
|
||||
fn fx(name: &str) -> SvgFilterFx {
|
||||
let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}"));
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true };
|
||||
match raster_effects(&[e]).first() {
|
||||
Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(),
|
||||
other => panic!("{name}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`.
|
||||
fn run(name: &str, rgb: [u8; 3]) -> Vec<u8> {
|
||||
let mut data: Vec<u8> = (0..40usize)
|
||||
.flat_map(|y| (0..40usize).map(move |x| (x, y)))
|
||||
.flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] })
|
||||
.collect();
|
||||
fx(name).apply(&mut data, 40, 40, &space(40));
|
||||
data
|
||||
}
|
||||
|
||||
fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * 40 + x) * 4;
|
||||
[d[i], d[i + 1], d[i + 2], d[i + 3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_is_a_filter_the_check_takes_under_its_own_name() {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for d in DEFAULT_FILTERS {
|
||||
assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name);
|
||||
assert!(seen.insert(d.name), "{} is listed twice", d.name);
|
||||
assert_eq!(d.name, d.name.trim());
|
||||
// Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is.
|
||||
assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name);
|
||||
assert_eq!(default_filter(d.name), Some(d));
|
||||
assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name);
|
||||
}
|
||||
assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX);
|
||||
assert_eq!(default_filter("soft blur"), None, "names match exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_draws_and_is_written_to_svg_as_a_filter() {
|
||||
let plain = {
|
||||
let mut d = vec![0u8; 40 * 40 * 4];
|
||||
for y in 10..30 {
|
||||
for x in 10..30 {
|
||||
d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]);
|
||||
}
|
||||
}
|
||||
d
|
||||
};
|
||||
for d in DEFAULT_FILTERS {
|
||||
assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name);
|
||||
assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks.
|
||||
#[test]
|
||||
fn the_color_defaults_compute_what_svg_1_1_defines() {
|
||||
let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1);
|
||||
// feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11).
|
||||
let inv = at(&run("Invert", [200, 60, 20]), 20, 20);
|
||||
assert!(near(inv, [55, 195, 235, 255]), "{inv:?}");
|
||||
// feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10).
|
||||
let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20);
|
||||
let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8;
|
||||
assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}");
|
||||
// feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave
|
||||
// R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'.
|
||||
let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20);
|
||||
let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64);
|
||||
let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8);
|
||||
assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}");
|
||||
}
|
||||
|
||||
/// The shape defaults against what their primitives define: an offset copy of the alpha behind
|
||||
/// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20).
|
||||
#[test]
|
||||
fn the_shape_defaults_move_and_resize_the_alpha() {
|
||||
let shadow = run("Hard Shadow", [200, 60, 20]);
|
||||
assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top");
|
||||
// Right of and below the art by up to 3: black at 60% alpha (premultiplied 153).
|
||||
assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]);
|
||||
assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset");
|
||||
assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left");
|
||||
let thick = run("Thicken", [200, 60, 20]);
|
||||
assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius");
|
||||
let thin = run("Thin", [200, 60, 20]);
|
||||
assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius");
|
||||
let soft = run("Soft Shadow", [200, 60, 20]);
|
||||
assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]);
|
||||
let below = at(&soft, 33, 33);
|
||||
assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() {
|
||||
let (all, defaults) = listed(&[]);
|
||||
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len()));
|
||||
assert!(all.iter().all(|l| l.default));
|
||||
let mine = SvgFilter { name: "Mine".into(), xml: "<filter id=\"Mine\"><feOffset/></filter>".into() };
|
||||
let glow = SvgFilter { name: "Glow".into(), xml: "<filter id=\"Glow\"><feOffset dx=\"1\"/></filter>".into() };
|
||||
let (all, defaults) = listed(&[mine.clone(), glow.clone()]);
|
||||
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len()));
|
||||
let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap();
|
||||
assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was");
|
||||
assert_eq!(all.last(), Some(&Listed { filter: mine, default: false }));
|
||||
assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,15 @@ use crate::{PixelFx, RasterFx, raster_effects};
|
||||
/// resolution whose pixels are `line` points wide.
|
||||
fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace {
|
||||
let (wd, hd) = (w as f64 * px, h as f64 * px);
|
||||
PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) }
|
||||
PixelSpace {
|
||||
to_doc: Affine::scale(px),
|
||||
px,
|
||||
center: Point::new(wd / 2.0, hd / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wd, hd),
|
||||
channels: Channels::Rgb,
|
||||
line,
|
||||
extent: 0.5 * wd.hypot(hd),
|
||||
}
|
||||
}
|
||||
|
||||
/// `w` × `h` premultiplied pixels: `f(x, y)` each.
|
||||
@@ -214,6 +222,154 @@ fn user_space_starts_at_the_origin() {
|
||||
assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// The opacity of `data` (`w` wide) after the filter `xml` with `params` runs on a blue square
|
||||
/// over 10..20 pt of a 40 pt raster one point a pixel, at each of `points`.
|
||||
fn turned_run(xml: &str, params: serde_json::Value, points: &[(usize, usize)]) -> Vec<u8> {
|
||||
let w = 40;
|
||||
let mut data = image(w, w, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
let mut p = params;
|
||||
p["xml"] = json!(xml);
|
||||
filter(p).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
points.iter().map(|&(x, y)| at(&data, w, x, y)[3]).collect()
|
||||
}
|
||||
|
||||
const SHIFT_X: &str = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dx="4"/></filter>"#;
|
||||
|
||||
/// With `axes`, the filter runs in its turned or skewed user space: an offset along its x axis
|
||||
/// moves the art along that axis in the document (SVG 1.1 measures a primitive's lengths in the
|
||||
/// user space of the element the filter is on).
|
||||
#[test]
|
||||
fn a_turned_user_space_moves_the_art_along_its_own_axes() {
|
||||
// The square spans 10..20 pt; moved 4 pt along x it covers 14..24 across.
|
||||
let points = [(22, 15), (15, 22), (12, 11)];
|
||||
assert_eq!(turned_run(SHIFT_X, json!({}), &points), [255, 0, 0], "the document's axes: to the right");
|
||||
// Turned a quarter turn: the filter's x axis points down the page.
|
||||
let down = turned_run(SHIFT_X, json!({ "axes": [0.0, 1.0, -1.0, 0.0] }), &points);
|
||||
assert_eq!(down, [0, 255, 0], "moved down, not to the right");
|
||||
// Skewed: one unit along y is one across and one down, so dy 4 moves the art 4 pt each way.
|
||||
let shift_y = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dy="4"/></filter>"#;
|
||||
let skewed = turned_run(shift_y, json!({ "axes": [1.0, 0.0, 1.0, 1.0] }), &[(22, 22), (11, 22), (11, 11)]);
|
||||
assert!(skewed[0] > 200 && skewed[1] < 60 && skewed[2] < 60, "moved across and down: {skewed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axes_the_effect_cannot_measure_are_not_drawn() {
|
||||
for axes in [json!([0, 0, 0, 0]), json!([1, 2]), json!([1, 0, 0, "1"]), json!([2000, 0, 0, 1]), json!([0.01, 0, 0, 0.01]), json!("turned")] {
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": SHIFT_X, "axes": axes }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "{axes}: drawn without it");
|
||||
assert!(valid_axes(&axes).is_none(), "{axes}");
|
||||
}
|
||||
assert_eq!(valid_axes(&json!([0, 1, -1, 0])), Some(Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0])));
|
||||
}
|
||||
|
||||
/// A region measured against the object's box is measured against its box in the turned user
|
||||
/// space: a diamond turned an eighth of a turn is a square there, and a flood over 0..100% of it
|
||||
/// covers the diamond alone.
|
||||
#[test]
|
||||
fn a_turned_region_is_measured_against_the_box_in_its_user_space() {
|
||||
let w = 40;
|
||||
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
|
||||
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
let flood = r##"<filter id="F" filterUnits="userSpaceOnUse" x="0%" y="0%" width="100%" height="100%"><feFlood flood-color="#ff0000"/></filter>"##;
|
||||
let h = std::f64::consts::FRAC_1_SQRT_2;
|
||||
filter(json!({ "xml": flood, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "inside the diamond");
|
||||
assert!(at(&data, w, 12, 12)[3] < 40, "outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
|
||||
}
|
||||
|
||||
/// In a turned user space, a region in the object's bounding box (the default `filterUnits`) and a
|
||||
/// primitive's lengths in it (`primitiveUnits="objectBoundingBox"`) are measured against the
|
||||
/// object's box there: on a diamond turned an eighth of a turn, a flood over 0..100% of the box
|
||||
/// covers the diamond alone.
|
||||
#[test]
|
||||
fn a_turned_filter_measures_box_units_against_the_box_in_its_user_space() {
|
||||
let w = 40;
|
||||
let h = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let region = r##"<filter id="F" x="0" y="0" width="1" height="1"><feFlood flood-color="#ff0000"/></filter>"##;
|
||||
let primitive = r##"<filter id="F" filterUnits="userSpaceOnUse" x="-1000" y="-1000" width="2000" height="2000" primitiveUnits="objectBoundingBox"><feFlood flood-color="#ff0000" x="0" y="0" width="1" height="1"/></filter>"##;
|
||||
for xml in [region, primitive] {
|
||||
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
|
||||
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
filter(json!({ "xml": xml, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "{xml}: inside the diamond");
|
||||
assert!(at(&data, w, 12, 12)[3] < 40, "{xml}: outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG import stores a filter's user space again only when `scale` and `axes` together stay within
|
||||
/// what it holds: each alone can be valid while their product is not.
|
||||
#[test]
|
||||
fn a_user_space_opens_again_only_within_what_import_stores() {
|
||||
let opens = |scale: f64, axes: serde_json::Value| filter(json!({ "xml": SHIFT_X, "scale": scale, "axes": axes })).opens_again();
|
||||
assert!(opens(1000.0, json!(null)));
|
||||
assert!(opens(2.0, json!([0.0, 1.0, -1.0, 0.0])));
|
||||
assert!(!opens(1000.0, json!([2.0, 0.0, 0.0, 2.0])), "scale 2000 across");
|
||||
assert!(!opens(0.001, json!([0.5, 0.0, 0.0, 0.5])), "scale 0.0005 across");
|
||||
let space = user_space(Affine::new([0.0, 2.0, -2.0, 0.0, 5.0, 6.0])).unwrap();
|
||||
assert_eq!((space.scale, space.origin, space.axes), (2.0, [5.0, 6.0], Some([0.0, 1.0, -1.0, 0.0])));
|
||||
}
|
||||
|
||||
/// The region of a turned filter reaches as far as its turned box does.
|
||||
#[test]
|
||||
fn a_turned_region_reaches_along_the_turned_axes() {
|
||||
let b = Rect::new(0.0, 0.0, 50.0, 50.0);
|
||||
let user = r#"<filter id="u" filterUnits="userSpaceOnUse" x="-30" y="-5" width="100" height="100"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": user })).outset(b) - 45.0).abs() < 1e-9, "45 pt below the box");
|
||||
// A quarter turn: user y runs to the left of the page, so -5..95 of it lies 95 pt left of the box.
|
||||
assert!((filter(json!({ "xml": user, "axes": [0.0, 1.0, -1.0, 0.0] })).outset(b) - 95.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// A filter skewed as far as `axes` allows runs on a canvas no larger than four times the raster's
|
||||
/// pixels, however far the skew spreads the raster's box in its user space.
|
||||
#[test]
|
||||
fn a_skewed_filter_runs_within_its_pixel_budget() {
|
||||
let (w, h) = (64, 48);
|
||||
let f = filter(json!({ "xml": SHIFT_X, "axes": [1.0, 0.0, 999.0, 1.0] }));
|
||||
let all = Rect::new(0.0, 0.0, w as f64, h as f64);
|
||||
let (cw, ch, ..) = f.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
|
||||
let (cw, ch) = (f64::from(cw), f64::from(ch));
|
||||
assert!(cw * ch <= TURNED_ROOM * (w * h) as f64 + cw + ch + 1.0, "{cw} × {ch}");
|
||||
// It still draws.
|
||||
let mut data = image(w, h, |x, y| if (20..40).contains(&x) && (10..30).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
f.apply(&mut data, w, h, &space(w, h, 1.0, 1.0));
|
||||
// A plain quarter turn keeps the raster's own pixel size.
|
||||
let turned = filter(json!({ "xml": SHIFT_X, "axes": [0.0, 1.0, -1.0, 0.0] }));
|
||||
let (cw, ch, outer, _) = turned.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
|
||||
assert_eq!((cw, ch), (48, 64));
|
||||
assert!((outer.determinant() - 1.0).abs() < 1e-9);
|
||||
// Stretched 100 times across and squeezed 100 times down: each canvas axis keeps the raster's
|
||||
// detail along it, not one column of it.
|
||||
let stretched = filter(json!({ "xml": SHIFT_X, "axes": [100.0, 0.0, 0.0, 0.01] }));
|
||||
let (cw, ch, ..) = stretched.turned_canvas(100, 100, 1.0, Rect::new(0.0, 0.0, 100.0, 100.0), &space(100, 100, 1.0, 1.0)).unwrap();
|
||||
assert_eq!((cw, ch), (100, 100));
|
||||
}
|
||||
|
||||
/// On a far skewed canvas, a radius or a standard deviation in the object's box spans no more
|
||||
/// canvas pixels than the caps allow: it is measured against the art's box on the canvas, which the
|
||||
/// skew spreads far wider than the art's box in the raster.
|
||||
#[test]
|
||||
fn a_skewed_filter_keeps_box_lengths_within_the_caps_on_its_canvas() {
|
||||
let (w, h) = (64, 48);
|
||||
let sp = space(w, h, 1.0, 1.0);
|
||||
let drawn = Rect::new(20.0, 10.0, 40.0, 30.0);
|
||||
for (xml, length, cap) in [
|
||||
("<filter id=\"m\" primitiveUnits=\"objectBoundingBox\"><feMorphology radius=\"1.5\"/></filter>", 1.5, MAX_WINDOW_PX),
|
||||
("<filter id=\"b\" primitiveUnits=\"objectBoundingBox\"><feGaussianBlur stdDeviation=\"20\"/></filter>", 20.0, MAX_BLUR_PX),
|
||||
] {
|
||||
let f = filter(json!({ "xml": xml, "axes": [1.0, 0.0, 999.0, 1.0] }));
|
||||
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
|
||||
// The art's box on the canvas: the drawn pixels taken into user space, then onto the canvas.
|
||||
let art = (outer * f.to_doc().inverse() * sp.to_doc).transform_rect_bbox(drawn);
|
||||
let px = length * art.width().max(art.height());
|
||||
assert!(px <= cap + 1e-6, "{xml}: {px} canvas pixels");
|
||||
}
|
||||
// A user-space radius spans no more than 32 canvas pixels along either axis.
|
||||
let f = filter(json!({ "xml": "<filter id=\"u\"><feMorphology radius=\"100\"/></filter>", "scale": 1000.0, "axes": [1.0, 0.0, 999.0, 1.0] }));
|
||||
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
|
||||
let [qx, _, _, qy, _, _] = outer.as_coeffs();
|
||||
assert!(100.0 * qx.max(qy) <= MAX_WINDOW_PX + 1e-6, "{qx} {qy}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_no_finer_than_the_raster_effects_resolution() {
|
||||
let w = 16;
|
||||
@@ -440,7 +596,8 @@ fn a_region_measured_against_the_box_is_written_out() {
|
||||
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-50%" y="0" width="200%" height="10"><feOffset/></filter>"#;
|
||||
let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] }));
|
||||
assert_eq!(
|
||||
f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(),
|
||||
// The object over 10..30 pt of the page: 0..20 of the user space that starts at the origin.
|
||||
f.written_xml(Rect::new(0.0, 0.0, 20.0, 10.0)).as_deref(),
|
||||
Some(r#"<filter id="r" filterUnits="userSpaceOnUse" x="-10" y="0" width="40" height="10"><feOffset/></filter>"#)
|
||||
);
|
||||
let plain = filter(json!({ "xml": RED_FLOOD }));
|
||||
|
||||
@@ -11,6 +11,7 @@ mod rasterfollow;
|
||||
mod scale;
|
||||
mod solidcontext;
|
||||
mod transformfx;
|
||||
mod typestroke;
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
@@ -1850,6 +1851,7 @@ fn rasterize_compose_leaves_the_raster_alone_when_the_sizes_do_not_fit() {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1.0, 1.0),
|
||||
size: vectorcraft_geom::Vec2::new(2.0, 2.0),
|
||||
channels: pixel::Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: std::f64::consts::SQRT_2,
|
||||
|
||||
@@ -386,9 +386,111 @@ fn a_fills_geometry_effect_shapes_the_clip_before_the_effects_around_it() {
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let exported = baked.layers.iter().find_map(|l| first_clip(l)).map(|c| clip_outline(&c).unwrap().0.bounding_box()).unwrap();
|
||||
assert!(close(exported), "exported: {exported:?}");
|
||||
// A clipping path that paints its fill keeps it, a path with the fill's effect live.
|
||||
// A clipping path that paints its fill clips alike and paints the fill it clips by.
|
||||
let painted = first_clip(&crate::evaluate_container(None, &scaled(clip_with(Paint::solid(Color::BLACK)))).unwrap()).unwrap();
|
||||
assert!(painted.clip_paint().fill.is_some(), "{painted:?}");
|
||||
assert!(close(clip_outline(&painted).unwrap().0.bounding_box()), "painted: {painted:?}");
|
||||
let fill = painted.clip_paint().fill.unwrap();
|
||||
assert!(close(fill.geometric_bounds().unwrap()), "painted fill: {fill:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_painted_clipping_paths_fill_and_stroke_effects_apply_before_the_effects_around_it() {
|
||||
// A clipping path with a black fill grown by Offset Path 10 and a 2 pt blue stroke moved 30 pt
|
||||
// right by a Transform, in a group that its Transform scales to 50 %: the fill paints the grown
|
||||
// square at half size, 60 pt across, and the stroke the square at half size, 15 pt right of
|
||||
// it, on the canvas and in an export alike.
|
||||
let mut clip = clipping_path(3, vec![]);
|
||||
clip.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0).into();
|
||||
for item in &mut clip.appearance.items {
|
||||
match item {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => f.effects.push(fx("path.offsetPath", json!({"offset": 10}))),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => s.effects.push(fx("distort.transform", json!({"moveH": 30}))),
|
||||
}
|
||||
}
|
||||
let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, clip.clone()))]);
|
||||
outer.appearance.effects.push(fx("distort.transform", json!({"scaleH": 50, "scaleV": 50})));
|
||||
fn first_clip(n: &Node) -> Option<Arc<Node>> {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: true } => children.first().cloned(),
|
||||
_ => n.children()?.iter().find_map(|c| first_clip(c)),
|
||||
}
|
||||
}
|
||||
let check = |what: &str, c: &Node| {
|
||||
let paint = c.clip_paint();
|
||||
let fill = paint.fill.as_ref().and_then(Node::geometric_bounds).unwrap();
|
||||
assert!((fill.width() - 60.0).abs() < 0.5 && (fill.height() - 60.0).abs() < 0.5, "{what} fill: {fill:?}");
|
||||
let stroke = paint.stroke.as_ref().and_then(Node::geometric_bounds).unwrap();
|
||||
assert!((stroke.width() - 50.0).abs() < 0.5 && (stroke.x0 - fill.x0 - 20.0).abs() < 0.5, "{what} stroke: {stroke:?} fill: {fill:?}");
|
||||
};
|
||||
let evaluated = crate::evaluate_container(None, &outer).unwrap();
|
||||
let canvas = first_clip(&evaluated).unwrap();
|
||||
check("canvas", &canvas);
|
||||
// The clip group's box takes in the stroke's width, as for a path that paints its stroke.
|
||||
let stroke = canvas.clip_paint().stroke.as_ref().and_then(Node::geometric_bounds).unwrap();
|
||||
let visual = evaluated.children().and_then(|ch| ch.first()).and_then(|g| g.visual_bounds()).unwrap();
|
||||
assert!(visual.x1 > stroke.x1 + 0.25, "{visual:?} {stroke:?}");
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
check("exported", &baked_clip(&d));
|
||||
// Without effects around it, the export paints the fill and the stroke as the canvas does.
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, clip_group(2, clip.clone())).unwrap();
|
||||
let paint = baked_clip(&d).clip_paint();
|
||||
let fill = paint.fill.as_ref().and_then(Node::geometric_bounds);
|
||||
let stroke = paint.stroke.as_ref().and_then(Node::geometric_bounds);
|
||||
assert_eq!(fill.map(|f| f.width()), Some(120.0), "{paint:?}");
|
||||
assert_eq!(stroke.map(|s| s.x0), Some(80.0), "{paint:?}");
|
||||
// A piece that an effect around it splits into several paths (a compound path), or puts in a
|
||||
// group with its copies, still paints.
|
||||
let NodeKind::Group { children, .. } = &canvas.kind else { panic!("not the pieces: {canvas:?}") };
|
||||
let mut split = canvas.as_ref().clone();
|
||||
let mut compound = children[0].as_ref().clone();
|
||||
compound.kind = NodeKind::Compound { children: vec![children[0].clone(), children[0].clone()], rule: vectorcraft_geom::FillRule::NonZero };
|
||||
let copies = Node::group(NodeId(9), vec![children[1].clone(), children[1].clone()]);
|
||||
if let Some(ch) = split.children_mut() {
|
||||
ch[0] = Arc::new(compound);
|
||||
ch[1] = Arc::new(copies);
|
||||
}
|
||||
let paint = split.clip_paint();
|
||||
assert!(paint.fill.is_some() && paint.stroke.is_some(), "{split:?}");
|
||||
let stroke = paint.stroke.unwrap();
|
||||
assert_eq!(stroke.children().map(|ch| ch.len()), Some(1), "only the stroke's group: {stroke:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_painted_clipping_paths_stroke_keeps_the_width_its_transform_scales_it_to() {
|
||||
// A compound clipping path with a 2 pt stroke whose Transform scales strokes to 200 % without
|
||||
// transforming the object: the export paints the stroke at 4 pt.
|
||||
let square = Node::path(NodeId(4), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default());
|
||||
let mut clip = Node::new(NodeId(3), NodeKind::Compound { children: vec![Arc::new(square)], rule: vectorcraft_geom::FillRule::NonZero });
|
||||
clip.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0).into();
|
||||
let scale = json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true});
|
||||
for item in &mut clip.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
|
||||
s.effects.push(fx("distort.transform", scale.clone()));
|
||||
}
|
||||
}
|
||||
fn widths(n: &Node, out: &mut Vec<f64>) {
|
||||
for item in &n.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
|
||||
out.push(s.width);
|
||||
}
|
||||
}
|
||||
n.children().into_iter().flatten().for_each(|c| widths(c, out));
|
||||
}
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, clip_group(2, clip)).unwrap();
|
||||
let baked = baked_clip(&d);
|
||||
let stroke = baked.clip_paint().stroke.unwrap();
|
||||
let mut found = vec![];
|
||||
widths(&stroke, &mut found);
|
||||
assert!(!found.is_empty() && found.iter().all(|w| (w - 4.0).abs() < 1e-6), "{found:?} {stroke:?}");
|
||||
// The stroke is still drawn where the path lies, as the Transform does not move the object.
|
||||
let bounds = stroke.geometric_bounds().unwrap();
|
||||
assert!((bounds.x0 - 50.0).abs() < 0.5 && (bounds.width() - 100.0).abs() < 0.5, "{bounds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within};
|
||||
use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
use crate::pixel::{Light, StrokeDirection};
|
||||
use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
@@ -117,13 +118,71 @@ fn a_hidden_shadow_follows_the_transform_it_loses() {
|
||||
assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0)));
|
||||
}
|
||||
|
||||
/// Rasterize keeps its room around the art: its image keeps its own pixel grid.
|
||||
/// Rasterize keeps its room around the art: its image keeps its own pixel grid, and the Transform
|
||||
/// effect moves the image instead ([`crate::rasterize_stage`]).
|
||||
#[test]
|
||||
fn rasterize_before_a_transform_keeps_its_options() {
|
||||
let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6}));
|
||||
let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
assert_eq!(crate::raster::followed(&effects)[0], rasterize);
|
||||
assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]);
|
||||
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
|
||||
}
|
||||
|
||||
/// The Transform effects after the last Rasterize effect move its image when, from the first of
|
||||
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
|
||||
/// ones with Transform Objects off, leave the image where it is.
|
||||
#[test]
|
||||
fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
let rasterize = || fx(crate::RASTERIZE, json!({}));
|
||||
let scale = || transform(json!({"scaleH": 200, "scaleV": 200}));
|
||||
let mut hidden = scale();
|
||||
hidden.visible = false;
|
||||
let off = transform(json!({"scaleH": 200, "objects": false}));
|
||||
let roughen = fx("distort.roughen", json!({}));
|
||||
let shadow = shadow(5.0, 5.0, 2.0);
|
||||
let cases: Vec<(Vec<Effect>, Option<Vec<usize>>)> = vec![
|
||||
(vec![rasterize(), hidden.clone()], None),
|
||||
(vec![rasterize(), off.clone()], None),
|
||||
(vec![rasterize(), hidden, off, scale()], Some(vec![3])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10})), scale()], Some(vec![1, 2])),
|
||||
// Effects before the first Transform effect go into the image; anything after it holds
|
||||
// the image back.
|
||||
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
|
||||
(vec![rasterize(), scale(), roughen], None),
|
||||
(vec![rasterize(), scale(), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
|
||||
// The Transform effect before the Rasterize effect moves the art.
|
||||
(vec![scale(), rasterize()], None),
|
||||
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
|
||||
];
|
||||
for (effects, want) in cases {
|
||||
let ids: Vec<&str> = effects.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(crate::rasterize_stage(&effects), want, "{ids:?}");
|
||||
}
|
||||
// What the image is made from hides those Transform effects; the rest stay as they are.
|
||||
let effects = [rasterize(), scale()];
|
||||
let staged = crate::staged_effects(&effects, &[1]);
|
||||
assert_eq!((staged[0].visible, staged[1].visible), (true, false));
|
||||
}
|
||||
|
||||
/// The map that moves the image is each Transform effect's map about its reference point on the
|
||||
/// bounds of the geometry it takes, in order.
|
||||
#[test]
|
||||
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
// Twice the size about the center (20, 20), then 5 pt to the right.
|
||||
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
|
||||
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
|
||||
// The second Transform effect turns about the center of what the first one made.
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = map * Point::new(20.0, 20.0);
|
||||
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
|
||||
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
|
||||
}
|
||||
|
||||
/// An SVG filter keeps its options: it paints in its own user space.
|
||||
@@ -378,6 +437,230 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() {
|
||||
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
|
||||
}
|
||||
|
||||
/// The light direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_light(effects: &[Effect]) -> Option<Light> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(
|
||||
PixelFx::Underpainting { light, .. }
|
||||
| PixelFx::RoughPastels { light, .. }
|
||||
| PixelFx::ConteCrayon { light, .. }
|
||||
| PixelFx::BasRelief { light, .. }
|
||||
| PixelFx::Plaster { light, .. }
|
||||
| PixelFx::Texturizer { light, .. },
|
||||
) => Some(light),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The stroke direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_strokes(effects: &[Effect]) -> Option<StrokeDirection> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The screen angles of the first Color Halftone `effects` draw.
|
||||
fn drawn_screens(effects: &[Effect]) -> [f64; 4] {
|
||||
match raster_effects(effects).into_iter().next() {
|
||||
Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles,
|
||||
other => panic!("expected a Color Halftone, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with.
|
||||
fn relief_then(light: &str, params: Value) -> Option<Light> {
|
||||
drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)])
|
||||
}
|
||||
|
||||
/// A light direction before a Transform effect turns and reflects with the art (y down on the
|
||||
/// page), to the nearest of the eight directions, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn bas_relief_light_follows_rotation_and_reflection() {
|
||||
assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left));
|
||||
assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom));
|
||||
assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top));
|
||||
assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right));
|
||||
// 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway
|
||||
// between Top and Top Left.
|
||||
assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft));
|
||||
// A turn of 90° counterclockwise, from each direction.
|
||||
for (from, to) in [
|
||||
("bottom", Light::Right),
|
||||
("bottomLeft", Light::BottomRight),
|
||||
("left", Light::Bottom),
|
||||
("topLeft", Light::BottomLeft),
|
||||
("top", Light::Left),
|
||||
("topRight", Light::TopLeft),
|
||||
("right", Light::Top),
|
||||
("bottomRight", Light::TopRight),
|
||||
] {
|
||||
assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}");
|
||||
}
|
||||
// Every filter with a light direction, and Bas Relief's default light (Bottom).
|
||||
for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] {
|
||||
let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))];
|
||||
assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}");
|
||||
}
|
||||
assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right));
|
||||
// The Transform effects after the filter turn it together, with one rounding at the end.
|
||||
let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))];
|
||||
assert_eq!(drawn_light(&twice), Some(Light::TopRight));
|
||||
}
|
||||
|
||||
/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest
|
||||
/// of the four, a stroke and its reverse being the same, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn stroke_axis_follows_transform() {
|
||||
let strokes = |id: &str, way: Option<&str>, params: Value| {
|
||||
let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w }));
|
||||
drawn_strokes(&[fx(id, p), transform(params)])
|
||||
};
|
||||
let sprayed = "brushStrokes.sprayedStrokes";
|
||||
let pen = "sketch.graphicPen";
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical));
|
||||
assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal));
|
||||
assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal));
|
||||
}
|
||||
|
||||
fn near4(a: [f64; 4], b: [f64; 4]) -> bool {
|
||||
a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angles before a Transform effect turn and reflect with the art.
|
||||
#[test]
|
||||
fn halftone_channels_follow_rotation_and_reflection() {
|
||||
let screens = |p: Value, transforms: &[Value]| {
|
||||
let mut effects = vec![fx("pixelate.colorHalftone", p)];
|
||||
effects.extend(transforms.iter().cloned().map(transform));
|
||||
drawn_screens(&effects)
|
||||
};
|
||||
let defaults = screens(json!({}), &[json!({"rotate": 90})]);
|
||||
assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}");
|
||||
let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]);
|
||||
assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}");
|
||||
let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]);
|
||||
assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}");
|
||||
// One Transform effect reflects, then turns; two apply in the order they are listed.
|
||||
let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25});
|
||||
let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]);
|
||||
assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}");
|
||||
let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]);
|
||||
assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}");
|
||||
}
|
||||
|
||||
/// Only the visible Transform effects listed after a filter that move the art once turn its
|
||||
/// direction; a hidden filter turns too, and a zero scale leaves it as it is.
|
||||
#[test]
|
||||
fn only_earlier_visible_single_map_effects_follow() {
|
||||
let relief = fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top));
|
||||
for params in [
|
||||
json!({"rotate": 90, "objects": false}),
|
||||
json!({"rotate": 90, "copies": 1}),
|
||||
json!({"rotate": 90, "random": true}),
|
||||
json!({"scaleH": 0, "scaleV": 0}),
|
||||
] {
|
||||
assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}");
|
||||
}
|
||||
let mut hidden = transform(json!({"rotate": 90}));
|
||||
hidden.visible = false;
|
||||
assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top));
|
||||
let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))];
|
||||
assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero));
|
||||
// A hidden filter kept when the Transform effect is applied draws turned once it is shown.
|
||||
let mut off = relief;
|
||||
off.visible = false;
|
||||
let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]);
|
||||
assert_eq!(kept.len(), 1);
|
||||
let mut shown = kept[0].clone();
|
||||
shown.visible = true;
|
||||
assert_eq!(drawn_light(&[shown]), Some(Light::Left));
|
||||
}
|
||||
|
||||
/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's
|
||||
/// effects and from each fill's and stroke's.
|
||||
fn lights_in(n: &Node) -> Vec<Light> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
for list in lists {
|
||||
out.extend(drawn_light(list));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The canvas, a fill's own effects, a group's members and export turn the light the same way.
|
||||
#[test]
|
||||
fn nested_and_baked_directions_match_canvas() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let turn = || transform(json!({"rotate": 90}));
|
||||
// A fill's own Transform effect, and the object's Transform effect over its fill.
|
||||
let fill = fill_square(31, vec![relief(), turn()]);
|
||||
let item = fill.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(item.effects()), Some(Light::Left));
|
||||
let mut over = fill_square(32, vec![relief()]);
|
||||
over.appearance.effects = vec![turn()];
|
||||
let item = over.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left));
|
||||
// A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not
|
||||
// Left (Top Left after the first turn, then Left after the second).
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let mut both = fill_square(37, vec![relief(), thirty()]);
|
||||
both.appearance.effects = vec![thirty()];
|
||||
let item = both.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft));
|
||||
// A group's Transform effect over a member's own filter and its fill's.
|
||||
let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left; 2]);
|
||||
// Baked for export: the Transform effect is applied and the filter keeps the turned light.
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap();
|
||||
d.insert(Some(layer), 1, g).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let b = baked.node(NodeId(36)).unwrap();
|
||||
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects);
|
||||
assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left));
|
||||
for id in [34, 35] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once:
|
||||
/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's).
|
||||
#[test]
|
||||
fn nested_group_turns_round_the_light_once() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]);
|
||||
let outer = group(40, vec![inner], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &outer).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]);
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
for id in [42, 43] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}");
|
||||
}
|
||||
// Three groups make 90°: Left, not Bottom Left.
|
||||
let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &three).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left]);
|
||||
}
|
||||
|
||||
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
|
||||
/// before the 3D effect, as it does without the 3D effect.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live
|
||||
//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text
|
||||
//! space, placed by the transform and filled.
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign};
|
||||
use vectorcraft_geom::{Affine, FillRule, Rect, shapes};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
/// A black run with a red stroke of `width` and round joins.
|
||||
fn style(width: f64) -> CharStyle {
|
||||
CharStyle {
|
||||
fill: Paint::solid(Color::BLACK),
|
||||
stroke: Paint::solid(red()),
|
||||
stroke_width: width,
|
||||
stroke_join: LineJoin::Round,
|
||||
..CharStyle::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 x 10 square in text space standing in for a glyph.
|
||||
fn square() -> Node {
|
||||
Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default())
|
||||
}
|
||||
|
||||
fn area(n: &Node) -> f64 {
|
||||
vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uneven_scale_fills_the_stroke_the_canvas_paints() {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill");
|
||||
assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK));
|
||||
assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0));
|
||||
assert!(stroke.appearance.stroke().is_none());
|
||||
assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red()));
|
||||
assert_eq!(stroke.id, NodeId(7));
|
||||
// 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones.
|
||||
let b = stroke.geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}");
|
||||
// The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide.
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() {
|
||||
for (xf, weight) in [
|
||||
(Affine::translate((5.0, 5.0)), 4.0),
|
||||
(Affine::scale(2.0), 8.0),
|
||||
(Affine::rotate(0.5) * Affine::scale(2.0), 8.0),
|
||||
(Affine::scale_non_uniform(-2.0, 2.0), 8.0),
|
||||
] {
|
||||
let mut piece = square();
|
||||
assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}");
|
||||
let st = piece.appearance.stroke().expect("a live stroke");
|
||||
assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width);
|
||||
assert_eq!(st.join, LineJoin::Round);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shears_and_flattening_transforms_fill_the_stroke() {
|
||||
// A shear keeps the area.
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke");
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke));
|
||||
// Flattened to a line or a point: no division by the determinant, nothing non-finite.
|
||||
for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none());
|
||||
if let Some(b) = stroke.geometric_bounds() {
|
||||
assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stroke_options_shape_the_filled_stroke_in_text_space() {
|
||||
let xf = Affine::scale_non_uniform(3.0, 1.0);
|
||||
let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf);
|
||||
// No stroke, or no weight: nothing is filled.
|
||||
assert!(filled(style(0.0)).is_none());
|
||||
assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none());
|
||||
// Inside and outside alignment are kept to their side of the square before it is scaled.
|
||||
let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap();
|
||||
assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)));
|
||||
assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside));
|
||||
let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap();
|
||||
assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds());
|
||||
// Dashes are laid out along the square in text space: half of each 10 pt is painted.
|
||||
let solid = area(&filled(style(1.0)).unwrap());
|
||||
let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() };
|
||||
let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap());
|
||||
assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() {
|
||||
let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)];
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap();
|
||||
let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
// Fitted across the stroke's box in text space (the square grown by half the weight), then scaled.
|
||||
let geom = g.geom.expect("placed");
|
||||
assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}");
|
||||
}
|
||||
@@ -43,6 +43,7 @@ pub(crate) mod graph;
|
||||
mod halftone;
|
||||
pub mod help;
|
||||
pub mod importmatches;
|
||||
mod info;
|
||||
pub(crate) mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
@@ -344,6 +345,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(docmenu::specs());
|
||||
v.extend(variablecmds::specs());
|
||||
v.extend(docinfo::specs());
|
||||
v.extend(info::specs());
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(artboardalign::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
@@ -828,6 +830,7 @@ pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
@@ -896,6 +899,9 @@ pub use brushsym::reset_transformation_changes;
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
|
||||
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
|
||||
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
|
||||
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
|
||||
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
|
||||
//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number),
|
||||
//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are
|
||||
//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
|
||||
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
|
||||
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
|
||||
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
|
||||
@@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000;
|
||||
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
|
||||
/// the answer holds an object for each.
|
||||
const MAX_SET_STEPS: usize = 100_000;
|
||||
/// The most recorded values kept in the set; the others are counted but not kept.
|
||||
const MAX_VALUES: usize = 100_000;
|
||||
/// The longest name kept (bytes).
|
||||
const MAX_NAME: usize = 1024;
|
||||
/// The most tokens listed as unread.
|
||||
@@ -56,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Read Action Set File",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
|
||||
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
|
||||
always,
|
||||
read
|
||||
)]
|
||||
@@ -73,12 +76,33 @@ pub struct AiaStep {
|
||||
pub on: Option<i64>,
|
||||
/// How many `/parameter-N` blocks it has.
|
||||
pub params: usize,
|
||||
/// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`].
|
||||
pub values: Vec<AiaValue>,
|
||||
/// Its `/parameterCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The line its block opens on (from 1).
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// A value a step was recorded with: a `/parameter-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaValue {
|
||||
/// Its `/key`, if it has one that fits an `i64`.
|
||||
pub key: Option<i64>,
|
||||
/// Its `/type`, read as UTF-8 with replacement characters, if it has one.
|
||||
pub kind: Option<String>,
|
||||
/// Its `/value`, if it is a number that fits an `i64` or text.
|
||||
pub value: Option<AiaData>,
|
||||
}
|
||||
|
||||
/// A recorded `/value` that is kept.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AiaData {
|
||||
Int(i64),
|
||||
/// The bytes of text in parentheses or of hexadecimal text.
|
||||
Text(Vec<u8>),
|
||||
}
|
||||
|
||||
/// An action: an `/action-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaAction {
|
||||
@@ -106,6 +130,8 @@ pub struct AiaSet {
|
||||
pub truncated: bool,
|
||||
/// How many steps were read in all the actions.
|
||||
steps: usize,
|
||||
/// How many recorded values were kept in all the steps.
|
||||
values: usize,
|
||||
}
|
||||
|
||||
/// A token of the text.
|
||||
@@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
|
||||
enum Kind {
|
||||
Action,
|
||||
Step,
|
||||
Param,
|
||||
/// A recorded value, and whether it is kept.
|
||||
Param(bool),
|
||||
/// A block that isn't read, or one past a cap.
|
||||
Other,
|
||||
}
|
||||
@@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin
|
||||
}
|
||||
},
|
||||
Some(Kind::Step) if numbered(name, b"parameter-") => {
|
||||
let mut kept = false;
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.params += 1;
|
||||
if set.values < MAX_VALUES {
|
||||
s.values.push(AiaValue::default());
|
||||
set.values += 1;
|
||||
kept = true;
|
||||
}
|
||||
}
|
||||
Kind::Param
|
||||
Kind::Param(kept)
|
||||
}
|
||||
Some(Kind::Param | Kind::Other) => Kind::Other,
|
||||
Some(Kind::Param(_) | Kind::Other) => Kind::Other,
|
||||
_ => {
|
||||
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
|
||||
Kind::Other
|
||||
@@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
|
||||
/// says.
|
||||
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
|
||||
if bytes.is_none() {
|
||||
/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or
|
||||
/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count
|
||||
/// says marks `set` truncated, kept or not.
|
||||
fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) {
|
||||
if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
return;
|
||||
}
|
||||
let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut());
|
||||
let Some(v) = value.filter(|_| kept) else { return };
|
||||
match (name, token) {
|
||||
(Some(b"key"), Token::Int(key)) => v.key = key,
|
||||
(Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()),
|
||||
(Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)),
|
||||
(Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
unread(&mut set, line, "}");
|
||||
}
|
||||
}
|
||||
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
|
||||
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
|
||||
check_value(&mut set, bytes, line);
|
||||
}
|
||||
_ if matches!(stack.last(), Some(Kind::Param(_))) => {
|
||||
let kept = matches!(stack.last(), Some(Kind::Param(true)));
|
||||
let name = field(&mut pending);
|
||||
set_param(&mut set, kept, name.as_deref(), token, line);
|
||||
}
|
||||
// The other values inside a recorded value, or a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
|
||||
// The values inside a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Other)) => {
|
||||
pending = None;
|
||||
}
|
||||
Token::Hex(bytes) => {
|
||||
@@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number,
|
||||
/// text that is UTF-8 (else null) with its length in bytes, or null.
|
||||
fn value_json(v: &AiaValue) -> Value {
|
||||
let mut out = json!({ "key": v.key, "type": v.kind, "value": null });
|
||||
match &v.value {
|
||||
Some(AiaData::Int(n)) => out["value"] = json!(n),
|
||||
Some(AiaData::Text(t)) => {
|
||||
out["value"] = json!(std::str::from_utf8(t).ok());
|
||||
out["bytes"] = json!(t.len());
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn read(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "actionSet.read";
|
||||
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
|
||||
@@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let label = s.label.clone().filter(|l| !l.trim().is_empty());
|
||||
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
|
||||
let values: Vec<Value> = s.values.iter().map(value_json).collect();
|
||||
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line })
|
||||
})
|
||||
.collect();
|
||||
json!({ "name": a.name, "steps": steps })
|
||||
|
||||
@@ -8,6 +8,7 @@ mod contour;
|
||||
mod cutting;
|
||||
mod document;
|
||||
mod image;
|
||||
mod packaging;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
@@ -15,6 +16,7 @@ mod shapes;
|
||||
mod typetools;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
@@ -27,6 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(cutting::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(image::specs());
|
||||
v.extend(packaging::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
|
||||
@@ -9,7 +9,7 @@ mod tests;
|
||||
mod text;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
use vectorcraft_pathops::addons as po;
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Simplify Anchors (Keep Shape)…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts",
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step when a path changes; open ends stay; from the selection, locked and hidden paths are left out, and named by `ids`, the paths of the objects, groups and layers it names are taken even when locked or hidden, but not those on a locked artboard; a changed path loses its selected anchors and segments → {ids, before, after} anchor counts",
|
||||
has_selection,
|
||||
simplify
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Deep Ungroup…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step when a group goes; each object keeps the opacity of the groups it was in; from the selection, locked and hidden groups stay whole; named by `ids`, the groups it names and the groups in the groups and layers it names are ungrouped even when locked or hidden (a named layer stays), but not those on a locked artboard, and their objects become hidden or locked when a group was; locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
has_selection,
|
||||
deep_ungroup
|
||||
),
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rejoin Path Pieces…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}",
|
||||
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step when a path is made; from the selection, locked and hidden paths are left out, and named by `ids`, they are taken, but not those on a locked artboard; only pieces alike in being hidden (by themselves or a group or layer above them) and in being locked join; locked and hidden paths made are not selected → {ids, joined (paths made), removed (pieces merged into them)}",
|
||||
has_selection,
|
||||
rejoin
|
||||
),
|
||||
@@ -91,9 +91,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included; locked and hidden
|
||||
/// paths, and those in locked or hidden groups, stay out.
|
||||
fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
/// Whether a request names its objects with `ids` (present and not null) rather than taking the
|
||||
/// selection.
|
||||
fn named(p: &Value) -> bool {
|
||||
p.get("ids").is_some_and(|v| !v.is_null())
|
||||
}
|
||||
|
||||
/// Keep the items of `items` whose object (`id`) a command acts on: when `named`, every one not on
|
||||
/// a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer)
|
||||
/// included; else only those that can be edited.
|
||||
fn retain_targets<T>(d: &Document, items: &mut Vec<T>, named: bool, id: impl Fn(&T) -> NodeId) {
|
||||
if named {
|
||||
let locks = d.locked_artboards();
|
||||
items.retain(|t| !locks.holds_id(id(t)));
|
||||
} else {
|
||||
let editable = d.editable();
|
||||
items.retain(|t| editable(id(t)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included, that a command acts on
|
||||
/// ([`retain_targets`]).
|
||||
fn paths_under(d: &Document, roots: &[NodeId], named: bool) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for n in roots.iter().filter_map(|id| d.node(*id)) {
|
||||
n.walk(&mut |c| {
|
||||
@@ -102,8 +121,7 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
});
|
||||
}
|
||||
let editable = d.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
retain_targets(d, &mut out, named, |id| *id);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -116,7 +134,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let protect = switch_or(p, "protectCorners", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = paths_under(d, &roots);
|
||||
let ids = paths_under(d, &roots, named(p));
|
||||
let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect();
|
||||
let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum();
|
||||
if before > MAX_ANCHORS {
|
||||
@@ -258,10 +276,11 @@ fn ungroupable(n: &Node, clips: bool) -> bool {
|
||||
}
|
||||
|
||||
/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts
|
||||
/// the groups. Members take on the opacity of the groups they were in, and a clipping path
|
||||
/// becomes a plain path. A locked or hidden group stays whole.
|
||||
fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) || n.locked || !n.visible {
|
||||
/// the groups. Members take on the opacity of the groups they were in, are hidden when one of them
|
||||
/// was hidden and locked when one of them was locked, and a clipping path becomes a plain path. A
|
||||
/// locked or hidden group stays whole unless `named`.
|
||||
fn flatten(n: Node, clips: bool, named: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) || (!named && (n.locked || !n.visible)) {
|
||||
out.push(n);
|
||||
return;
|
||||
}
|
||||
@@ -276,26 +295,57 @@ fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
*clipping = false;
|
||||
}
|
||||
c.opacity *= n.opacity;
|
||||
flatten(c, clips, out, count);
|
||||
c.visible &= n.visible;
|
||||
c.locked |= n.locked;
|
||||
flatten(c, clips, named, out, count);
|
||||
}
|
||||
}
|
||||
|
||||
/// The outermost groups Deep Ungroup takes apart in layer `n`, its sublayers included, in paint
|
||||
/// order, leaving out those on a locked artboard.
|
||||
fn groups_in_layer(d: &Document, n: &Node, clips: bool, out: &mut Vec<NodeId>) {
|
||||
let locks = d.locked_artboards();
|
||||
fn visit(n: &Node, clips: bool, locks: &LockedArtboards, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_layer() {
|
||||
visit(c, clips, locks, out);
|
||||
} else if ungroupable(c, clips) && !locks.holds_id(c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(n, clips, &locks, out);
|
||||
}
|
||||
|
||||
fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.cleanup.deepUngroup";
|
||||
let clips = switch_or(p, "includeClipGroups", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let named = named(p);
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Locked and hidden objects, and those in locked or hidden groups, stay as they are.
|
||||
let roots: Vec<NodeId> = {
|
||||
let editable = d.editable();
|
||||
roots.into_iter().filter(|id| editable(*id)).collect()
|
||||
};
|
||||
// From the selection, locked and hidden objects, and those in locked or hidden groups, stay as
|
||||
// they are; named, only those on a locked artboard do.
|
||||
retain_targets(d, &mut roots, named, |id| *id);
|
||||
// A named layer stays: the groups in it, and in its sublayers, are taken apart.
|
||||
let mut groups = vec![];
|
||||
for id in roots {
|
||||
match d.node(id) {
|
||||
Some(n) if named && n.is_layer() => {
|
||||
let at = groups.len();
|
||||
groups_in_layer(d, n, clips, &mut groups);
|
||||
if groups.len() == at {
|
||||
groups.push(id);
|
||||
}
|
||||
}
|
||||
_ => groups.push(id),
|
||||
}
|
||||
}
|
||||
let (mut items, mut selected, mut count) = (vec![], vec![], 0);
|
||||
for id in &roots {
|
||||
for id in &groups {
|
||||
match d.node(*id).filter(|n| ungroupable(n, clips)) {
|
||||
Some(n) => {
|
||||
let mut out = vec![];
|
||||
flatten(n.clone(), clips, &mut out, &mut count);
|
||||
flatten(n.clone(), clips, named, &mut out, &mut count);
|
||||
selected.extend(out.iter().map(|n| n.id));
|
||||
items.push((*id, out));
|
||||
}
|
||||
@@ -304,7 +354,7 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// With no group to take apart, the document, the selection and the undo history stay as they
|
||||
// are, and the reply lists the selection.
|
||||
if items.is_empty() {
|
||||
if count == 0 {
|
||||
selected = s.doc()?.selection.objects.to_vec();
|
||||
} else {
|
||||
selected = s.edit("Deep Ungroup", move |d, sel| {
|
||||
@@ -319,26 +369,39 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<_>>(), "ungrouped": count }))
|
||||
}
|
||||
|
||||
/// One path Rejoin Path Pieces takes: its id, its subpath, and whether it and every group and layer
|
||||
/// above it are visible, and whether they are all unlocked.
|
||||
type Piece = (NodeId, SubPath, (bool, bool));
|
||||
|
||||
/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order
|
||||
/// (compound path members, clipping paths and guides stay out).
|
||||
fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> {
|
||||
fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) {
|
||||
/// (compound path members, clipping paths and guides stay out; [`retain_targets`]).
|
||||
fn pieces(d: &Document, roots: &[NodeId], named: bool) -> Vec<Piece> {
|
||||
fn visit(n: &Node, above: (bool, bool), out: &mut Vec<Piece>) {
|
||||
let state = (above.0 && n.visible, above.1 && !n.locked);
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => {
|
||||
if let [sp] = path.subpaths.as_slice()
|
||||
&& !sp.closed
|
||||
{
|
||||
out.push((n.id, sp.clone()));
|
||||
out.push((n.id, sp.clone(), state));
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, state, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out));
|
||||
let editable = d.editable();
|
||||
out.retain(|(id, _)| editable(*id));
|
||||
for (id, n) in roots.iter().filter_map(|id| Some((*id, d.node(*id)?))) {
|
||||
// The groups and layers above the root, and their state.
|
||||
let above = d.ancestry(id).unwrap_or_default();
|
||||
let above = above.split_last().map_or(&[][..], |(_, up)| up);
|
||||
if above.last().and_then(|i| d.node(*i)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })) {
|
||||
continue;
|
||||
}
|
||||
let state = above.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), a| (v && a.visible, u && !a.locked));
|
||||
visit(n, state, &mut out);
|
||||
}
|
||||
retain_targets(d, &mut out, named, |piece| piece.0);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -349,18 +412,26 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`gap` must be from 0 to 6 pt"));
|
||||
}
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let found = pieces(&s.doc()?.doc, &roots);
|
||||
let found = pieces(&s.doc()?.doc, &roots, named(p));
|
||||
if found.len() > MAX_OBJECTS {
|
||||
return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into()));
|
||||
}
|
||||
let subpaths: Vec<SubPath> = found.iter().map(|(_, sp)| sp.clone()).collect();
|
||||
// Each chain becomes its topmost piece (the last in paint order); the others go.
|
||||
// Only pieces alike in being shown and in being unlocked join, so that a joined path neither
|
||||
// shows hidden art nor hides shown art, nor locks or unlocks a piece.
|
||||
let (mut kept, mut gone) = (vec![], vec![]);
|
||||
for j in po::rejoin(&subpaths, gap) {
|
||||
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect();
|
||||
let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue };
|
||||
gone.extend(ids.into_iter().filter(|id| *id != top));
|
||||
kept.push((top, j.path));
|
||||
for state in [(true, true), (true, false), (false, true), (false, false)] {
|
||||
let part: Vec<&Piece> = found.iter().filter(|f| f.2 == state).collect();
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let subpaths: Vec<SubPath> = part.iter().map(|f| f.1.clone()).collect();
|
||||
// Each chain becomes its topmost piece (the last in paint order); the others go.
|
||||
for j in po::rejoin(&subpaths, gap) {
|
||||
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| part.get(m).map(|f| f.0)).collect();
|
||||
let Some(top) = j.members.iter().max().and_then(|&m| part.get(m).map(|f| f.0)) else { continue };
|
||||
gone.extend(ids.into_iter().filter(|id| *id != top));
|
||||
kept.push((top, j.path));
|
||||
}
|
||||
}
|
||||
if !kept.is_empty() {
|
||||
let ids: Vec<NodeId> = kept.iter().map(|k| k.0).collect();
|
||||
@@ -369,7 +440,9 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_path(d, *id, PathData::single(sp.clone()));
|
||||
}
|
||||
d.remove_many(&gone)?;
|
||||
sel.set(ids);
|
||||
// Locked and hidden paths, and those in locked or hidden groups, are not selected.
|
||||
let editable = d.editable();
|
||||
sel.set(ids.into_iter().filter(|id| editable(*id)));
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, Rect};
|
||||
|
||||
use crate::Session;
|
||||
@@ -123,18 +123,100 @@ fn simplify_leaves_locked_and_hidden_paths_alone() {
|
||||
assert_eq!(r["before"], 16);
|
||||
assert!(anchors(&s, ids[0]) < 16);
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
// Named by `ids`, or in a locked group, a path stays too, with no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap();
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// In a selected locked group, a path stays too, with no undo step.
|
||||
change(&mut s, ids[1], |n| n.locked = false);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0)));
|
||||
assert_eq!(anchors(&s, ids[1]), 16);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// Named by `ids`, the locked group's paths, its hidden one included, are simplified.
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([ids[0].0, ids[1].0, ids[2].0]));
|
||||
assert!(anchors(&s, ids[1]) < 16 && anchors(&s, ids[2]) < 16);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// A path of 16 anchors at (`x`, `y`): an ellipse with anchors added twice.
|
||||
fn ellipse16(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
let e = id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 50, "height": 50})).unwrap());
|
||||
select(s, &[e]);
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
e
|
||||
}
|
||||
|
||||
/// Simplify Anchors takes the locked and hidden paths `ids` names, those in the locked or hidden
|
||||
/// groups and layers it names (their locked and hidden members too) and a hidden compound path's
|
||||
/// member, as one undo step, without selecting them; from the selection it leaves them alone, and a
|
||||
/// path on a locked artboard stays even when named.
|
||||
#[test]
|
||||
fn simplify_named_locked_and_hidden_paths() {
|
||||
let mut s = session();
|
||||
let locked = ellipse16(&mut s, 10.0, 10.0);
|
||||
let hidden = ellipse16(&mut s, 70.0, 10.0);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, hidden, |n| n.visible = false);
|
||||
// A locked group with a hidden member, and a hidden group with a locked member.
|
||||
let in_locked = ellipse16(&mut s, 130.0, 10.0);
|
||||
let locked_group = wrap(&mut s, in_locked, |c| NodeKind::Group { children: c, clip: false });
|
||||
change(&mut s, locked_group, |n| n.locked = true);
|
||||
change(&mut s, in_locked, |n| n.visible = false);
|
||||
let in_hidden = ellipse16(&mut s, 190.0, 10.0);
|
||||
let hidden_group = wrap(&mut s, in_hidden, |c| NodeKind::Group { children: c, clip: false });
|
||||
change(&mut s, hidden_group, |n| n.visible = false);
|
||||
change(&mut s, in_hidden, |n| n.locked = true);
|
||||
// A member of a hidden compound path.
|
||||
let member = ellipse16(&mut s, 250.0, 10.0);
|
||||
let compound = wrap(&mut s, member, |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
|
||||
change(&mut s, compound, |n| n.visible = false);
|
||||
// A path in a locked layer, named itself.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let in_layer = ellipse16(&mut s, 10.0, 100.0);
|
||||
let on_board = ellipse16(&mut s, 10.0, 200.0);
|
||||
change(&mut s, layer, |n| n.locked = true);
|
||||
let all = [locked, hidden, in_locked, in_hidden, member, in_layer];
|
||||
select(&mut s, &[locked, hidden, locked_group, hidden_group, compound]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]), "from the selection, none is taken");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
|
||||
select(&mut s, &[]);
|
||||
s.edit("Select Anchors", |_, sel| {
|
||||
sel.anchors.insert(locked, [(0, 1)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0, hidden.0, locked_group.0, hidden_group.0, member.0, in_layer.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!(all.iter().map(|i| i.0).collect::<Vec<_>>()));
|
||||
assert_eq!(r["before"], 16 * 6);
|
||||
assert_eq!(r["after"].as_u64(), Some(all.iter().map(|id| anchors(&s, *id) as u64).sum::<u64>()));
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) < 16), "{r}");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "nothing is selected, and the changed path's anchors are not");
|
||||
let n = node(&s, in_hidden).unwrap();
|
||||
assert!(n.locked && n.visible && !node(&s, hidden_group).unwrap().visible);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) < 16));
|
||||
// Nothing left to remove: no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// On a locked artboard, a named path stays as it is.
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [on_board.0]})).unwrap();
|
||||
assert_eq!((r["ids"].clone(), anchors(&s, on_board), undo_steps(&s)), (json!([]), 16, steps));
|
||||
}
|
||||
|
||||
/// Each kind: what makes the issue in a fresh document (beside a clean rectangle).
|
||||
@@ -610,14 +692,15 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible);
|
||||
assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
// Named by `ids`, a locked group stays as it is, with no undo step.
|
||||
// Named by `ids`, a locked group is taken apart as one undo step; its member becomes locked
|
||||
// and is not selected.
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(r["ungrouped"], 0);
|
||||
assert!(node(&s, locked).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(r["ungrouped"], 1);
|
||||
assert!(node(&s, locked).is_none() && node(&s, c).unwrap().locked);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
// With nothing ungrouped, the selection stays and the reply lists it.
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap();
|
||||
@@ -625,6 +708,108 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
}
|
||||
|
||||
/// Put `ids` inside a new container that `kind` makes of its members.
|
||||
fn wrap_all(s: &mut Session, ids: &[NodeId], kind: fn(Vec<std::sync::Arc<Node>>) -> NodeKind) -> NodeId {
|
||||
s.edit("t", |d, _| {
|
||||
let w = d.alloc_id();
|
||||
Ok(d.wrap(ids, |c| Node::new(w, kind(c)))?)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn plain_group(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
|
||||
NodeKind::Group { children: c, clip: false }
|
||||
}
|
||||
|
||||
fn sublayer(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
|
||||
NodeKind::Layer { color: LayerColor::Preset(0), template: false, printable: true, children: c, clip: false, preview: true, dim_images: None }
|
||||
}
|
||||
|
||||
/// Named by `ids`, Deep Ungroup takes apart locked and hidden groups, those nested in a group it
|
||||
/// names and those in a layer it names (its sublayers included, the layer staying), as one undo
|
||||
/// step; their members become locked or hidden as the groups were, keep the groups' opacity and are
|
||||
/// not selected. From the selection those groups stay whole, as do a clipping group and a group on a
|
||||
/// locked artboard even when named.
|
||||
#[test]
|
||||
fn deep_ungroup_named_locked_and_hidden_groups() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
let locked = wrap_all(&mut s, &[a], plain_group);
|
||||
let hidden = wrap_all(&mut s, &[b], plain_group);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, hidden, |n| {
|
||||
n.visible = false;
|
||||
n.opacity = 0.5;
|
||||
});
|
||||
select(&mut s, &[locked, hidden]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, they stay whole");
|
||||
assert!(node(&s, locked).is_some() && node(&s, hidden).is_some());
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0, hidden.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(2), json!([])));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(node(&s, locked).is_none() && node(&s, hidden).is_none());
|
||||
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
|
||||
assert!(na.locked && na.visible && !nb.visible && !nb.locked);
|
||||
assert_eq!(nb.opacity, 0.5);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, locked).is_some() && !node(&s, a).unwrap().locked && node(&s, b).unwrap().visible);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(node(&s, locked).is_none() && node(&s, a).unwrap().locked);
|
||||
// Locked and hidden groups nested in a named group that can be edited.
|
||||
let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
|
||||
let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
let inner_locked = wrap_all(&mut s, &[e], plain_group);
|
||||
let inner_hidden = wrap_all(&mut s, &[f], plain_group);
|
||||
change(&mut s, inner_locked, |n| n.locked = true);
|
||||
change(&mut s, inner_hidden, |n| n.visible = false);
|
||||
let outer = wrap_all(&mut s, &[c, inner_locked, inner_hidden], plain_group);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [outer.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(3), json!([c.0])));
|
||||
assert!(node(&s, e).unwrap().locked && !node(&s, f).unwrap().visible);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [c]);
|
||||
// In a named layer and its sublayer; the layers and a clipping group stay.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let g = rect(&mut s, 10.0, 100.0, 20.0, 20.0);
|
||||
let h = rect(&mut s, 40.0, 100.0, 20.0, 20.0);
|
||||
let layer_locked = wrap_all(&mut s, &[g], plain_group);
|
||||
change(&mut s, layer_locked, |n| n.locked = true);
|
||||
let layer_hidden = wrap_all(&mut s, &[h], plain_group);
|
||||
change(&mut s, layer_hidden, |n| n.visible = false);
|
||||
let sub = wrap_all(&mut s, &[layer_hidden], sublayer);
|
||||
let clipped = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let clip = rect(&mut s, 95.0, 95.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let clip_group = s.doc().unwrap().selection.objects[0];
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [layer.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(2), steps + 1));
|
||||
assert!(node(&s, layer_locked).is_none() && node(&s, layer_hidden).is_none());
|
||||
assert!(node(&s, layer).is_some() && node(&s, clip_group).is_some());
|
||||
assert!(node(&s, g).unwrap().locked && !node(&s, h).unwrap().visible);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(h), Some(sub));
|
||||
// On a locked artboard, a named group stays whole, with the selection as it was.
|
||||
let k = rect(&mut s, 10.0, 200.0, 20.0, 20.0);
|
||||
let on_board = wrap_all(&mut s, &[k], plain_group);
|
||||
let off_board = rect(&mut s, 500.0, 10.0, 20.0, 20.0);
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[off_board]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [on_board.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone(), undo_steps(&s)), (json!(0), json!([off_board.0]), steps));
|
||||
assert!(node(&s, on_board).is_some());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [off_board]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
let mut s = session();
|
||||
@@ -646,3 +831,74 @@ fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Named by `ids`, Rejoin Path Pieces takes locked and hidden pieces (in a locked group or layer
|
||||
/// too) and joins only pieces alike in being hidden and in being locked, whichever is topmost, as one
|
||||
/// undo step; a locked or hidden path it makes is not selected. From the selection it takes only
|
||||
/// pieces that can be edited, and compound path members and pieces on a locked artboard stay out.
|
||||
#[test]
|
||||
fn rejoin_named_locked_and_hidden_pieces() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]);
|
||||
let b = line(&mut s, &[(50.05, 10.0), (90.0, 10.0)]);
|
||||
let g = wrap_all(&mut s, &[a, b], plain_group);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
select(&mut s, &[g]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, none is taken");
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([b.0])));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked path is not selected");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).is_some() && anchors(&s, b) == 2);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
|
||||
// A shown piece and two hidden ones, the hidden on top: only the hidden pair joins.
|
||||
let c = line(&mut s, &[(10.0, 40.0), (50.0, 40.0)]);
|
||||
let e = line(&mut s, &[(50.05, 40.0), (90.0, 40.0)]);
|
||||
let h = line(&mut s, &[(90.05, 40.0), (130.0, 40.0)]);
|
||||
change(&mut s, e, |n| n.visible = false);
|
||||
change(&mut s, h, |n| n.visible = false);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [c.0, e.0, h.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([h.0])));
|
||||
assert!(node(&s, e).is_none() && anchors(&s, c) == 2 && anchors(&s, h) == 3);
|
||||
assert!(!node(&s, h).unwrap().visible && node(&s, c).unwrap().visible);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden path is not selected");
|
||||
// An unlocked piece under a locked one, and a hidden piece under a shown one: none joins.
|
||||
let k = line(&mut s, &[(10.0, 70.0), (50.0, 70.0)]);
|
||||
let m = line(&mut s, &[(50.05, 70.0), (90.0, 70.0)]);
|
||||
let n = line(&mut s, &[(10.0, 100.0), (50.0, 100.0)]);
|
||||
let o = line(&mut s, &[(50.05, 100.0), (90.0, 100.0)]);
|
||||
change(&mut s, m, |x| x.locked = true);
|
||||
change(&mut s, n, |x| x.visible = false);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [k.0, m.0, n.0, o.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), undo_steps(&s)), (json!(0), json!(0), steps));
|
||||
assert!([k, m, n, o].iter().all(|id| anchors(&s, *id) == 2));
|
||||
// Named pieces in a locked layer join; members of a compound path stay out.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let p = line(&mut s, &[(10.0, 130.0), (50.0, 130.0)]);
|
||||
let q = line(&mut s, &[(50.05, 130.0), (90.0, 130.0)]);
|
||||
let u = line(&mut s, &[(10.0, 160.0), (50.0, 160.0)]);
|
||||
let v = line(&mut s, &[(50.05, 160.0), (90.0, 160.0)]);
|
||||
wrap_all(&mut s, &[u, v], |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
|
||||
let w = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)]);
|
||||
let x = line(&mut s, &[(50.05, 200.0), (90.0, 200.0)]);
|
||||
change(&mut s, layer, |l| l.locked = true);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [p.0, q.0, u.0, v.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["ids"].clone()), (json!(1), json!([q.0])));
|
||||
assert!(node(&s, p).is_none() && anchors(&s, u) == 2 && anchors(&s, v) == 2);
|
||||
// On a locked artboard, named pieces stay as they are.
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [w.0, x.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps));
|
||||
assert!(node(&s, w).is_some() && node(&s, x).is_some());
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
|
||||
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
|
||||
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
|
||||
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod roles;
|
||||
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::super::CommandSpec;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
roles::specs()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`,
|
||||
//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top
|
||||
//! stroke is painted with the swatch the document's role table gives that role, at any tint. The
|
||||
//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut,
|
||||
//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a
|
||||
//! string, takes its default swatch, named after the role.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Document unknown key: the role table, `{role id: swatch name}`.
|
||||
pub(crate) const ROLES_KEY: &str = "packagingRoles";
|
||||
|
||||
const SET_ROLE: &str = "addon.packaging.setRole";
|
||||
const ROLES: &str = "addon.packaging.roles";
|
||||
const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
|
||||
|
||||
/// What a fold line does when the blank is cut and folded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Role {
|
||||
/// Separates the material.
|
||||
Cut,
|
||||
/// A fold.
|
||||
Crease,
|
||||
/// A fold cut part way through the board.
|
||||
PartialCut,
|
||||
/// A fold along a line of cuts.
|
||||
Perforation,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation];
|
||||
|
||||
/// The role's id in params and in the role table.
|
||||
pub(crate) fn id(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "cut",
|
||||
Role::Crease => "crease",
|
||||
Role::PartialCut => "partialCut",
|
||||
Role::Perforation => "perforation",
|
||||
}
|
||||
}
|
||||
|
||||
/// The role's name, which is also its default swatch's name.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "Cut",
|
||||
Role::Crease => "Crease",
|
||||
Role::PartialCut => "Partial Cut",
|
||||
Role::Perforation => "Perforation",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_id(id: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| r.id() == id)
|
||||
}
|
||||
|
||||
/// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta,
|
||||
/// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan.
|
||||
fn color(self) -> Color {
|
||||
match self {
|
||||
Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0),
|
||||
Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0),
|
||||
Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0),
|
||||
Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
Role::ALL.iter().position(|r| *r == self).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatch each role is carried by, in [`Role::ALL`] order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct RoleTable([String; 4]);
|
||||
|
||||
impl RoleTable {
|
||||
/// The document's role table, with each missing or damaged entry at its default. When a damaged
|
||||
/// table names one swatch for two roles, the later role takes its default name instead, or
|
||||
/// "Crease 2" and so on when an earlier role has that.
|
||||
pub(crate) fn of(d: &Document) -> RoleTable {
|
||||
let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object);
|
||||
let mut names: Vec<String> = Vec::with_capacity(Role::ALL.len());
|
||||
for r in Role::ALL {
|
||||
let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) {
|
||||
Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(),
|
||||
_ => {
|
||||
let base = r.name();
|
||||
std::iter::once(base.to_string())
|
||||
.chain((2..).map(|i| format!("{base} {i}")))
|
||||
.find(|n| !names.contains(n))
|
||||
.unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
};
|
||||
names.push(name);
|
||||
}
|
||||
RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string())))
|
||||
}
|
||||
|
||||
/// The swatch of `role`.
|
||||
pub(crate) fn swatch(&self, role: Role) -> &str {
|
||||
self.0.get(role.index()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// The role swatch `name` carries.
|
||||
pub(crate) fn role_of_swatch(&self, name: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| self.swatch(*r) == name)
|
||||
}
|
||||
|
||||
/// The role of object `n`: the role of the swatch its top stroke is painted with.
|
||||
pub(crate) fn role_of(&self, n: &Node) -> Option<Role> {
|
||||
if !can_carry(n) {
|
||||
return None;
|
||||
}
|
||||
match &n.appearance.stroke()?.paint {
|
||||
Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(&self) -> Value {
|
||||
Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::<Map<_, _>>())
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color.
|
||||
/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped
|
||||
/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a
|
||||
/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no
|
||||
/// two roles share a swatch.
|
||||
pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) {
|
||||
let before = RoleTable::of(d);
|
||||
let mut table = before.clone();
|
||||
for r in Role::ALL {
|
||||
let name = table.swatch(r).to_string();
|
||||
let moved = if name == from && global {
|
||||
Some(to.to_string())
|
||||
} else if name == from || (name == to && from != to) {
|
||||
Some(free_role_name(d, &table, r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
if table != before {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes
|
||||
/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the
|
||||
/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other
|
||||
/// role keeps its name, which the next `setRole` makes a swatch for.
|
||||
pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) {
|
||||
let mut table = RoleTable::of(d);
|
||||
if !linked || table.role_of_swatch(kept).is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return };
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = kept.to_string();
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
|
||||
/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the
|
||||
/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search
|
||||
/// always ends at a free one.
|
||||
fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
|
||||
let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n);
|
||||
let base = role.name();
|
||||
if free(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
|
||||
/// guide, or a compound path.
|
||||
fn can_carry(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
|
||||
/// groups, each once, and
|
||||
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
|
||||
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
|
||||
/// are on a locked artboard are left out and counted as skipped.
|
||||
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } => {
|
||||
for c in children {
|
||||
// A group's clipping path draws no stroke: it is skipped.
|
||||
if matches!(c.kind, NodeKind::Path { clipping: true, .. }) {
|
||||
*skipped += 1;
|
||||
} else {
|
||||
walk(c, out, skipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => *skipped += 1,
|
||||
}
|
||||
}
|
||||
let (mut out, mut skipped) = (vec![], 0);
|
||||
// A path of a compound path is painted with the compound's appearance: the compound takes the
|
||||
// role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a
|
||||
// group and its member are never both roots.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) {
|
||||
walk(n, &mut out, &mut skipped);
|
||||
}
|
||||
if editable {
|
||||
// Named directly or not, a locked or hidden object, or one in a locked or hidden group or
|
||||
// layer or on a locked artboard, stays as it is.
|
||||
let ok = d.editable();
|
||||
let before = out.len();
|
||||
out.retain(|id| ok(*id));
|
||||
skipped += before - out.len();
|
||||
}
|
||||
(out, skipped)
|
||||
}
|
||||
|
||||
/// Every object of the document that can carry a role, through layers and groups.
|
||||
fn document_targets(d: &Document) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.packaging.setRole",
|
||||
"Make Fold Line",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
has_selection,
|
||||
set_role
|
||||
),
|
||||
cmd!(
|
||||
query "addon.packaging.roles",
|
||||
"Fold Lines",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
|
||||
has_doc,
|
||||
roles
|
||||
),
|
||||
cmd!(
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"Role Swatches…",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}",
|
||||
has_doc,
|
||||
set_role_swatch
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The role `p` gives: `Some(None)` for `none` when `none` is allowed.
|
||||
fn role_param(p: &Value, cmd: &str, none: bool) -> Result<Option<Role>> {
|
||||
let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?;
|
||||
match Role::from_id(id) {
|
||||
Some(r) => Ok(Some(r)),
|
||||
None if none && id == "none" => Ok(None),
|
||||
None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))),
|
||||
None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why swatch `name` of `d` can't carry a role, if it can't.
|
||||
fn unfit_swatch(d: &Document, name: &str) -> Option<String> {
|
||||
if name == REGISTRATION || name == "[None]" {
|
||||
return Some(format!("`{name}` can't carry a role"));
|
||||
}
|
||||
let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) };
|
||||
match &sw.paint {
|
||||
Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")),
|
||||
Paint::Solid { .. } if sw.global => None,
|
||||
Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")),
|
||||
_ => Some(format!("`{name}` isn't a color swatch")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d`
|
||||
/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process
|
||||
/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a
|
||||
/// free name, which the role table then gives the role.
|
||||
fn role_paint(d: &mut Document, role: Role) -> Result<Paint> {
|
||||
let mut table = RoleTable::of(d);
|
||||
let current = table.swatch(role);
|
||||
let taken = match d.swatch(current) {
|
||||
Some(_) => unfit_swatch(d, current).is_some(),
|
||||
None => d.swatch_name_taken(current),
|
||||
};
|
||||
if taken {
|
||||
let free = free_role_name(d, &table, role);
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = free;
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
let name = table.swatch(role);
|
||||
if d.swatch(name).is_none() {
|
||||
let model = d.color_mode.model();
|
||||
let color = role.color();
|
||||
let color = if color.model() == model {
|
||||
color
|
||||
} else {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cms.convert(&color, model, cms.settings().intent)
|
||||
};
|
||||
d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true });
|
||||
}
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name())));
|
||||
}
|
||||
d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color")))
|
||||
}
|
||||
|
||||
/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed.
|
||||
fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool {
|
||||
let Some(n) = d.node_mut(id) else { return false };
|
||||
let had = table.role_of(n);
|
||||
let mut a = (*n.appearance).clone();
|
||||
match paint {
|
||||
Some(paint) => {
|
||||
a.set_stroke(paint.clone());
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
// A hidden stroke would carry the role without drawing or printing the line.
|
||||
st.visible = true;
|
||||
st.overprint = overprint;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if had.is_none() {
|
||||
return false;
|
||||
}
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if let Paint::Solid { color, .. } = st.paint {
|
||||
st.paint = Paint::solid(color);
|
||||
}
|
||||
st.overprint = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if a == *n.appearance {
|
||||
return false;
|
||||
}
|
||||
n.appearance = vectorcraft_doc::Shared::new(a);
|
||||
true
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let role = role_param(p, SET_ROLE, true)?;
|
||||
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
|
||||
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
|
||||
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
|
||||
}
|
||||
let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line");
|
||||
let mut changed = 0;
|
||||
edit_counted(s, label, |d| {
|
||||
let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned());
|
||||
let paint = role.map(|r| role_paint(d, r)).transpose()?;
|
||||
// A role swatch made again (its strokes may still name it) is a change of its own.
|
||||
let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before;
|
||||
let table = RoleTable::of(d);
|
||||
changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count();
|
||||
Ok(changed + usize::from(made))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
|
||||
}
|
||||
|
||||
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, ROLES)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (scope, ids) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", role_targets(d, &roots, false).0),
|
||||
(false, false) => ("selection", role_targets(d, &roots, false).0),
|
||||
(false, true) => ("document", document_targets(d)),
|
||||
};
|
||||
let table = RoleTable::of(d);
|
||||
let mut counts = [0usize; 4];
|
||||
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
|
||||
if let Some(c) = counts.get_mut(r.index()) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let rows: Vec<Value> = Role::ALL
|
||||
.into_iter()
|
||||
.zip(counts)
|
||||
.map(|(r, count)| {
|
||||
let swatch = table.swatch(r);
|
||||
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
|
||||
}
|
||||
|
||||
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) };
|
||||
let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, why));
|
||||
}
|
||||
let mut table = RoleTable::of(d);
|
||||
if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name())));
|
||||
}
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = name.to_string();
|
||||
}
|
||||
let value = table.to_value();
|
||||
let changed = RoleTable::of(d) != table;
|
||||
if changed {
|
||||
s.edit("Role Swatches", |d, _| {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), value);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "role": role.id(), "swatch": name, "changed": changed }))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Tests for Packaging Tools: fold line roles, their swatches and the role table.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session(mode: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.setRole", &p).unwrap()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, cmd: &str, p: Value) -> String {
|
||||
s.execute(cmd, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// The `roles` query's counts, in role order.
|
||||
fn counts(s: &mut Session, p: Value) -> Vec<u64> {
|
||||
let r = s.execute("addon.packaging.roles", &p).unwrap();
|
||||
r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sw = d.swatch("Cut").unwrap();
|
||||
assert!(sw.global && sw.spot, "{sw:?}");
|
||||
assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document");
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint);
|
||||
assert!(st.overprint, "role strokes overprint by default");
|
||||
// Again: nothing changes, and no undo step is recorded.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
// Undo takes the swatch away with the role.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() {
|
||||
let mut s = session("rgb");
|
||||
for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() {
|
||||
let id = rect(&mut s, 20.0 + 60.0 * i as f64);
|
||||
set_role(&mut s, json!({"role": role, "ids": [id.0]}));
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let colors: Vec<Color> = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect();
|
||||
assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}");
|
||||
assert_eq!(colors.iter().map(|c| c.to_hex()).collect::<BTreeSet<_>>().len(), 4, "four colors: {colors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("strip", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
n.appearance.items.retain(AppearanceItem::is_fill);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(node(&s, a).appearance.stroke().is_none());
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false}));
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.width, 1.0, "a 1 pt stroke");
|
||||
assert!(!st.overprint);
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_takes_the_role_away_and_keeps_the_color() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap();
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.paint, Paint::solid(shown));
|
||||
assert!(!st.overprint);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]);
|
||||
// Nothing left with a role: no undo step.
|
||||
set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_roles_and_targets_are_refused() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected");
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap());
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch");
|
||||
// Text beside a path is skipped and counted.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_walked_and_their_locked_and_hidden_members_left_out() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
d.node_mut(c).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]);
|
||||
// Named directly, a locked or hidden path is left out too.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2)));
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_s_clipping_path_is_skipped_and_counted() {
|
||||
let mut s = session("cmyk");
|
||||
let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0, b.0]), "each path once");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A locked line keeps its role and is counted, whether its group is selected or not.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it");
|
||||
assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_free_role_swatch_name_is_searched_past_ten_thousand() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]);
|
||||
let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false };
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000"));
|
||||
assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name");
|
||||
assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line");
|
||||
// A kept swatch that already carries a role keeps it; the merged role's lines take it.
|
||||
s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]);
|
||||
// The next Make Cut Line makes the Cut role's swatch again.
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_process_swatch_can_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_counts_the_selection_or_the_whole_document() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]}));
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2)));
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0)));
|
||||
assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]);
|
||||
let rows = r["roles"].as_array().unwrap();
|
||||
assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2}));
|
||||
assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_maps_a_role_to_another_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
// The old swatch's objects keep their color and lose the role.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
// The same mapping again changes nothing.
|
||||
let steps_now = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_role_swatch_keeps_its_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
// A swatch that carries no role leaves the table alone.
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"}));
|
||||
// Undo puts the old name back in the table with the swatch.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
// No Crease swatch exists yet, so the name is free for the Cut swatch.
|
||||
s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role");
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [b.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_group_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch");
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back");
|
||||
assert_eq!(steps(&s), before + 1, "as one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_stroke_is_shown_when_it_takes_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) {
|
||||
st.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(node(&s, a).appearance.stroke().unwrap().visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_refuses_swatches_that_cannot_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
for (swatch, says) in [
|
||||
("Nope", "no swatch"),
|
||||
("Ramp", "isn't a color swatch"),
|
||||
("Plain", "process color"),
|
||||
("Ink Tint", "tint swatch"),
|
||||
("[None]", "can't carry a role"),
|
||||
("[Registration]", "can't carry a role"),
|
||||
("Crease", "already carries the Crease role"),
|
||||
] {
|
||||
let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch}));
|
||||
assert!(e.contains(says), "{swatch}: {e}");
|
||||
}
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch"));
|
||||
assert_eq!(steps(&s), before, "no refusal records an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_role_table_reads_as_the_defaults() {
|
||||
let mut s = session("cmyk");
|
||||
s.edit("damage", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]);
|
||||
s.edit("not an object", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!("Cut"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
// One swatch named for two roles: the later role takes its own default.
|
||||
s.edit("duplicate", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]);
|
||||
let b = rect(&mut s, 100.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_save_and_open_keep_the_role_table_and_the_roles() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
/// A document with one rectangle of each of Cut and Crease.
|
||||
fn two_roles() -> Session {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, format: &str) -> String {
|
||||
String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() {
|
||||
let mut s = two_roles();
|
||||
let c = rect(&mut s, 180.0);
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&s.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
let pdf = String::from_utf8_lossy(&bytes);
|
||||
assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate");
|
||||
assert!(pdf.contains("/Separation/Crease"));
|
||||
assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space");
|
||||
assert!(pdf.contains("/OP true"), "the role strokes overprint");
|
||||
// Without overprint, nothing in the file overprints.
|
||||
let mut plain = session("cmyk");
|
||||
let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0));
|
||||
set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false}));
|
||||
set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&plain.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("/OP true"));
|
||||
assert!(!export(&mut s, "pdf").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() {
|
||||
let mut s = two_roles();
|
||||
let svg = export(&mut s, "svg");
|
||||
let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect();
|
||||
let strokes = if strokes.is_empty() {
|
||||
svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect()
|
||||
} else {
|
||||
strokes
|
||||
};
|
||||
assert_eq!(strokes.len(), 2, "two stroke colors: {svg}");
|
||||
let dxf = export(&mut s, "dxf");
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
// The rectangles' white fills come out as true colors too.
|
||||
let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect();
|
||||
assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}");
|
||||
let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap();
|
||||
let plot = String::from_utf8_lossy(&b64(&plot)).into_owned();
|
||||
assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_paths_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. }));
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]}));
|
||||
assert_eq!(r["ids"], json!([c.0]));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]);
|
||||
// A member named by id gives its compound the role.
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
@@ -531,8 +531,13 @@ fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() {
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap();
|
||||
assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1));
|
||||
assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays");
|
||||
// Stretched across its own axes (it is turned): skewed, so no longer.
|
||||
// Stretched along its turned bounding box: still the shape, wider along its own axis.
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap();
|
||||
let r = shape_of(&s, id).unwrap();
|
||||
assert!((r.width - 300.0).abs() < 1e-6 && (r.height - 200.0).abs() < 1e-6 && (r.rotation + 30.0).abs() < 1e-6, "{r:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Stretched across the page's axes (it is turned): skewed, so no longer.
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140], "basis": "page"})).unwrap();
|
||||
assert_eq!(shape_of(&s, id), None);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(shape_of(&s, id).is_some(), "undo brings it back");
|
||||
@@ -1220,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
|
||||
let mut centred = 0;
|
||||
for id in ids(&r) {
|
||||
let sp = path(&s, id).subpaths[0].clone();
|
||||
if let [a, b, c] = sp.anchors.as_slice()
|
||||
if let [a, b, c] = &*sp.anchors.to_vec()
|
||||
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
|
||||
{
|
||||
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
|
||||
|
||||
@@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::super::links::{Status, statuses};
|
||||
use super::super::panelcmds::listed_artboards;
|
||||
use super::super::select::{is_selectable, on_artboard, selectable};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param};
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
|
||||
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select by Artboards",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
"{artboards: [index…] (0-based whole numbers, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
has_doc,
|
||||
by_artboards
|
||||
),
|
||||
@@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`relation` must be overlap, inside or outside"));
|
||||
}
|
||||
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
|
||||
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
|
||||
if indices.is_empty() {
|
||||
if listed.as_array().is_some_and(Vec::is_empty) {
|
||||
return Err(bad(C, "choose at least one artboard"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let rects =
|
||||
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
|
||||
let rects: Vec<_> =
|
||||
listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect();
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
|
||||
.into_iter()
|
||||
|
||||
@@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is
|
||||
/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past
|
||||
/// the last artboard each have their own error.
|
||||
#[test]
|
||||
fn artboard_errors_say_what_is_wrong() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers";
|
||||
let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices";
|
||||
for (p, want) in [
|
||||
(json!({"artboards": ["1"]}), entries),
|
||||
(json!({"artboards": [-1]}), entries),
|
||||
(json!({"artboards": [1.5]}), entries),
|
||||
(json!({"artboards": [true]}), entries),
|
||||
(json!({"artboards": [9, "1"]}), entries),
|
||||
(json!({"artboards": "0"}), not_a_list),
|
||||
(json!({"artboards": null}), not_a_list),
|
||||
(json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"),
|
||||
(json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"),
|
||||
(json!({"artboards": [9]}), "no such artboard"),
|
||||
(json!({"artboards": [0, 9]}), "no such artboard"),
|
||||
] {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
|
||||
}
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_is_measured_by_its_art() {
|
||||
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release Type on a Path…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path (when the type starts before an open path's start, the first character drawn on the path stays where it was drawn and the characters that were not drawn come before it); Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
@@ -229,6 +229,28 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin)
|
||||
}
|
||||
|
||||
/// A glyph of a character: its byte, whether it stands for characters (a list marker does not),
|
||||
/// and its place among the glyphs of that byte and kind (an All Caps ß is two glyphs).
|
||||
type GlyphKey = (usize, bool, usize);
|
||||
|
||||
/// The key and pen position of the first glyph drawn in `lay`, in text order: characters before an
|
||||
/// open path's start are not drawn ([`vectorcraft_text::PositionedGlyph::off_path`]). None without
|
||||
/// a drawn glyph.
|
||||
fn first_drawn_pen(lay: &vectorcraft_text::TextLayout) -> Option<(GlyphKey, Point)> {
|
||||
let (gi, g) = (lay.glyphs.iter().enumerate())
|
||||
.filter(|(_, g)| !g.off_path && g.origin.x.is_finite() && g.origin.y.is_finite())
|
||||
.min_by_key(|(gi, g)| (g.byte, g.len != 0, *gi))?;
|
||||
let kind = g.len != 0;
|
||||
let nth = lay.glyphs.iter().take(gi).filter(|h| h.byte == g.byte && (h.len != 0) == kind).count();
|
||||
Some(((g.byte, kind, nth), g.origin))
|
||||
}
|
||||
|
||||
/// The pen position of the glyph `key` names in `lay`. None without one.
|
||||
fn pen_at(lay: &vectorcraft_text::TextLayout, (byte, kind, nth): GlyphKey) -> Option<Point> {
|
||||
let g = lay.glyphs.iter().filter(|g| g.byte == byte && (g.len != 0) == kind).nth(nth)?;
|
||||
(g.origin.x.is_finite() && g.origin.y.is_finite()).then_some(g.origin)
|
||||
}
|
||||
|
||||
/// `t`, type on a path, as point type on one straight line: the same runs and character and
|
||||
/// paragraph attributes, its baseline starting where its first character sat on the path (in the
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped, and
|
||||
@@ -237,13 +259,14 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
let TextKind::OnPath { path, .. } = &t.kind else { return None };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Where the first character sat. Text that didn't fit on the path has no glyph there: it
|
||||
// starts at the start bracket.
|
||||
let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| {
|
||||
// Where the first drawn character sat; characters before an open path's start come before it
|
||||
// on the line. Text that didn't fit on the path has no glyph there: it starts at the start
|
||||
// bracket.
|
||||
let (key, at) = first_drawn_pen(&vectorcraft_text::layout(db, t)).map(|(b, p)| (Some(b), p)).or_else(|| {
|
||||
let ap = ArcPath::new(path);
|
||||
let (from, _) = t.kind.path_span()?;
|
||||
let (p, _) = ap.at(from * ap.len());
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some((None, p))
|
||||
})?;
|
||||
let mut out = t.clone();
|
||||
// Point type has no brackets to fit: it keeps the sizes the path drew it at.
|
||||
@@ -254,9 +277,10 @@ fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
out.path_spacing = 0.0;
|
||||
// Point type is in no thread: its first paragraph starts in it.
|
||||
out.first_para_continues = false;
|
||||
// Where the point type puts its own first character; the origin moves so it lands at `at`,
|
||||
// whatever the paragraph's alignment and direction.
|
||||
let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO);
|
||||
// Where the point type puts that glyph; the origin moves so it lands at `at`, whatever the
|
||||
// paragraph's alignment and direction.
|
||||
let own_lay = vectorcraft_text::layout(db, &out);
|
||||
let own = key.and_then(|k| pen_at(&own_lay, k)).or_else(|| first_pen(&own_lay)).unwrap_or(Point::ZERO);
|
||||
let shift = at - own;
|
||||
if !(shift.x.is_finite() && shift.y.is_finite()) {
|
||||
return None;
|
||||
|
||||
@@ -482,6 +482,44 @@ mod release {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type that starts before its open path: the first drawn character stays where it was drawn,
|
||||
/// and the characters that were not drawn come before it on the line.
|
||||
#[test]
|
||||
fn type_starting_before_its_open_path_keeps_its_drawn_characters_in_place() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Hidden start");
|
||||
s.execute("type.pathOptions", &json!({"start": -0.05})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &before);
|
||||
let first = lay.glyphs.iter().filter(|g| !g.off_path).min_by_key(|g| g.byte).unwrap();
|
||||
let (byte, drawn) = (first.byte, before.xf * first.origin);
|
||||
assert!(byte > 0, "some characters are before the path");
|
||||
s.execute(C, &json!({"mode": "text"})).unwrap();
|
||||
let after = text(&s, id);
|
||||
assert_eq!(after.kind, TextKind::Point);
|
||||
assert_eq!(after.plain_text(), before.plain_text());
|
||||
let back = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &after);
|
||||
let same = back.glyphs.iter().find(|g| g.byte == byte).unwrap();
|
||||
assert!(close(after.xf * same.origin, drawn), "{:?} vs {drawn:?}", after.xf * same.origin);
|
||||
let lead = back.glyphs.iter().find(|g| g.byte == 0).unwrap();
|
||||
assert!((after.xf * lead.origin).x < drawn.x, "the hidden characters come before it");
|
||||
// An All Caps ß is two glyphs: with the first before the path's start, the second stays
|
||||
// where it was drawn.
|
||||
let id = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "ße");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "allCaps": true})).unwrap();
|
||||
let adv = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, id)).glyphs[0].advance;
|
||||
s.execute("type.pathOptions", &json!({"start": -1.2 * adv / 400.0})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &before);
|
||||
assert!(lay.glyphs[0].byte == 0 && lay.glyphs[1].byte == 0 && lay.glyphs[0].off_path && !lay.glyphs[1].off_path);
|
||||
let drawn = before.xf * lay.glyphs[1].origin;
|
||||
s.execute(C, &json!({"mode": "text"})).unwrap();
|
||||
let after = text(&s, id);
|
||||
let back = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &after);
|
||||
let second = back.glyphs.iter().filter(|g| g.byte == 0).nth(1).unwrap();
|
||||
assert!(close(after.xf * second.origin, drawn), "{:?} vs {drawn:?}", after.xf * second.origin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipped_type_releases_its_path_as_it_runs() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, 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)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, 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)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Effect",
|
||||
[],
|
||||
None,
|
||||
"{…as effect.apply} same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?, target?} → {ids, index, item}",
|
||||
"{…as effect.apply} same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?, target?, aligned?} → {ids, index, item}",
|
||||
has_doc,
|
||||
super::effectcmd::apply
|
||||
),
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, 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)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, 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)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -183,14 +183,21 @@ pub(crate) struct ActiveItem {
|
||||
impl Session {
|
||||
/// The method returns explicit target parameters and the selected appearance effect list.
|
||||
pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> {
|
||||
let mut ids = appearance_targets(self, params).ok()?;
|
||||
let mut ids = drop_design_art(&self.active()?.doc, appearance_targets(self, params).ok()?);
|
||||
let item = item_target(self, params, "effect.apply").ok()?;
|
||||
let anchor = item.anchor(self, &ids);
|
||||
let node = self.active()?.doc.node(*ids.get(anchor)?)?;
|
||||
// Aligned effects given with a graph design's art first are effects of the art's stack, which stays first; the
|
||||
// Appearance panel's active row is a row of the first selected object's.
|
||||
let of = match item {
|
||||
ItemTarget::Item { explicit: false, .. } => None,
|
||||
_ => design_reference(self, params, "effect.apply").ok()?,
|
||||
};
|
||||
let own = *ids.get(anchor)?;
|
||||
let node = self.active()?.doc.node(of.unwrap_or(own))?;
|
||||
let at = item.effects_item(&node.appearance, "effect.apply").ok()?;
|
||||
let effects = node.appearance.effects_at(at)?;
|
||||
ids.swap(0, anchor);
|
||||
let ids: Vec<u64> = ids.into_iter().map(|id| id.0).collect();
|
||||
let ids: Vec<u64> = with_reference(of, &ids).into_iter().map(|id| id.0).collect();
|
||||
let aligned = match item {
|
||||
ItemTarget::Item { aligned, .. } => aligned,
|
||||
ItemTarget::Top => aligned(params, "effect.apply").ok()?,
|
||||
@@ -253,6 +260,10 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))),
|
||||
// The active item is a row of the first selected object's own stack.
|
||||
None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top),
|
||||
// A row of a graph design's art in a series stands for nothing: the commands leave that art out.
|
||||
None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => {
|
||||
Ok(ItemTarget::Top)
|
||||
}
|
||||
None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false, aligned: true })),
|
||||
}
|
||||
}
|
||||
@@ -300,6 +311,21 @@ impl ItemTarget {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
|
||||
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
|
||||
/// an equal item is left out (`None`).
|
||||
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
|
||||
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
|
||||
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
|
||||
Some(ItemTarget::Item { index, explicit: true, aligned: true })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
/// is: the first selected object (or the compound path holding it) for the active item, which
|
||||
/// need not paint first; the first target otherwise, or when that object is not among them.
|
||||
@@ -384,6 +410,41 @@ pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], id
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of a graph design in a graph series whose stack the aligned rows of `p` (`aligned: true`) are rows of: the
|
||||
/// first of the [`appearance_targets`] when it is such art, which the edit leaves out ([`without_design_art`]). A
|
||||
/// command reads it after its own target checks.
|
||||
pub(crate) fn design_reference(s: &Session, p: &Value, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if !aligned(p, cmd)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(ids.first().copied().filter(|id| super::graph::is_design_art(d, *id)))
|
||||
}
|
||||
|
||||
/// The [`design_reference`] of an edit aimed at `item`: none for the Appearance panel's active row, which is a row of the
|
||||
/// first selected object's stack.
|
||||
pub(crate) fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if matches!(item, ItemTarget::Item { explicit: false, .. }) {
|
||||
return Ok(None);
|
||||
}
|
||||
design_reference(s, p, cmd)
|
||||
}
|
||||
|
||||
/// `ids` after `of` (see [`design_reference`]), when there is one.
|
||||
pub(crate) fn with_reference(of: Option<NodeId>, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
of.into_iter().chain(ids.iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// [`items_per_target`] of `ids`, with the aligned rows `idx` taken from the stack of `of` (see [`design_reference`])
|
||||
/// when there is one: a row a target has no equal of is left out of that target.
|
||||
pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec<Vec<usize>> {
|
||||
match of {
|
||||
Some(of) => items_per_target(d, &with_reference(Some(of), ids), idx, true).into_iter().skip(1).collect(),
|
||||
None => items_per_target(d, ids, idx, aligned),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
|
||||
fn targets_contents(p: &Value) -> Result<bool> {
|
||||
match p.get("target") {
|
||||
@@ -424,22 +485,44 @@ const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn a
|
||||
|
||||
/// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series
|
||||
/// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets
|
||||
/// are all such art is refused.
|
||||
pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
/// are all such art is refused as an error of `cmd`.
|
||||
pub(crate) fn edit_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = appearance_targets(s, p)?;
|
||||
without_design_art(&s.doc()?.doc, ids, "appearance")
|
||||
without_design_art(&s.doc()?.doc, ids, cmd)
|
||||
}
|
||||
|
||||
/// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else.
|
||||
pub(crate) fn without_design_art(d: &Document, mut ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn without_design_art(d: &Document, ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let given = ids.len();
|
||||
ids.retain(|id| !super::graph::is_design_art(d, *id));
|
||||
let ids = drop_design_art(d, ids);
|
||||
if given > 0 && ids.is_empty() {
|
||||
return Err(bad(cmd, DESIGN_ART));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// `ids` without the art of graph designs drawn in graph series, for the paint commands, which leave it out without an
|
||||
/// error.
|
||||
pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
ids.retain(|id| !super::graph::is_design_art(d, *id));
|
||||
ids
|
||||
}
|
||||
|
||||
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
|
||||
/// [`super::graph::is_design_art`] accepts.
|
||||
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in roots {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |m| {
|
||||
if m.extras().series_index.is_some() {
|
||||
out.extend(m.children().into_iter().flatten().map(|c| c.id).filter(|c| super::graph::is_design_art(d, *c)));
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
@@ -476,15 +559,15 @@ pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
|
||||
|
||||
/// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the
|
||||
/// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = edit_targets(s, p)?;
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = edit_targets(s, p, cmd)?;
|
||||
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
|
||||
}
|
||||
|
||||
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
|
||||
/// which can hold effects and a graphic style link of its own.
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let own = edit_targets(s, p)?;
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let own = edit_targets(s, p, cmd)?;
|
||||
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
|
||||
let groups = stood_for(&own, &ids);
|
||||
ids.extend(groups);
|
||||
@@ -513,7 +596,7 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool {
|
||||
|
||||
/// [`whole_targets`] of `cmd`, which needs at least one.
|
||||
fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = whole_targets(s, p)?;
|
||||
let ids = whole_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
@@ -522,7 +605,7 @@ fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId
|
||||
|
||||
/// [`row_targets`] of `cmd`, which needs at least one.
|
||||
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = row_targets(s, p)?;
|
||||
let ids = row_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
@@ -536,16 +619,23 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not
|
||||
/// an edit, and when `f` leaves every target as it was, the document and its undo history stay as
|
||||
/// they are.
|
||||
///
|
||||
/// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which
|
||||
/// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to
|
||||
/// it, a target without one is left as it is, and no target with one is an error. Returns the
|
||||
/// targets `f` was aimed at, in the order of `ids`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn edit_items(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| {
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
// The rows `f` edited are kept by `edit_items_then`.
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false);
|
||||
@@ -562,17 +652,29 @@ pub(crate) fn edit_items_then(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let art = of.and_then(|of| s.doc().ok()?.doc.node(of).map(|n| n.appearance.clone()));
|
||||
let per = match (item, art) {
|
||||
// Checked even when the art is the only object given, which leaves `ids` empty.
|
||||
(ItemTarget::Item { index, explicit: true, aligned: true }, Some(art)) => {
|
||||
item.resolve(&art, fill, cmd)?;
|
||||
let per = item.per_target_of(s, of, ids);
|
||||
if per.iter().all(Option::is_none) {
|
||||
return Err(bad(cmd, format!("no appearance item {index}")));
|
||||
}
|
||||
per
|
||||
}
|
||||
_ if ids.is_empty() => return Ok(Vec::new()),
|
||||
_ => item.per_target(s, ids),
|
||||
};
|
||||
let aimed: Vec<NodeId> = ids.iter().zip(&per).filter(|(_, item)| item.is_some()).map(|(id, _)| *id).collect();
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = item.per_target(s, ids);
|
||||
super::overprint::edit_counted(s, label, |d| {
|
||||
let mut edited = Vec::new();
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
@@ -591,7 +693,13 @@ pub(crate) fn edit_items_then(
|
||||
let labels = super::graph::capture_label_rows(d, &rows);
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
|
||||
})?;
|
||||
Ok(())
|
||||
Ok(aimed)
|
||||
}
|
||||
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// How many of `ids` differ in `d` from `before`.
|
||||
@@ -600,17 +708,23 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_
|
||||
}
|
||||
|
||||
/// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or
|
||||
/// null is an error of command `cmd`.
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`] and [`reference_of`]), else `default`. A `stroke` other than
|
||||
/// true, false or null is an error of command `cmd`.
|
||||
pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result<bool> {
|
||||
check_switches(p, &["stroke"], cmd)?;
|
||||
if let Some(b) = p.get("stroke").and_then(Value::as_bool) {
|
||||
return Ok(b);
|
||||
}
|
||||
let ItemTarget::Item { index, .. } = item else { return Ok(default) };
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
let holder = match reference_of(s, p, item, cmd)? {
|
||||
Some(of) => Some(of),
|
||||
None => {
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
ids.get(item.anchor(s, &ids)).copied()
|
||||
}
|
||||
};
|
||||
Ok(holder.and_then(|id| d.node(id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`].
|
||||
@@ -1032,7 +1146,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
|
||||
check_switches(p, &["visible"], "appearance.setItem")?;
|
||||
let paint = paint_from(s, p)?;
|
||||
let ids = row_targets(s, p)?;
|
||||
let ids = row_targets(s, p, "appearance.setItem")?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.setItem", "select objects or give ids"));
|
||||
}
|
||||
@@ -1040,7 +1154,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When every object comes out as it was (for example, when none has item `index`), the document
|
||||
// and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &[idx], aligned(p, "appearance.setItem")?);
|
||||
let of = design_reference(s, p, "appearance.setItem")?;
|
||||
let per = rows_per_target(&before, of, &ids, &[idx], aligned(p, "appearance.setItem")?);
|
||||
super::overprint::edit_counted(s, "Appearance", |d| {
|
||||
let mut edited = Vec::new();
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
@@ -1127,7 +1242,8 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When no object has an item at any of the indices, the document and its undo history stay as
|
||||
// they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p, "appearance.removeItem")?);
|
||||
let of = design_reference(s, p, "appearance.removeItem")?;
|
||||
let per = rows_per_target(&before, of, &ids, &idx, aligned(p, "appearance.removeItem")?);
|
||||
super::overprint::edit_counted(s, "Remove Item", |d| {
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
@@ -1168,12 +1284,19 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut first_at = None;
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
let mut active_at = None;
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object.
|
||||
if aligned(p, C)? && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art,
|
||||
// which is left out, go to `to` in an object whose stack is the same as the art's.
|
||||
let of = design_reference(s, p, C)?;
|
||||
if aligned(p, C)?
|
||||
&& to.is_some()
|
||||
&& (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids))))
|
||||
{
|
||||
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p, C)?);
|
||||
// With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist.
|
||||
let per =
|
||||
if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) };
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
@@ -1280,15 +1403,19 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let aligned = aligned(p, C)?;
|
||||
if p.get("from").and_then(Value::as_str) == Some("contents") {
|
||||
// A graph series group's own Contents row, not its paths, which have none.
|
||||
let ids = edit_targets(s, p)?;
|
||||
let ids = edit_targets(s, p, C)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select objects or give ids"));
|
||||
}
|
||||
// The Contents row's place counts the rows below it, which isn't one place in several different stacks either.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
}
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
}
|
||||
if p.get("indices").is_some() {
|
||||
|
||||
@@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
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 },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -397,6 +398,59 @@ fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brus
|
||||
Brush { name: name.into(), kind }
|
||||
}
|
||||
|
||||
/// Tech Circuit: original conductor geometry, drawn as filled paths so widths and chamfers
|
||||
/// survive brush warping. Pattern tiles meet at x = 0 and 24 with identical lead cross-sections.
|
||||
fn tech_circuit() -> BrushLibrary {
|
||||
let pad = |x: f64| {
|
||||
black(polygon(&[
|
||||
(x - 4.0, -2.0),
|
||||
(x - 2.0, -4.0),
|
||||
(x + 2.0, -4.0),
|
||||
(x + 4.0, -2.0),
|
||||
(x + 4.0, 2.0),
|
||||
(x + 2.0, 4.0),
|
||||
(x - 2.0, 4.0),
|
||||
(x - 4.0, 2.0),
|
||||
]))
|
||||
};
|
||||
// 45-degree jogs lift the conductor to a parallel run and bring it back.
|
||||
let trace = group(vec![
|
||||
black(polygon(&[
|
||||
(4.0, -1.0),
|
||||
(23.0, -1.0),
|
||||
(33.0, -11.0),
|
||||
(61.0, -11.0),
|
||||
(71.0, -1.0),
|
||||
(96.0, -1.0),
|
||||
(96.0, 1.0),
|
||||
(70.0, 1.0),
|
||||
(60.0, -9.0),
|
||||
(34.0, -9.0),
|
||||
(24.0, 1.0),
|
||||
(4.0, 1.0),
|
||||
])),
|
||||
pad(4.0),
|
||||
pad(96.0),
|
||||
]);
|
||||
let bus = group([-4.0, 0.0, 4.0].into_iter().map(|y| black(shapes::rectangle(Rect::new(0.0, y - 0.75, 24.0, y + 0.75)))).collect());
|
||||
let terminals = group(vec![
|
||||
// Overlap the ring's rim without filling the test point's hole.
|
||||
black(shapes::rectangle(Rect::new(0.0, -0.6, 15.5, 0.6))),
|
||||
black(shapes::rectangle(Rect::new(18.5, -0.6, 24.0, 0.6))),
|
||||
pad(6.0),
|
||||
ring(Point::new(17.0, 0.0), 3.0, 1.4),
|
||||
]);
|
||||
built(
|
||||
"Tech Circuit",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art("Circuit Trace", trace, Colorization::Tints),
|
||||
border("Bus Lines", bus, None, PatternFit::Stretch),
|
||||
border("Terminal Nodes", terminals, None, PatternFit::Stretch),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// An invisible rectangle that fixes a tile's width.
|
||||
fn spacer(r: Rect) -> Node {
|
||||
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
|
||||
|
||||
@@ -19,8 +19,8 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::{remove_each, separate};
|
||||
use super::swatch::{anchor, names_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
str_param, switch_or,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, named_ids, number_or, ok, str_param,
|
||||
switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paintbrush",
|
||||
[],
|
||||
None,
|
||||
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
|
||||
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, a `style` other than \"pencil\" or \"brush\", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled \"pencil\" path while the stroke is None) and an unknown key are errors and nothing is drawn; the path and its brush are one undo step → {id}",
|
||||
has_doc,
|
||||
brush_freehand
|
||||
),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::{
|
||||
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
|
||||
anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown,
|
||||
str_param,
|
||||
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
|
||||
};
|
||||
|
||||
// ---------- brushes ----------
|
||||
@@ -729,9 +728,10 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&out) }))
|
||||
}
|
||||
|
||||
/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws
|
||||
/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style`
|
||||
/// other than "pencil" or "brush", is an error before anything is drawn.
|
||||
/// Paints a `path.freehand` stroke with the brush `brush` names, in one undo step with the path.
|
||||
/// A `brush` left out or null draws the plain path; a `brush` that is not a string or names no
|
||||
/// brush in the document, a `style` other than "pencil" or "brush", and a `brush` for a path with
|
||||
/// no stroke are errors before anything is drawn.
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.freehand";
|
||||
let name = match crate::cmd::text_param(p, "brush", C)? {
|
||||
@@ -745,13 +745,6 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))),
|
||||
}
|
||||
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
|
||||
let r = crate::cmd::run_checked(s, spec, p)?;
|
||||
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
st.brush = Some(name.clone());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(r)
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node, NodeId, NodeKind, Selection, TraceView};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Live Paint"],
|
||||
Some("Cmd+Alt+X"),
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
|
||||
has_selection_or_ids,
|
||||
lp_make
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces: each face reached has its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the place of its topmost fill (none leaves one fill of none), and its strokes and its own opacity stay as they are; when every face it reaches already has only that one fill, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
@@ -144,7 +144,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, automatic: flat art with its own colours, else fullTone, 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, method: \"abutting\"|\"overlapping\", 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, automatic: flat art with its own colours, else fullTone, 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, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; 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)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -414,22 +414,274 @@ fn source_nodes(n: &Node) -> Vec<Arc<Node>> {
|
||||
if is_live_paint(n) { b::sources(n).and_then(|g| g.children().cloned()).unwrap_or_default() } else { vec![Arc::new(n.clone())] }
|
||||
}
|
||||
|
||||
/// Does appearance row `i` draw: it is shown, has paint and an opacity above 0, and a stroke also
|
||||
/// has a weight above 0?
|
||||
fn row_draws(i: &AppearanceItem) -> bool {
|
||||
match i {
|
||||
AppearanceItem::Fill(f) => f.visible && !f.paint.is_none() && f.opacity > 0.0,
|
||||
AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.opacity > 0.0 && s.width > 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a source path gives the faces and edges made from it.
|
||||
struct SourceStyle {
|
||||
/// The fill rows that draw, in paint order (none when the path's opacity is 0).
|
||||
fills: Vec<AppearanceItem>,
|
||||
/// The stroke rows that draw, in paint order (none when the path's opacity is 0).
|
||||
strokes: Vec<AppearanceItem>,
|
||||
/// The top stroke's weight, for an edge given no stroke that draws.
|
||||
width: f64,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
}
|
||||
|
||||
impl SourceStyle {
|
||||
/// The style of source path `n`: its rows keep their order and settings, gradients fitted to
|
||||
/// its bounds keep that fit, and the strokes' pen pressure, tilt, bearing and rotation stay
|
||||
/// with the path.
|
||||
fn of(n: &Node) -> Self {
|
||||
let mut a = (*n.appearance).clone().without_pressure();
|
||||
if a.has_unplaced_gradient()
|
||||
&& let Some(bounds) = n.geometric_bounds()
|
||||
{
|
||||
a.pin_gradients(bounds);
|
||||
}
|
||||
let width = a.stroke().map_or(1.0, |s| s.width);
|
||||
let (mut fills, mut strokes) = (vec![], vec![]);
|
||||
if n.opacity > 0.0 {
|
||||
for i in a.items.into_iter().filter(row_draws) {
|
||||
if i.is_fill() { fills.push(i) } else { strokes.push(i) }
|
||||
}
|
||||
}
|
||||
Self { fills, strokes, width, opacity: n.opacity, blend: n.blend }
|
||||
}
|
||||
|
||||
/// Give part `n` the rows `rows` of this source with its opacity and blending mode; with no
|
||||
/// rows, `n` keeps the unpainted row it has.
|
||||
fn paint(&self, n: &mut Node, rows: &[AppearanceItem]) {
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
n.appearance = Appearance { items: rows.to_vec(), ..Default::default() }.into();
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
}
|
||||
|
||||
/// How far, in points, a place on an edge may be from its source path and still be on it.
|
||||
const ON_SOURCE: f64 = 0.05;
|
||||
|
||||
/// Does stroke row `i` have settings that depend on where along its path a piece of it lies or
|
||||
/// which way it runs: dashes, arrowheads, a width profile, a brush, or a gradient along or across
|
||||
/// the stroke?
|
||||
fn depends_on_place(i: &AppearanceItem) -> bool {
|
||||
matches!(i, AppearanceItem::Stroke(s) if s.dash.is_some() || s.start_arrow.is_some() || s.end_arrow.is_some() || s.profile.is_some() || s.brush.is_some() || s.gradient_mode != vectorcraft_doc::StrokeGradientMode::Within)
|
||||
}
|
||||
|
||||
/// One subpath's segments with the length along it where each starts, then its whole length, and
|
||||
/// a grid of square cells listing the segments whose bounds, grown by [`ON_SOURCE`], reach into
|
||||
/// each cell, so finding the segments near a point does not look at every segment.
|
||||
struct Track {
|
||||
segs: Vec<kurbo::PathSeg>,
|
||||
at: Vec<f64>,
|
||||
closed: bool,
|
||||
cell: f64,
|
||||
grid: HashMap<(i64, i64), Vec<usize>>,
|
||||
/// Segments that reach into more than [`Track::MAX_CELLS`] cells, or that come after the grid
|
||||
/// holds [`Track::CELLS_PER_SEGMENT`] entries per segment, looked at for every point.
|
||||
wide: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
const ACCURACY: f64 = 1e-4;
|
||||
const MAX_CELLS: i64 = 4096;
|
||||
const CELLS_PER_SEGMENT: usize = 16;
|
||||
|
||||
fn new(sp: &SubPath) -> Self {
|
||||
use kurbo::{ParamCurveArclen, Shape as _};
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let segs: Vec<kurbo::PathSeg> = bp.segments().collect();
|
||||
let mut at = Vec::with_capacity(segs.len() + 1);
|
||||
let mut len = 0.0;
|
||||
for s in &segs {
|
||||
at.push(len);
|
||||
len += s.arclen(Self::ACCURACY);
|
||||
}
|
||||
at.push(len);
|
||||
let boxes: Vec<kurbo::Rect> = segs.iter().map(|s| s.bounding_box().inflate(ON_SOURCE, ON_SOURCE)).collect();
|
||||
// Cells about as wide as an average segment's bounds.
|
||||
let mean = boxes.iter().map(|b| b.width().max(b.height())).sum::<f64>() / boxes.len().max(1) as f64;
|
||||
let cell = if mean.is_finite() { mean.max(4.0 * ON_SOURCE) } else { 4.0 * ON_SOURCE };
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
let mut wide = vec![];
|
||||
// The grid holds at most this many entries in all.
|
||||
let mut budget = boxes.len().saturating_mul(Self::CELLS_PER_SEGMENT);
|
||||
for (k, b) in boxes.iter().enumerate() {
|
||||
let (x0, y0) = Self::cell_of(Point::new(b.x0, b.y0), cell);
|
||||
let (x1, y1) = Self::cell_of(Point::new(b.x1, b.y1), cell);
|
||||
let cells = x1.saturating_sub(x0).saturating_add(1).saturating_mul(y1.saturating_sub(y0).saturating_add(1));
|
||||
let Some(cells) = usize::try_from(cells).ok().filter(|&c| cells <= Self::MAX_CELLS && c <= budget) else {
|
||||
wide.push(k);
|
||||
continue;
|
||||
};
|
||||
budget -= cells;
|
||||
for x in x0..=x1 {
|
||||
for y in y0..=y1 {
|
||||
grid.entry((x, y)).or_default().push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { segs, at, closed: sp.closed, cell, grid, wide }
|
||||
}
|
||||
|
||||
fn cell_of(p: Point, cell: f64) -> (i64, i64) {
|
||||
((p.x / cell).floor() as i64, (p.y / cell).floor() as i64)
|
||||
}
|
||||
|
||||
fn len(&self) -> f64 {
|
||||
self.at.last().copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// The lengths along the subpath to each of its segments' places nearest `p` that are within
|
||||
/// [`ON_SOURCE`] of it (more than one where the subpath passes `p` again).
|
||||
fn places(&self, p: Point) -> Vec<f64> {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
|
||||
let near = self.grid.get(&Self::cell_of(p, self.cell)).map(Vec::as_slice).unwrap_or_default();
|
||||
let mut out = vec![];
|
||||
for &k in near.iter().chain(&self.wide) {
|
||||
let Some(s) = self.segs.get(k) else { continue };
|
||||
let n = s.nearest(p, 1e-9);
|
||||
if n.distance_sq <= ON_SOURCE * ON_SOURCE {
|
||||
out.push(self.at.get(k).copied().unwrap_or(0.0) + s.subsegment(0.0..n.t).arclen(Self::ACCURACY));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The signed length from `a` to `b` along the subpath (the shorter way round a closed one).
|
||||
fn step(&self, a: f64, b: f64) -> f64 {
|
||||
let (d, len) = (b - a, self.len());
|
||||
if self.closed && len > 0.0 { d - len * (d / len).round() } else { d }
|
||||
}
|
||||
|
||||
/// Of `places`, the one nearest along the subpath to `target`.
|
||||
fn nearest(&self, places: &[f64], target: f64) -> Option<f64> {
|
||||
places.iter().copied().min_by(|x, y| self.step(*x, target).abs().total_cmp(&self.step(*y, target).abs()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where edge `edge` runs along its source path, whose subpaths' tracks are `tracks`: the length
|
||||
/// along the source subpath to the edge's start, whether the edge starts at that subpath's start and
|
||||
/// ends at its end (an open subpath), and whether it runs the whole subpath. The middle of the
|
||||
/// edge's first segment places it, and its ends are taken where they lie that far along the source,
|
||||
/// so a path that passes a point twice is told apart. An edge that runs against the direction of its
|
||||
/// source is reversed first, and a closed edge as long as its closed source is started at the anchor
|
||||
/// where its source starts (one with no anchor there, or a shorter loop cut from a source that
|
||||
/// crosses itself, does not count as running the whole subpath). `None` when the edge is
|
||||
/// not a single piece found on the source.
|
||||
fn edge_run(tracks: &[Track], edge: &mut PathData) -> Option<(f64, bool, bool, bool)> {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen};
|
||||
let [sp] = edge.subpaths.as_slice() else { return None };
|
||||
if sp.segment_count() == 0 {
|
||||
return None;
|
||||
}
|
||||
let (a, z) = (sp.anchors.first()?.p, if sp.closed { sp.anchors.first()?.p } else { sp.anchors.last()?.p });
|
||||
let first = sp.segment(0);
|
||||
let mid = first.eval(0.5);
|
||||
let half = first.subsegment(0.0..0.5).arclen(Track::ACCURACY);
|
||||
let length = sp.anchor_arc_positions().last().copied().unwrap_or(0.0);
|
||||
let edge_closed = sp.closed;
|
||||
// (how far off the fit is, track, start, end, runs forward) for the subpath that fits best.
|
||||
let mut found: Option<(f64, &Track, f64, f64, bool)> = None;
|
||||
for track in tracks {
|
||||
// The start lies half the first segment before its middle along the source, or after it
|
||||
// when the edge runs the other way: take the place and way that fit best.
|
||||
let starts_at = track.places(a);
|
||||
let mut best: Option<(f64, f64, bool)> = None;
|
||||
for pm in track.places(mid) {
|
||||
for forward in [true, false] {
|
||||
let Some(pa) = track.nearest(&starts_at, if forward { pm - half } else { pm + half }) else { continue };
|
||||
let miss = (if forward { track.step(pa, pm) } else { track.step(pm, pa) } - half).abs();
|
||||
if best.is_none_or(|(m, _, _)| miss < m) {
|
||||
best = Some((miss, pa, forward));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((miss, pa, forward)) = best else { continue };
|
||||
let target = if forward { pa + length } else { pa - length };
|
||||
let Some(pz) = track.nearest(&track.places(z), target) else { continue };
|
||||
let miss = miss + track.step(pz, target).abs();
|
||||
if found.is_none_or(|(m, ..)| miss < m) {
|
||||
found = Some((miss, track, pa, pz, forward));
|
||||
}
|
||||
}
|
||||
let (_, track, pa, pz, forward) = found?;
|
||||
let (from, to) = if forward { (pa, pz) } else { (pz, pa) };
|
||||
if !forward {
|
||||
edge.reverse();
|
||||
}
|
||||
let open = !track.closed;
|
||||
let starts = open && from <= ON_SOURCE;
|
||||
let ends = open && to >= track.len() - ON_SOURCE;
|
||||
if open {
|
||||
return Some((from, starts, ends, starts && ends));
|
||||
}
|
||||
// A closed edge runs the whole closed subpath, from the anchor the planar map starts it at.
|
||||
// Start it at the anchor where the source starts, so settings that follow the path begin there.
|
||||
let start = track.segs.first().map(|s| s.start())?;
|
||||
let moved = edge_closed
|
||||
&& (length - track.len()).abs() <= ON_SOURCE.max(track.len() * 1e-4)
|
||||
&& edge.subpaths.first_mut().is_some_and(|sp| match sp.anchors.iter().position(|a| a.p.distance(start) <= ON_SOURCE) {
|
||||
Some(k) => {
|
||||
sp.anchors.rotate_left(k);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
});
|
||||
Some((if moved { 0.0 } else { from }, false, false, moved))
|
||||
}
|
||||
|
||||
/// Fit stroke row `row` of a source path to an edge cut from it, which runs as [`edge_run`] says
|
||||
/// (`None`: not known): its dashes go on from where the edge starts along the source, with the
|
||||
/// lengths set and without the fit of dashes aligned to corners and path ends, its arrowheads stay only at the source's own ends, and its width profile and brush, which spread
|
||||
/// over the whole path, stay only on an edge that runs the whole path.
|
||||
fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
|
||||
let AppearanceItem::Stroke(s) = row else { return };
|
||||
let (from, starts, ends, whole) = run.unwrap_or((0.0, false, false, false));
|
||||
if !whole {
|
||||
if let Some(d) = &mut s.dash
|
||||
&& run.is_some()
|
||||
{
|
||||
d.offset += from;
|
||||
d.align_corners = false;
|
||||
}
|
||||
s.profile = None;
|
||||
s.brush = None;
|
||||
}
|
||||
if !starts {
|
||||
s.start_arrow = None;
|
||||
}
|
||||
if !ends {
|
||||
s.end_arrow = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The planar map's inputs from `sources` (paths and compound paths, back → front), with the
|
||||
/// fill, stroke and stroke width of each.
|
||||
fn source_shapes(sources: &[Arc<Node>]) -> (Vec<po::Shape>, Vec<(Paint, Paint, f64)>) {
|
||||
/// style of each.
|
||||
fn source_shapes(sources: &[Arc<Node>]) -> (Vec<po::Shape>, Vec<SourceStyle>) {
|
||||
let mut lv = vec![];
|
||||
for n in sources {
|
||||
b::leaf_shapes(n, &mut lv);
|
||||
}
|
||||
let mut shapes = vec![];
|
||||
let mut styles: Vec<(Paint, Paint, f64)> = vec![];
|
||||
let mut styles: Vec<SourceStyle> = vec![];
|
||||
for l in lv {
|
||||
if let Some((path, rule)) = b::node_outline(l)
|
||||
&& !path.is_empty()
|
||||
{
|
||||
shapes.push(po::Shape::new(path, rule, styles.len() as u64));
|
||||
let a = &l.appearance;
|
||||
styles.push((a.fill_paint(), a.stroke_paint(), a.stroke().map(|s| s.width).unwrap_or(1.0)));
|
||||
styles.push(SourceStyle::of(l));
|
||||
}
|
||||
}
|
||||
(shapes, styles)
|
||||
@@ -462,17 +714,35 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
|
||||
let nfaces = regs.len();
|
||||
for r in regs {
|
||||
let id = d.alloc_id();
|
||||
let fill = r.top().and_then(|t| styles.get(t)).map_or(Paint::None, |s| s.0.clone());
|
||||
let mut n = Node::path(id, r.path, fill_only(fill));
|
||||
let mut n = Node::path(id, r.path, fill_only(Paint::None));
|
||||
n.name = Some(FACE_NAME.into());
|
||||
// The front-most covering source with a fill that draws gives the face its fill rows.
|
||||
if let Some(s) = r.sources.iter().rev().filter_map(|&t| styles.get(t)).find(|s| !s.fills.is_empty()) {
|
||||
s.paint(&mut n, &s.fills);
|
||||
}
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
let nedges = edges.len();
|
||||
// The tracks of the sources whose edges need them, measured once each.
|
||||
let mut tracks: HashMap<usize, Vec<Track>> = HashMap::new();
|
||||
for e in edges {
|
||||
let Some((_, stroke, w)) = styles.get(e.key as usize) else { continue };
|
||||
let key = e.key as usize;
|
||||
let Some(s) = styles.get(key) else { continue };
|
||||
let mut path = e.path;
|
||||
let mut rows = s.strokes.clone();
|
||||
if rows.iter().any(depends_on_place) {
|
||||
let source = tracks
|
||||
.entry(key)
|
||||
.or_insert_with(|| shapes.get(key).map(|src| src.path.subpaths.iter().map(Track::new).collect()).unwrap_or_default());
|
||||
let run = edge_run(source, &mut path);
|
||||
for r in &mut rows {
|
||||
fit_to_edge(r, run);
|
||||
}
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, e.path, stroke_only(stroke.clone(), *w));
|
||||
let mut n = Node::path(id, path, stroke_only(Paint::None, s.width));
|
||||
n.name = Some(EDGE_NAME.into());
|
||||
s.paint(&mut n, &rows);
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
Ok((children, nfaces, nedges))
|
||||
@@ -481,8 +751,9 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
|
||||
/// Give the faces and edges of `g`, a Live Paint group made again from the sources of `old`, the
|
||||
/// look of `old`'s face or edge where they lie: each face takes everything but the outline (its
|
||||
/// appearance, none included, its transparency and the rest) of the old face its inside point is
|
||||
/// in, and each edge that of the old edge its middle lies on. Faces and edges where `old` had none
|
||||
/// keep the paint of their sources.
|
||||
/// in, and each edge that of the old edge its middle lies on, with the old edge's stroke rows fitted
|
||||
/// to the part of it the new edge runs, as [`fit_to_edge`] fits a source's rows. Faces and edges
|
||||
/// where `old` had none keep the paint of their sources.
|
||||
fn repaint_from(g: &mut Node, old: &Node) {
|
||||
/// How far an edge's middle may be from the old edge it lies on.
|
||||
const ON_EDGE: f64 = 1e-3;
|
||||
@@ -505,7 +776,30 @@ fn repaint_from(g: &mut Node, old: &Node) {
|
||||
n.id = c.id;
|
||||
n.kind = c.kind.clone();
|
||||
n.bbox_angle = c.bbox_angle;
|
||||
// An edge cut from the old one takes the old edge's dashes, arrowheads, width profile
|
||||
// and brush as they fall on its part of the old edge.
|
||||
if c.name.as_deref() == Some(EDGE_NAME)
|
||||
&& let Some(old_path) = was.path_data()
|
||||
{
|
||||
fit_to_old_edge(&mut n, old_path);
|
||||
}
|
||||
*c = Arc::new(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fit the stroke rows of edge `n`, which it took from an old edge whose outline is `old`, to the
|
||||
/// part of the old edge that `n` runs, as [`fit_to_edge`] fits a source's rows to an edge cut from
|
||||
/// it; `n` is reversed when it runs against the old edge.
|
||||
fn fit_to_old_edge(n: &mut Node, old: &PathData) {
|
||||
if !n.appearance.items.iter().any(depends_on_place) {
|
||||
return;
|
||||
}
|
||||
let tracks: Vec<Track> = old.subpaths.iter().map(Track::new).collect();
|
||||
let run = n.path_data_mut().and_then(|path| edge_run(&tracks, path));
|
||||
let mut a = (*n.appearance).clone();
|
||||
for r in &mut a.items {
|
||||
fit_to_edge(r, run);
|
||||
}
|
||||
n.appearance = a.into();
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
|
||||
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
|
||||
source_nodes, source_shapes, switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -85,6 +85,9 @@ pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// How far, in points, the middle of an edge Merge makes may be from the old edge it lies on.
|
||||
const ON_OLD_EDGE: f64 = 1e-3;
|
||||
|
||||
/// What Merge carries from a face or edge to the part it makes again in its place, another path:
|
||||
/// the appearance, visibility, opacity and blending mode. Gradients fitted to the old outline keep
|
||||
/// that fit, and the strokes' pen pressure, tilt, bearing and rotation stay behind.
|
||||
@@ -125,18 +128,11 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
check_live_paint_takes(d, roots)?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw, and (point on edge,
|
||||
// paint) for every edge.
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the
|
||||
// old edges below.
|
||||
let keep_faces: Vec<(Point, Carried)> =
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let keep_edges: Vec<(Point, Carried)> = b::edges(&old)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let pd = e.path_data()?;
|
||||
let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?;
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), Carried::of(e)))
|
||||
})
|
||||
.collect();
|
||||
let old_parts = old.clone();
|
||||
let mut sources = source_nodes(&old);
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
@@ -162,12 +158,24 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
carried.onto(Arc::make_mut(f));
|
||||
}
|
||||
}
|
||||
for (pt, carried) in keep_edges {
|
||||
if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(e) = ch.iter_mut().find(|c| c.id == eid)
|
||||
{
|
||||
carried.onto(Arc::make_mut(e));
|
||||
// Each edge whose middle lies on an old edge, every piece of an edge an added path cuts
|
||||
// included, takes the old edge's paint, with its rows fitted to its part of the old edge.
|
||||
if let Some(ch) = g.children_mut() {
|
||||
for c in ch.iter_mut().filter(|c| c.name.as_deref() == Some(EDGE_NAME)) {
|
||||
let Some(mid) = c
|
||||
.path_data()
|
||||
.and_then(|pd| pd.subpaths.first())
|
||||
.filter(|sp| sp.segment_count() > 0)
|
||||
.map(|sp| kurbo::ParamCurve::eval(&sp.segment(0), 0.5))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(was) = edge_near(&old_parts, mid, ON_OLD_EDGE) else { continue };
|
||||
let e = Arc::make_mut(c);
|
||||
Carried::of(was).onto(e);
|
||||
if let Some(outline) = was.path_data() {
|
||||
fit_to_old_edge(e, outline);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut merged = Beside::replacing(d, roots);
|
||||
@@ -363,9 +371,52 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed }))
|
||||
}
|
||||
|
||||
/// Which parts a Live Paint Bucket click paints besides the one under the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum LpScope {
|
||||
/// The part under the pointer alone (a click).
|
||||
One,
|
||||
/// A face and the faces reached from it across edges that draw no stroke ([`b::flood_faces`]),
|
||||
/// or an edge and the edges joined to it end to end that draw with the same stroke paint
|
||||
/// ([`b::connected_edges`], [`b::lp_stroke_paint`]) (a double-click).
|
||||
Connected,
|
||||
/// Every face with the same fill, or every edge that draws with the same stroke paint, in the
|
||||
/// group (a triple-click).
|
||||
SamePaint,
|
||||
}
|
||||
|
||||
/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null.
|
||||
fn scope_param(p: &Value, c: &str) -> Result<LpScope> {
|
||||
match p.get("scope").filter(|v| !v.is_null()) {
|
||||
None => Ok(LpScope::One),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("one") => Ok(LpScope::One),
|
||||
Some("connected") => Ok(LpScope::Connected),
|
||||
Some("samePaint") => Ok(LpScope::SamePaint),
|
||||
_ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it,
|
||||
/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is
|
||||
/// an error naming `scopes`, the scopes it applies to.
|
||||
fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option<super::Paint>> {
|
||||
let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
if !allowed {
|
||||
return Err(bad(c, format!("match applies only with scope {scopes}")));
|
||||
}
|
||||
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
|
||||
}
|
||||
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
|
||||
if scope != LpScope::One && p.get("points").is_some() {
|
||||
return Err(bad(C, "scope applies to a click: leave out points"));
|
||||
}
|
||||
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
|
||||
let values = input
|
||||
.as_array()
|
||||
@@ -400,7 +451,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let group = object_param(p, "group", C)?;
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
|
||||
// and every visible face the drag crosses; → (the face at the point, the faces).
|
||||
// the faces its scope adds, and every visible face the drag crosses; → (the face at the point,
|
||||
// the faces).
|
||||
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet<NodeId>)> {
|
||||
let fid = d
|
||||
.node(gid)
|
||||
@@ -408,6 +460,18 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|f| f.id)
|
||||
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
|
||||
let mut targets = std::collections::BTreeSet::from([fid]);
|
||||
if scope != LpScope::One {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
if scope == LpScope::Connected {
|
||||
targets.extend(b::flood_faces(n, fid));
|
||||
} else {
|
||||
let like = match &like {
|
||||
Some(m) => m.clone(),
|
||||
None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(),
|
||||
};
|
||||
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
|
||||
}
|
||||
}
|
||||
if let Some(points) = points {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
// Use the existing region-crossing probes, so even a face narrower than the distance
|
||||
@@ -457,34 +521,37 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let (g, face) = match live {
|
||||
let (g, face, count) = match live {
|
||||
Some(gid) => {
|
||||
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
|
||||
// Faces that already have the paint stay as they are: when every face has it, nothing
|
||||
// changes and no undo step is recorded.
|
||||
let count = targets.len();
|
||||
// Faces that already have only the fill the bucket would leave ([`bucket_keeps`]) stay as
|
||||
// they are: when every face does, nothing changes and no undo step is recorded.
|
||||
let d = &s.doc()?.doc;
|
||||
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
|
||||
let unpainted: Vec<NodeId> =
|
||||
targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| !bucket_keeps(&f.appearance, true, &paint, 0.0))).collect();
|
||||
if unpainted.is_empty() {
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0 }));
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
|
||||
}
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in unpainted {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
|
||||
}
|
||||
Ok((gid, fid))
|
||||
Ok((gid, fid, count))
|
||||
})?
|
||||
}
|
||||
None => s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = make_live(d, sel, &roots)?.0;
|
||||
let (fid, targets) = targets_in(d, gid)?;
|
||||
let count = targets.len();
|
||||
for target in targets {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
|
||||
}
|
||||
Ok((gid, fid))
|
||||
Ok((gid, fid, count))
|
||||
})?,
|
||||
};
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "face": face.0 }))
|
||||
Ok(json!({ "group": g.0, "face": face.0, "count": count }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -498,31 +565,121 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "width out of range"));
|
||||
}
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let (eid, unchanged) = {
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
|
||||
let through: Vec<NodeId> = match p.get("through") {
|
||||
None => vec![],
|
||||
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
|
||||
Some(v) => {
|
||||
let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?;
|
||||
ids.iter()
|
||||
.map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids")))
|
||||
.collect::<Result<_>>()?
|
||||
}
|
||||
};
|
||||
let (eid, count, changed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
// An edge that already has the paint and the width (or has no stroke and gets none) stays as
|
||||
// it is, and no undo step is recorded.
|
||||
let unchanged = match e.appearance.stroke() {
|
||||
Some(st) => st.paint == paint && st.width == width,
|
||||
None => paint.is_none(),
|
||||
let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
let eid = start.id;
|
||||
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
|
||||
let targets = match scope {
|
||||
LpScope::One => vec![eid],
|
||||
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
|
||||
LpScope::SamePaint => std::iter::once(eid)
|
||||
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
|
||||
.collect(),
|
||||
};
|
||||
(e.id, unchanged)
|
||||
let count = targets.len();
|
||||
// An edge that already has only the stroke the bucket would leave ([`bucket_keeps`]) stays
|
||||
// as it is; when every edge does, nothing changes and no undo step is recorded.
|
||||
let changed: Vec<NodeId> =
|
||||
targets.into_iter().filter(|t| d.node(*t).is_none_or(|e| !bucket_keeps(&e.appearance, false, &paint, width))).collect();
|
||||
(eid, count, changed)
|
||||
};
|
||||
if unchanged {
|
||||
return Ok(json!({ "group": g.0, "edge": eid.0 }));
|
||||
if changed.is_empty() {
|
||||
return Ok(json!({ "group": g.0, "edge": eid.0, "count": count }));
|
||||
}
|
||||
let edge = s.edit("Live Paint Bucket", |d, _| {
|
||||
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
|
||||
e.appearance.set_stroke(paint.clone());
|
||||
if let Some(st) = e.appearance.stroke_mut() {
|
||||
st.width = width;
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in &changed {
|
||||
bucket_paint(&mut d.node_mut(*target).ok_or(EngineError::NoNode(*target))?.appearance, false, &paint, width);
|
||||
}
|
||||
Ok(eid)
|
||||
Ok(())
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "edge": edge.0 }))
|
||||
Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
|
||||
}
|
||||
|
||||
/// Whether the Live Paint Bucket leaves appearance `a` as it is when it paints its fills (`fill`)
|
||||
/// or strokes with `paint` (a stroke at `width`): it has exactly one row of that kind, shown, fully
|
||||
/// opaque, blending normally and with the paint (a stroke also with the width, unless the paint is
|
||||
/// none), or it has no row of that kind and the paint is none.
|
||||
fn bucket_keeps(a: &Appearance, fill: bool, paint: &super::Paint, width: f64) -> bool {
|
||||
let mut rows = a.items.iter().filter(|i| i.is_fill() == fill);
|
||||
match (rows.next(), rows.next()) {
|
||||
(None, _) => paint.is_none(),
|
||||
(Some(row), None) => {
|
||||
row.visible()
|
||||
&& row.opacity() == 1.0
|
||||
&& row.blend() == vectorcraft_color::BlendMode::Normal
|
||||
&& row.paint() == paint
|
||||
&& match row {
|
||||
AppearanceItem::Fill(_) => true,
|
||||
AppearanceItem::Stroke(st) => paint.is_none() || st.width == width,
|
||||
}
|
||||
}
|
||||
(Some(_), Some(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint the fills (`fill`) or strokes of appearance `a` with `paint` (a stroke at `width`), as the
|
||||
/// Live Paint Bucket does: every row of that kind is replaced by one row, shown, fully opaque and
|
||||
/// blending normally, in the place of the topmost row of that kind. The new row keeps the other
|
||||
/// settings (a stroke's dashes, caps and arrowheads, a row's effects) of the topmost row of that
|
||||
/// kind that is shown, or of the topmost one when every row is hidden. Rows of the other kind stay
|
||||
/// as they are. With no row of that kind, a fill is added below the strokes and a stroke above the
|
||||
/// fills.
|
||||
fn bucket_paint(a: &mut Appearance, fill: bool, paint: &super::Paint, width: f64) {
|
||||
let of_kind = |i: &AppearanceItem| i.is_fill() == fill;
|
||||
let Some(top) = a.items.iter().rposition(of_kind) else {
|
||||
if fill {
|
||||
a.set_fill(paint.clone());
|
||||
} else {
|
||||
a.items.push(AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width)));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let base = a.items.iter().rposition(|i| of_kind(i) && i.visible()).unwrap_or(top);
|
||||
let Some(mut row) = a.items.get(base).cloned() else { return };
|
||||
match &mut row {
|
||||
AppearanceItem::Fill(f) => {
|
||||
f.paint = paint.clone();
|
||||
f.opacity = 1.0;
|
||||
f.blend = vectorcraft_color::BlendMode::Normal;
|
||||
f.visible = true;
|
||||
}
|
||||
AppearanceItem::Stroke(st) => {
|
||||
st.paint = paint.clone();
|
||||
st.width = width;
|
||||
st.opacity = 1.0;
|
||||
st.blend = vectorcraft_color::BlendMode::Normal;
|
||||
st.visible = true;
|
||||
}
|
||||
}
|
||||
let mut row = Some(row);
|
||||
a.items = std::mem::take(&mut a.items)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, item)| {
|
||||
if i == top {
|
||||
row.take()
|
||||
} else if of_kind(&item) {
|
||||
None
|
||||
} else {
|
||||
Some(item)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
|
||||
|
||||
@@ -12,6 +12,7 @@ use super::{
|
||||
thread_local! {
|
||||
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static TRACES_ON_THIS_THREAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
@@ -22,6 +23,22 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths
|
||||
/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto
|
||||
/// Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
let stroke_only = |m: &Arc<Node>| {
|
||||
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& m.appearance.fill_paint() == Paint::None
|
||||
&& m.appearance.stroke_paint() != Paint::None
|
||||
};
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only)))
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
@@ -393,11 +410,15 @@ fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
/// (by the boxes of everything they paint, effects included, within one point); otherwise it
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. A group among `items` (Auto Grouping) is refused.
|
||||
/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is,
|
||||
/// under every other group. Any other group among `items` (Auto Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
use vectorcraft_color::tint_percent;
|
||||
// The seam fills come first, under every path: kept there, they move under nothing.
|
||||
let mut items = items;
|
||||
let seams: Vec<Arc<Node>> = if items.first().is_some_and(|n| is_seam_fills(n)) { items.drain(..1).collect() } else { vec![] };
|
||||
// Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a
|
||||
// gradient, or another paint (its label). The name is apart from it: a swatch may be named as
|
||||
// a color's `#rrggbb` or as "Gradients".
|
||||
@@ -517,25 +538,31 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(groups
|
||||
let groups: Vec<Arc<Node>> = groups
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let mut g = Node::group(d.alloc_id(), run.members);
|
||||
g.name = Some(run.name);
|
||||
Arc::new(g)
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
Ok(seams.into_iter().chain(groups).collect())
|
||||
}
|
||||
|
||||
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
|
||||
/// Trace object traced again), its image, the image's encoded bytes, and the settings it is traced
|
||||
/// with. The tracer makes the same paths of the same inputs, so a trace made away from the command
|
||||
/// ([`TraceRun`]) stands in for the command's own in the same document.
|
||||
/// What a trace depends on: the document it is made in and the content it was reverted to, the
|
||||
/// object traced (an image, or an Image Trace object traced again), its image, the image's encoded
|
||||
/// bytes, and the settings it is traced with. The tracer makes the same paths of the same inputs,
|
||||
/// so a trace made away from the command ([`TraceRun`]) stands in for the command's own in the same
|
||||
/// document until File › Revert replaces its content.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct TraceInputs {
|
||||
/// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one
|
||||
/// document never stands in for one in another, however alike their images and settings.
|
||||
doc: u64,
|
||||
/// The document's [`DocState::reverts`](crate::DocState::reverts) when the trace was prepared.
|
||||
/// A trace prepared before File › Revert never stands in for one after it, even when the
|
||||
/// restored image, pixels, object and settings are the same.
|
||||
reverts: u64,
|
||||
target: NodeId,
|
||||
image: Box<ImageObject>,
|
||||
/// The settings traced with, as JSON.
|
||||
@@ -604,21 +631,25 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
let st = s.doc()?;
|
||||
let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam
|
||||
/// fills ([`seams_within`]).
|
||||
pub struct Traced {
|
||||
inputs: TraceInputs,
|
||||
raster: (u32, u32),
|
||||
res: tr::TraceResult,
|
||||
seams: Vec<tr::TracedPath>,
|
||||
}
|
||||
|
||||
impl Traced {
|
||||
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the
|
||||
/// document it was made in, which applies it as one undo step instead of tracing again. Any
|
||||
/// other trace drops it, a trace in another document included.
|
||||
/// other trace drops it and traces again, a trace in another document included, and so does
|
||||
/// the command after File › Revert replaced the document's content.
|
||||
pub fn hand_in(self, s: &mut Session) {
|
||||
s.trace_hand_off = Some(self);
|
||||
}
|
||||
@@ -627,6 +658,8 @@ impl Traced {
|
||||
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
|
||||
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
#[cfg(test)]
|
||||
TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1));
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back).
|
||||
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if !steps(0, 0) {
|
||||
@@ -636,7 +669,18 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64
|
||||
tr::TraceError::Cancelled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res })
|
||||
let seams = seams_within(&res, params, MAX_TRACE_ANCHORS);
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams })
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam
|
||||
/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the
|
||||
/// paths, so a trace whose paths have more than half of `max` gets none.
|
||||
fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec<tr::TracedPath> {
|
||||
if res.anchor_count() > max / 2 {
|
||||
return vec![];
|
||||
}
|
||||
tr::seam_fills(&res.paths, params)
|
||||
}
|
||||
|
||||
/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`]
|
||||
@@ -691,17 +735,30 @@ impl TraceRun {
|
||||
}
|
||||
|
||||
/// Does it still apply: would the command trace the same object, image, pixels and settings
|
||||
/// now, in the document it was prepared in?
|
||||
/// now, in the document it was prepared in, with no File › Revert since?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
|
||||
}
|
||||
|
||||
/// Has File › Revert replaced the content of the document it was prepared in since then? False
|
||||
/// when that document is no longer open.
|
||||
pub fn reverted(&self, s: &Session) -> bool {
|
||||
let TraceInputs { doc, reverts, .. } = self.prepared.inputs;
|
||||
s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts)
|
||||
}
|
||||
|
||||
/// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it
|
||||
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
|
||||
/// document, so it can run on any thread.
|
||||
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
|
||||
}
|
||||
|
||||
/// How many images this thread has decoded and traced so far.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn traces_on_this_thread() -> usize {
|
||||
TRACES_ON_THIS_THREAD.with(std::cell::Cell::get)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
@@ -716,7 +773,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
s.note_journal("savedPreset", recorded);
|
||||
}
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
|
||||
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
};
|
||||
@@ -729,6 +786,13 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
// Seam fills: document units per raster pixel along the direction the image is stretched most,
|
||||
// so that a stroke covers its pixels across an edge at any angle.
|
||||
let seam_unit = {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
|
||||
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
};
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
// A library color fills with the swatch's displayed color (its model kept), unlinked.
|
||||
@@ -754,8 +818,38 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
hidden.visible = false;
|
||||
children.push(Arc::new(hidden));
|
||||
}
|
||||
let paint_of = |tp: &tr::TracedPath| {
|
||||
let solid =
|
||||
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
|
||||
};
|
||||
// Abutting: the seam fills, in a group of their own under every path.
|
||||
let seams: Vec<Arc<Node>> = seam_fills
|
||||
.iter()
|
||||
.filter_map(|tp| {
|
||||
let width = tp.stroke?;
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * seam_unit)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into();
|
||||
Some(Arc::new(n))
|
||||
})
|
||||
.collect();
|
||||
if !seams.is_empty() {
|
||||
let mut g = Node::group(d.alloc_id(), seams);
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let paint = paint_of(&tp);
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
// Shapes: a path the tracer found to be a shape is that live shape.
|
||||
@@ -764,10 +858,6 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
*path = shape.to_path();
|
||||
*live = Some(Box::new(shape));
|
||||
}
|
||||
let solid =
|
||||
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
let paint = tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf));
|
||||
n.appearance = match tp.stroke {
|
||||
// Traced lines: round corners, and ends round or square as the tracer found them.
|
||||
Some(width) => Appearance {
|
||||
@@ -1103,9 +1193,28 @@ mod color_group_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, trace_warnings};
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
#[test]
|
||||
fn seam_fills_count_against_the_anchor_limit() {
|
||||
// Two colors side by side, the edge between them anti-aliased: one seam fill along it.
|
||||
let img = tr::Raster::from_fn(24, 16, |x, _| {
|
||||
let share = (10.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let all = tr::seam_fills(&res.paths, ¶ms);
|
||||
assert!(!all.is_empty(), "{res:?}");
|
||||
let anchors = res.anchor_count();
|
||||
// Twice the paths' anchors leaves room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all);
|
||||
// One anchor short of that: none.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_warnings_name_matched_colors_that_produce_no_paths() {
|
||||
let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() };
|
||||
|
||||
@@ -32,7 +32,7 @@ use crate::DocState;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = vec![
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg),
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty). Under automation read roots it is refused while the SVG would name a linked image's file outside them (an image whose pixels the clipboard doesn't hold; a relative path is followed from the document the objects came from while it is open)", always, export_svg),
|
||||
cmd!(
|
||||
query "clipboard.importSvg",
|
||||
"Load SVG into Clipboard",
|
||||
@@ -435,14 +435,37 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty).
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty, and when the SVG would name
|
||||
/// a linked image's file the caller asking now may not be shown: [`Self::clipboard_svg_refused`]).
|
||||
pub fn clipboard_svg(&self) -> Option<String> {
|
||||
if self.clipboard_svg_refused() {
|
||||
return None;
|
||||
}
|
||||
self.clipboard.svg()
|
||||
}
|
||||
|
||||
/// Would the internal clipboard's SVG name a linked image's file outside the read roots in
|
||||
/// force? It names the file of an image whose pixels the clipboard doesn't hold. A relative
|
||||
/// path is followed from the document the objects came from while it is open; otherwise it
|
||||
/// counts as outside.
|
||||
pub fn clipboard_svg_refused(&self) -> bool {
|
||||
self.check_clipboard_svg("clipboard.exportSvg").is_err()
|
||||
}
|
||||
|
||||
/// [`Self::clipboard_svg_refused`] as `cmd`'s error, which names no file or folder.
|
||||
fn check_clipboard_svg(&self, cmd: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !self.clipboard.has_art() {
|
||||
return Ok(());
|
||||
}
|
||||
let from = self.docs.iter().find(|d| Some(d.uid) == self.clipboard.source_doc);
|
||||
let base = from.map_or_else(super::links::LinkBase::default, super::links::LinkBase::of);
|
||||
super::fileio::check_images_in(cmd, "svg", &self.clipboard.to_document(), base, &json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn export_svg(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "svg": s.clipboard_svg() }))
|
||||
s.check_clipboard_svg("clipboard.exportSvg")?;
|
||||
Ok(json!({ "svg": s.clipboard.svg() }))
|
||||
}
|
||||
|
||||
fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -595,6 +595,8 @@ struct Relink {
|
||||
styles: BTreeMap<u32, u32>,
|
||||
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
|
||||
colors: BTreeMap<String, Color>,
|
||||
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
|
||||
keep_styles: bool,
|
||||
}
|
||||
|
||||
impl Relink {
|
||||
@@ -674,7 +676,9 @@ impl Relink {
|
||||
/// Relink a node tree (the mirror of [`node_refs`]).
|
||||
fn node(&self, n: &mut Node) {
|
||||
self.appearance(&mut n.appearance);
|
||||
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
|
||||
if !self.keep_styles {
|
||||
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
self.node(Arc::make_mut(&mut m.art));
|
||||
}
|
||||
@@ -1109,6 +1113,30 @@ impl Clipboard {
|
||||
self.import_used(d, &self.used(), choices, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
/// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste
|
||||
/// without Formatting sets its pie legend labels' contrast from the wedge colors before it
|
||||
/// pastes). Nothing changes for the document the objects came from (`same_doc`).
|
||||
pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) {
|
||||
if same_doc {
|
||||
return;
|
||||
}
|
||||
let used = self.used();
|
||||
let colors: BTreeMap<String, Color> = self
|
||||
.conflicts(d, &used)
|
||||
.into_iter()
|
||||
.filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge)
|
||||
.filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c)))
|
||||
.collect();
|
||||
if colors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let relink = Relink { colors, keep_styles: true, ..Default::default() };
|
||||
for n in &mut self.nodes {
|
||||
relink.node(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
|
||||
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
|
||||
/// compared and relinked with their names here, and each loop of definitions that use each
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, ProofTarget};
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, Policy, ProofTarget};
|
||||
use vectorcraft_color::recolor::Neutral;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::ColorMode;
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
always,
|
||||
color_settings
|
||||
),
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assign Profile…",
|
||||
["Edit"],
|
||||
None,
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: no profile, Don't Color Manage This Document, so colors show through the working space; the working space's name: that profile stays assigned when the working space changes). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
has_doc,
|
||||
assign_profile
|
||||
),
|
||||
@@ -163,12 +163,26 @@ fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
switch_or(p, key, false, cmd).map(Some)
|
||||
}
|
||||
|
||||
/// The policy `p` gives for `key`, one of `allowed`, or `None` when `p` leaves it out.
|
||||
fn policy_param(p: &Value, key: &str, allowed: &[Policy], cmd: &str) -> Result<Option<Policy>> {
|
||||
let Some(v) = text_param(p, key, cmd)? else { return Ok(None) };
|
||||
match Policy::parse(v).filter(|x| allowed.contains(x)) {
|
||||
Some(x) => Ok(Some(x)),
|
||||
None => {
|
||||
let ids: Vec<&str> = allowed.iter().map(Policy::id).collect();
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", ids.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_json(st: &ColorSettings) -> Value {
|
||||
json!({
|
||||
"rgb": st.rgb,
|
||||
"cmyk": st.cmyk,
|
||||
"intent": st.intent.id(),
|
||||
"bpc": st.bpc,
|
||||
"rgbPolicy": st.rgb_policy.id(),
|
||||
"cmykPolicy": st.cmyk_policy.id(),
|
||||
"profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -205,6 +219,12 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.intent = i;
|
||||
}
|
||||
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
|
||||
if let Some(v) = policy_param(p, "rgbPolicy", &Policy::RGB, C)? {
|
||||
st.rgb_policy = v;
|
||||
}
|
||||
if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? {
|
||||
st.cmyk_policy = v;
|
||||
}
|
||||
if st != before {
|
||||
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
|
||||
// Saved for the next start when the app attached a settings file (#6335).
|
||||
@@ -530,7 +550,12 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
convert_colors(d, &mode_converter(mode, intent, grays))
|
||||
}
|
||||
|
||||
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
|
||||
/// the art changed, as [`set_color_mode`] counts them.
|
||||
fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) -> usize {
|
||||
for sw in d.swatches_iter_mut() {
|
||||
match &mut sw.paint {
|
||||
Paint::Solid { color, .. } => *color = conv(color),
|
||||
@@ -538,6 +563,11 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
for st in &mut g.gradient.stops {
|
||||
st.color = conv(&st.color);
|
||||
}
|
||||
if let Some(freeform) = &mut g.freeform {
|
||||
for point in &mut freeform.points {
|
||||
point.color = conv(&point.color);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -621,6 +651,102 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
in_art
|
||||
}
|
||||
|
||||
/// Apply the color management policies of Edit → Color Settings to `d`, a document being opened:
|
||||
/// each RGB or CMYK profile it is tagged with that is not the working space of its model is kept
|
||||
/// (Preserve Embedded Profiles), taken off with the color numbers kept (Off, Preserve Numbers), or
|
||||
/// taken off after the colors of that model were converted from it into the working space with the
|
||||
/// working intent (Convert to Working Space). A profile that is not available here is taken off
|
||||
/// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
let working = cms::working_settings();
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
let mut notes = Vec::new();
|
||||
// What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after
|
||||
// converting the colors from the profile it holds.
|
||||
let mut decide = |label: &str, tag: Option<String>, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option<Option<String>> {
|
||||
let tag = tag.filter(|t| t != working)?;
|
||||
let available = cms::profile(&tag).is_some_and(|p| p.kind == kind);
|
||||
match policy {
|
||||
Policy::PreserveEmbedded => None,
|
||||
Policy::Off | Policy::PreserveNumbers => {
|
||||
notes.push(format!(
|
||||
"the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}",
|
||||
policy.label()
|
||||
));
|
||||
Some(None)
|
||||
}
|
||||
Policy::Convert if available => {
|
||||
notes.push(format!(
|
||||
"the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”"
|
||||
));
|
||||
Some(Some(tag))
|
||||
}
|
||||
Policy::Convert => {
|
||||
notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted"));
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb);
|
||||
let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk);
|
||||
if rgb_do.is_none() && cmyk_do.is_none() {
|
||||
return (notes, false);
|
||||
}
|
||||
let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten());
|
||||
if from_rgb.is_some() || from_cmyk.is_some() {
|
||||
let source = cms::for_document(from_rgb.as_deref(), from_cmyk.as_deref());
|
||||
let dest = cms::working();
|
||||
let intent = working.intent;
|
||||
let (rgb_on, cmyk_on) = (from_rgb.is_some(), from_cmyk.is_some());
|
||||
let conv = |c: &Color| match c {
|
||||
Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent),
|
||||
Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent),
|
||||
_ => *c,
|
||||
};
|
||||
convert_colors(d, &conv);
|
||||
convert_setting_colors(d, &conv);
|
||||
}
|
||||
if rgb_do.is_some() {
|
||||
d.color_profiles.rgb = None;
|
||||
}
|
||||
if cmyk_do.is_some() {
|
||||
d.color_profiles.cmyk = None;
|
||||
}
|
||||
(notes, true)
|
||||
}
|
||||
|
||||
/// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each
|
||||
/// artboard's background, the transparency grid and simulated paper colors of Document Setup, and
|
||||
/// the fill and stroke of the character and paragraph styles.
|
||||
fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) {
|
||||
for c in d.artboards.iter_mut().filter_map(|a| a.color.as_mut()) {
|
||||
*c = conv(c);
|
||||
}
|
||||
for c in &mut d.setup.grid_colors {
|
||||
*c = conv(c);
|
||||
}
|
||||
// A tint of a global swatch is the converted swatch's color at its tint, which
|
||||
// [`convert_colors`] already gave it.
|
||||
let bases = global_bases(d);
|
||||
let mut f = |c: &Color, link: proof::Link| mode_color(c, link, &bases, conv);
|
||||
for styles in [&mut d.char_styles, &mut d.para_styles] {
|
||||
if !styles.iter().any(|s| s.attrs.contains_key("fill") || s.attrs.contains_key("stroke")) {
|
||||
continue;
|
||||
}
|
||||
for def in styles.iter_mut() {
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(value) = def.attrs.get_mut(key) else { continue };
|
||||
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { continue };
|
||||
map_paint_colors(&mut paint, &mut f);
|
||||
if let Ok(v) = serde_json::to_value(&paint) {
|
||||
*value = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
|
||||
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
proof::map_node_colors(n, f);
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]),
|
||||
//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a
|
||||
//! font of its own. Type names a composite font as its family, and the font menus list them first.
|
||||
//! The font database holds the active document's composite fonts ([`sync`]); a file exported here
|
||||
//! carries them to another document.
|
||||
//! font of its own, and the characters of each custom character set in the set's font. Type names
|
||||
//! a composite font as its family, and the font menus list them first. The font database holds the
|
||||
//! active document's composite fonts ([`sync`]); a file exported here carries them to another
|
||||
//! document.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -26,6 +29,10 @@ const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
/// The keys a part may give.
|
||||
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
|
||||
|
||||
/// The keys a custom character set may give: its name and characters, then its part's values
|
||||
/// (a set is never scaled at the center).
|
||||
const SET_KEYS: [&str; 8] = ["name", "characters", "font", "style", "size", "baseline", "hScale", "vScale"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -33,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composite Fonts",
|
||||
[],
|
||||
None,
|
||||
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}",
|
||||
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}, custom?: [{name, characters, font, style, size, baseline, hScale, vScale}]}]}",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -42,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composite Fonts…",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
|
||||
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}, custom?: [{name, characters?: string = \"\", font?, style?, size?, baseline?, hScale?, vScale?}]}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. custom lists custom character sets: each sets the characters it lists in its own font, style, size, baseline and scales (values left out are the kanji part's), ahead of their class; a character two sets list is set by the later one. A set's name is trimmed and unique in the font in any case; its characters are each listed once, at most 8192, none a control character or past U+FFFF; at most 64 sets. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -51,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Composite Fonts",
|
||||
[],
|
||||
None,
|
||||
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}",
|
||||
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads (a file over 4 MB is refused); without path the file's text comes back as data → {path, count} | {data, count}",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -121,8 +128,8 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// copy of the Kanji part, and keys or values a part can't take refused.
|
||||
fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts")));
|
||||
if let Some(k) = o.keys().find(|k| !["name", "parts", "custom"].contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("unknown key `{k}`; a font takes name, parts and custom")));
|
||||
}
|
||||
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?;
|
||||
let name = CompositeFont::clean_name(raw)
|
||||
@@ -140,7 +147,17 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key())))
|
||||
};
|
||||
let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?;
|
||||
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) };
|
||||
let custom = match o.get("custom") {
|
||||
None => Vec::new(),
|
||||
Some(Value::Array(sets)) => {
|
||||
if sets.len() > CUSTOM_SETS_MAX {
|
||||
return Err(bad(c, format!("`{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets")));
|
||||
}
|
||||
sets.iter().map(|s| parse_set(s, &name, &kanji, c)).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(c, format!("`{name}`: custom must be a list of character sets"))),
|
||||
};
|
||||
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji), custom };
|
||||
for class in CharClass::ALL.into_iter().skip(1) {
|
||||
if let Some(p) = part(class)? {
|
||||
*f.parts.get_mut(class) = p;
|
||||
@@ -150,6 +167,38 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Custom character set `v` of composite font `font` from command parameters or a file: its name
|
||||
/// trimmed, the part values it leaves out those of `kanji`, and keys or values it can't take
|
||||
/// refused. [`CompositeFont::check`] checks its characters and values.
|
||||
fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<CustomCharSet> {
|
||||
let o = v.as_object().ok_or_else(|| bad(c, format!("`{font}`: each character set must be {{name, characters, font…}}")))?;
|
||||
if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("`{font}`: unknown key `{k}` in a character set")));
|
||||
}
|
||||
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, format!("`{font}`: each character set needs a name")))?;
|
||||
let name = CompositeFont::clean_name(raw)
|
||||
.ok_or_else(|| bad(c, format!("`{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
|
||||
let characters = match o.get("characters") {
|
||||
None => String::new(),
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(_) => return Err(bad(c, format!("`{font}`: `{name}`: characters must be a string"))),
|
||||
};
|
||||
// Checked here as well as by `check`, so a huge list is refused before it is copied again.
|
||||
if characters.chars().nth(CUSTOM_CHARS_MAX).is_some() {
|
||||
return Err(bad(c, format!("`{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters")));
|
||||
}
|
||||
let mut part = serde_json::to_value(kanji).map_err(|e| bad(c, e.to_string()))?;
|
||||
if let Some(p) = part.as_object_mut() {
|
||||
for k in &SET_KEYS[2..] {
|
||||
if let Some(given) = o.get(*k) {
|
||||
p.insert(k.to_string(), given.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let part: CompositePart = serde_json::from_value(part).map_err(|e| bad(c, format!("`{font}`: `{name}`: {e}")))?;
|
||||
Ok(CustomCharSet { name, characters, part })
|
||||
}
|
||||
|
||||
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
|
||||
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
|
||||
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
@@ -167,10 +216,10 @@ fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
for f in fonts {
|
||||
for class in CharClass::ALL {
|
||||
let font = &f.parts.get(class).font;
|
||||
let classes = CharClass::ALL.into_iter().map(|class| (class.key(), &f.parts.get(class).font));
|
||||
for (part, font) in classes.chain(f.custom.iter().map(|s| (s.name.as_str(), &s.part.font))) {
|
||||
if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() {
|
||||
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key())));
|
||||
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, part)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +309,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut file = Map::new();
|
||||
file.insert("compositeFonts".into(), json!(fonts));
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
|
||||
}
|
||||
match path {
|
||||
Some(path) => {
|
||||
write_file(path, text.as_bytes())?;
|
||||
|
||||
@@ -856,3 +856,127 @@ fn composite_fonts_export_and_import() {
|
||||
assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `font(name)` with two custom character sets: "Marks" (x and A) in Inter at 150%, and "A only"
|
||||
/// (A) in Source Sans 3, which sets A since it comes later.
|
||||
fn font_with_sets(name: &str) -> Value {
|
||||
let mut v = font(name);
|
||||
v["custom"] = json!([
|
||||
{"name": " Marks ", "characters": "xA", "font": "Inter", "size": 150, "hScale": 90},
|
||||
{"name": "A only", "characters": "A"},
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
/// Custom character sets are set with the font as one undo step, take values they leave out from
|
||||
/// the Kanji part, set the characters they list ahead of their class (the later set winning), are
|
||||
/// saved with the document, and measure type again when they change.
|
||||
#[test]
|
||||
fn custom_character_sets_set_their_characters() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
|
||||
assert_eq!(r["fonts"][0]["custom"][0]["name"], "Marks");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let f = s.doc().unwrap().doc.composite_fonts[0].clone();
|
||||
assert_eq!(f.custom.len(), 2);
|
||||
assert_eq!((f.custom[0].part.font.as_str(), f.custom[0].part.size, f.custom[0].part.h_scale), ("Inter", 150.0, 90.0));
|
||||
assert_eq!((f.custom[1].part.font.as_str(), f.custom[1].part.size), ("Source Sans 3", 100.0));
|
||||
// The same sets again change nothing.
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap();
|
||||
assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
|
||||
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "xAB", "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Sets"})).unwrap();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let face = |family: &str| db.face(family, "Regular").unwrap().id();
|
||||
let lay = vectorcraft_text::layout(db, &text(&s, id));
|
||||
let fonts: Vec<u32> = lay.glyphs.iter().map(|g| g.font_id).collect();
|
||||
assert_eq!(fonts, [face("Inter"), face("Source Sans 3"), face("JetBrains Mono")]);
|
||||
// Taking x out of Marks sets it in its class's font again, measured in the same step.
|
||||
let wide = text(&s, id).cached_bounds.unwrap().width();
|
||||
let mut fewer = font_with_sets("CF Sets");
|
||||
fewer["custom"][0]["characters"] = json!("A");
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [fewer]})).unwrap();
|
||||
assert!(text(&s, id).cached_bounds.unwrap().width() < wide - 1.0);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Bad custom character sets are refused with an error and no undo step.
|
||||
#[test]
|
||||
fn bad_custom_character_sets_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets Base")]})).unwrap();
|
||||
let before = steps(&s);
|
||||
let with = |f: &dyn Fn(&mut Value)| {
|
||||
let mut v = font_with_sets("CF Sets Refused");
|
||||
f(&mut v);
|
||||
json!({"fonts": [v]})
|
||||
};
|
||||
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(8193).collect();
|
||||
let sets: Vec<Value> = (0..65).map(|i| json!({"name": format!("S{i}")})).collect();
|
||||
for bad in [
|
||||
with(&|v| v["custom"] = json!("Marks")),
|
||||
with(&|v| v["custom"] = Value::Null),
|
||||
with(&|v| v["custom"][0]["characters"] = Value::Null),
|
||||
with(&|v| v["custom"][0] = json!("Marks")),
|
||||
with(&|v| v["custom"][0]["name"] = json!(" ")),
|
||||
with(&|v| {
|
||||
v["custom"][0].as_object_mut().unwrap().remove("name");
|
||||
}),
|
||||
with(&|v| v["custom"][1]["name"] = json!("marks")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!(["※"])),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("※※")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("A\n")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("😀")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!(many.clone())),
|
||||
with(&|v| v["custom"] = json!(sets.clone())),
|
||||
with(&|v| v["custom"][0]["size"] = json!(5)),
|
||||
with(&|v| v["custom"][0]["size"] = json!("50")),
|
||||
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(true)),
|
||||
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(false)),
|
||||
with(&|v| v["custom"][0]["font"] = json!("")),
|
||||
with(&|v| v["custom"][0]["font"] = json!("CF Sets Base")),
|
||||
with(&|v| v["custom"][0]["width"] = json!(3)),
|
||||
] {
|
||||
let e = s.execute("type.compositeFonts.set", &bad);
|
||||
assert!(e.is_err(), "accepted {bad}");
|
||||
assert_eq!(names(&s), ["CF Sets Base"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
// A set without characters is kept: it sets nothing.
|
||||
let ok = with(&|v| v["custom"][0]["characters"] = json!(""));
|
||||
s.execute("type.compositeFonts.set", &ok).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.composite_fonts[0].custom[0].characters, "");
|
||||
}
|
||||
|
||||
/// Export writes the custom character sets and Import reads them back; a file whose set is bad is
|
||||
/// refused.
|
||||
#[test]
|
||||
fn custom_character_sets_export_and_import() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets IO")]})).unwrap();
|
||||
let data = s.execute("type.compositeFonts.export", &json!({})).unwrap();
|
||||
let mut t = session();
|
||||
t.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap();
|
||||
assert_eq!(*t.doc().unwrap().doc.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
|
||||
let text = data["data"].as_str().unwrap().replace("\"A only\"", "\"marks\"");
|
||||
let mut u = session();
|
||||
assert!(u.execute("type.compositeFonts.import", &json!({"data": text})).is_err());
|
||||
assert!(names(&u).is_empty());
|
||||
// Fonts whose file would be larger than Import reads are refused.
|
||||
let full: String = (0x4E00u32..).filter_map(char::from_u32).take(8192).collect();
|
||||
let sets: Vec<Value> = (0..64).map(|i| json!({"name": format!("S{i}"), "characters": full})).collect();
|
||||
let big: Vec<Value> = (0..3)
|
||||
.map(|i| {
|
||||
let mut f = font(&format!("CF Sets Big {i}"));
|
||||
f["custom"] = json!(sets);
|
||||
f
|
||||
})
|
||||
.collect();
|
||||
let e = s.execute("type.compositeFonts.export", &json!({"fonts": big})).unwrap_err();
|
||||
assert!(e.to_string().contains("4 MB"), "{e}");
|
||||
}
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
@@ -429,6 +429,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"direction",
|
||||
"pathLength",
|
||||
"seed",
|
||||
"ringSeed",
|
||||
];
|
||||
check_numbers(p, &numbers, "shape.flare")?;
|
||||
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
|
||||
@@ -450,14 +451,28 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
|
||||
}
|
||||
};
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare).
|
||||
let mut seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0x2545_f491_4f6c_dd1d) | 1;
|
||||
let mut rnd = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// The generator's state is odd (never 0).
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
@@ -495,6 +510,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
|
||||
@@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec<SubPath> {
|
||||
if !end_on {
|
||||
run.reverse();
|
||||
}
|
||||
let Some((last, body)) = run.anchors.split_last() else { return vec![] };
|
||||
let run = run.anchors.into_vec();
|
||||
let Some((last, body)) = run.split_last() else { return vec![] };
|
||||
let q = axis.project(last.p);
|
||||
let mut anchors = body.to_vec();
|
||||
anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in));
|
||||
|
||||
@@ -104,9 +104,14 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result<Plane> {
|
||||
Ok(plane)
|
||||
}
|
||||
|
||||
/// The objects a perspective command acts on: the outermost of `ids` (each once, in the order first
|
||||
/// given), else the selection's roots.
|
||||
pub(super) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match named_ids(p)? {
|
||||
Some(v) => Ok(outermost(&s.doc()?.doc, v)),
|
||||
Some(v) => {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
Ok(outermost(&s.doc()?.doc, v.into_iter().filter(|id| seen.insert(*id)).collect()))
|
||||
}
|
||||
None => selected_roots(s),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection,
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::panelcmds::artboard_at;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
@@ -201,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Guide",
|
||||
[],
|
||||
None,
|
||||
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
|
||||
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
|
||||
has_doc,
|
||||
guide_add
|
||||
),
|
||||
@@ -767,15 +768,8 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pos = f64_req(p, "pos", "guide.add")?;
|
||||
let vertical = switch_or(p, "vertical", false, "guide.add")?;
|
||||
let artboard = match p.get("artboard").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let boards = &s.doc()?.doc.artboards;
|
||||
let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
Some(ab.id)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id);
|
||||
let layer = match id_param(p, "layer") {
|
||||
Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l),
|
||||
Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")),
|
||||
|
||||
@@ -33,3 +33,4 @@ mod smooth;
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
pub(super) use freehand::freehand_brushed;
|
||||
Loaded 100 of 605 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user