diff --git a/ASSETS.md b/ASSETS.md
index 029a978153..ffa455079d 100644
--- a/ASSETS.md
+++ b/ASSETS.md
@@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-anchor-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-appearance.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arc.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-arc-three-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Three-Point Arc tool: an arc through its two ends and a third point |
| `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
diff --git a/ROADMAP.md b/ROADMAP.md
index c4a6edc8fb..ef05d5dc9a 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -128,6 +128,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 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-18: Built-in Paint brush library: Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, original art brushes generated in code that take the stroke color as tints. Thirteen built-in brush libraries; 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-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
@@ -162,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
+- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs
index 74f2095669..5dfe7386f6 100644
--- a/apps/vectorcraft-cli/src/main.rs
+++ b/apps/vectorcraft-cli/src/main.rs
@@ -246,6 +246,7 @@ fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_script_data(&mut h.session);
prefs_dir::attach_metadata_templates_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
+ prefs_dir::attach_proof_setups(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs
index 1778503201..aa62211500 100644
--- a/apps/vectorcraft/src/main.rs
+++ b/apps/vectorcraft/src/main.rs
@@ -554,6 +554,7 @@ fn main() -> std::process::ExitCode {
// File Info's metadata templates live in their own folder next to the preferences.
prefs_dir::attach_metadata_templates_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
+ prefs_dir::attach_proof_setups(&mut session);
prefs_dir::attach_script_data(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs
index d9defc5686..f863a6eba3 100644
--- a/apps/vectorcraft/src/prefs_dir.rs
+++ b/apps/vectorcraft/src/prefs_dir.rs
@@ -81,6 +81,14 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
}
}
+/// Have View › Proof Setup list the proof setups saved in the `Proof Setups` folder, which
+/// `view.proofSetup.save` makes when it saves a setup by name.
+pub fn attach_proof_setups(session: &mut vectorcraft_engine::Session) {
+ if let Some(dir) = store_dir("Proof Setups") {
+ session.attach_proof_setups(dir);
+ }
+}
+
/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people
/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first
/// needs them.
diff --git a/assets/icons/dc-arc-three-point.svg b/assets/icons/dc-arc-three-point.svg
new file mode 100644
index 0000000000..479a9a5930
--- /dev/null
+++ b/assets/icons/dc-arc-three-point.svg
@@ -0,0 +1 @@
+
diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs
index 3fc68180d0..700632313e 100644
--- a/crates/cad/src/scene.rs
+++ b/crates/cad/src/scene.rs
@@ -34,6 +34,7 @@ const WIDE_LINES: &str =
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole";
+const DISTORTED_IMAGES: &str = "images changed by Perspective Distort or Free Distort are written as the nearest parallelogram";
const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)";
/// The warning for an image left out because it can't be decoded: the note raster exports give
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
@@ -671,7 +672,18 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
- NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
+ NodeKind::Image(im) => match vectorcraft_doc::image_quad::nearest_affine(n) {
+ // DXF clips nothing, so a distorted image is written at the affine placement nearest
+ // its corners, with the warning once it is written.
+ Some(xf) => {
+ if self.image(&ImageObject { xf, ..self.doc.shown_image(n, im).into_owned() }) {
+ self.warn(DISTORTED_IMAGES);
+ }
+ }
+ None => {
+ self.image(&self.doc.shown_image(n, im));
+ }
+ },
NodeKind::SymbolInstance { symbol, xf } => {
let doc = self.doc;
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
@@ -1325,18 +1337,19 @@ impl<'a> Scene<'a> {
name
}
- /// A placed image, linked to its file (written once per image).
- fn image(&mut self, im: &ImageObject) {
+ /// A placed image, linked to its file (written once per image). False when no `IMAGE` entity is
+ /// written.
+ fn image(&mut self, im: &ImageObject) -> bool {
if !self.o.version.handles() {
self.warn(NO_IMAGES);
- return;
+ return false;
}
if !self.o.include_images {
self.note_setting(IMAGES_OFF);
- return;
+ return false;
}
- let Some(i) = self.image_def(im) else { return };
- let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
+ let Some(i) = self.image_def(im) else { return false };
+ let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return false };
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
let map = self.to_dxf * im.xf;
let lin = |v: kurbo::Vec2| (map * v.to_point()) - (map * Point::ZERO);
@@ -1349,7 +1362,7 @@ impl<'a> Scene<'a> {
let at = map * Point::new(0.0, h);
let handle = self.handle();
let reactor = self.handle();
- let Some(def) = self.images.get_mut(i) else { return };
+ let Some(def) = self.images.get_mut(i) else { return false };
def.reactors.push((reactor, handle));
let def = def.handle;
let layer = self.layer.clone();
@@ -1375,6 +1388,7 @@ impl<'a> Scene<'a> {
if self.o.version >= crate::DxfVersion::R2010 {
self.e.int(290, 0);
}
+ true
}
/// The image file for image `im`, encoded once in the chosen format (`None`: left out).
diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs
index 797223b688..35a1e8c45d 100644
--- a/crates/cad/src/tests.rs
+++ b/crates/cad/src/tests.rs
@@ -984,6 +984,37 @@ fn images_can_be_left_out_with_their_files() {
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
}
+/// DXF does not clip, so an image changed by Perspective Distort is written as one image at the
+/// placement nearest its corners, with a warning; an undistorted image gets no warning.
+#[test]
+fn a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning() {
+ let mut d = image_and_fill_doc(Paint::None);
+ let warned = |o: &DxfOutput| o.warnings.iter().any(|w| w.contains("Perspective Distort or Free Distort"));
+ assert!(!warned(&export(&d, &opts(&d)).unwrap()));
+ let id = d.layers[0].children().unwrap()[1].id;
+ let q = [(12.0, 20.0), (28.0, 20.0), (30.0, 30.0), (10.0, 30.0)].map(|(x, y)| Point::new(x, y));
+ d.node_mut(id).unwrap().set_image_corners(q).unwrap();
+ let out = export(&d, &opts(&d)).unwrap();
+ assert!(warned(&out), "{:?}", out.warnings);
+ assert_eq!(kinds(&out).iter().filter(|k| *k == "IMAGE").count(), 1, "{:?}", kinds(&out));
+ // Placed as an undistorted image with the nearest affine placement as its transform would be.
+ let near = vectorcraft_doc::image_quad::nearest_affine(d.node(id).unwrap()).unwrap();
+ let mut plain = d.clone();
+ let n = plain.node_mut(id).unwrap();
+ n.extras_mut().image_quad = None;
+ if let NodeKind::Image(im) = &mut n.kind {
+ im.xf = near;
+ }
+ let placement = |o: &DxfOutput| {
+ let e = entities(o).into_iter().find(|e| kind(e) == "IMAGE").expect("an IMAGE");
+ [10, 20, 11, 21, 12, 22].map(|c| all(&e, c))
+ };
+ assert_eq!(placement(&out), placement(&export(&plain, &opts(&plain)).unwrap()));
+ // With images left out, no IMAGE is written and the distortion warning does not appear.
+ let left_out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
+ assert!(!warned(&left_out), "{:?}", left_out.warnings);
+}
+
#[test]
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index fa8cd564f2..c3d74615ae 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -10,6 +10,7 @@ pub mod freeform;
pub mod gradient;
pub mod harmony;
pub mod libraries;
+pub mod oklab;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
@@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
[r + m, g + m, b + m]
}
+/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color
+/// conversion, as CSS Color 4 converts sRGB to HSL
+/// (). The hue is 0 while the saturation is
+/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in
+/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001
+/// below 1, or a saturation of 0.00001 or less reads as a gray.
+pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] {
+ const EPSILON: f32 = 1e-5;
+ let max = r.max(g).max(b);
+ let min = r.min(g).min(b);
+ let d = max - min;
+ let l = (max + min) / 2.0;
+ if d <= 0.0 {
+ return [0.0, 0.0, l];
+ }
+ let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) };
+ let mut h = rgb_to_hsb([r, g, b])[0];
+ if s < 0.0 {
+ h += 180.0;
+ s = -s;
+ }
+ if s <= EPSILON {
+ return [0.0, 0.0, l];
+ }
+ let h = h.rem_euclid(360.0);
+ [if h >= 360.0 { 0.0 } else { h }, s, l]
+}
+
+/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS
+/// Color 4 converts HSL to sRGB (): the inverse of
+/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120°
+/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's
+/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue.
+pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] {
+ let h = h.rem_euclid(360.0);
+ let a = s * l.min(1.0 - l);
+ let f = |n: f32| {
+ let k = (n + h / 30.0).rem_euclid(12.0);
+ l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
+ };
+ [f(0.0), f(8.0), f(4.0)]
+}
+
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
@@ -499,6 +543,59 @@ mod tests {
}
}
+ /// The HSL examples of CSS Color 4, section 7 (),
+ /// the first six rows, and two hues outside 0..360 that wrap into that range.
+ #[test]
+ fn hsl_follows_css_color_4() {
+ for (hsl, hex) in [
+ ([0.0, 1.0, 0.5], "#ff0000"),
+ ([120.0, 1.0, 0.5], "#00ff00"),
+ ([120.0, 1.0, 0.25], "#008000"),
+ ([120.0, 1.0, 0.75], "#80ff80"),
+ ([240.0, 1.0, 0.5], "#0000ff"),
+ ([60.0, 1.0, 0.5], "#ffff00"),
+ ([360.0, 1.0, 0.5], "#ff0000"),
+ ([-120.0, 1.0, 0.5], "#0000ff"),
+ ] {
+ let [r, g, b] = hsl_to_rgb(hsl);
+ assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}");
+ }
+ let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]);
+ assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}");
+ let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated());
+ assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}");
+ // A gray has no hue: the hue is 0 and the saturation 0, at any lightness.
+ for v in [0.0, 0.25, 0.5, 1.0] {
+ assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]);
+ }
+ // Black and white keep any hue and saturation they are given.
+ assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]);
+ assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]);
+ // A color past the gamut that gives a negative saturation turns its hue by 180°.
+ let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]);
+ assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}");
+ // A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°.
+ let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5]));
+ assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}");
+ }
+
+ /// The 216 web colors go to HSL and back to the same 8-bit color.
+ #[test]
+ fn hsl_roundtrip() {
+ let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff];
+ for r in steps {
+ for g in steps {
+ for b in steps {
+ let c = Color::rgb8(r, g, b);
+ let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated());
+ assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex());
+ let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8);
+ assert_eq!(back, [r, g, b], "{}", c.to_hex());
+ }
+ }
+ }
+ }
+
#[test]
fn cmyk_conversions() {
assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]);
diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs
index 5fc952a061..c2946d92a2 100644
--- a/crates/color/src/libraries.rs
+++ b/crates/color/src/libraries.rs
@@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option> {
// ---------- colour construction ----------
-/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped.
+/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below
+/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does
+/// ().
pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
+ oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) })
+}
+
+/// Linear sRGB of OKLab `(l, a, b)`, unclamped.
+pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
- let lin = [
+ [
4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3,
-1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3,
-0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3,
- ];
- lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 })
+ ]
}
/// OKLab `[l, a, b]` of a colour's display RGB.
@@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] {
srgb_to_oklab(c.to_rgb_uncalibrated())
}
-/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded).
+/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded
+/// with the curve's sign turned, as CSS Color 4's extended sRGB does
+/// ().
pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] {
let [r, g, b] = rgb.map(|v| {
let v = f64::from(v);
- if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+ if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) }
});
let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs
new file mode 100644
index 0000000000..31500d1ac5
--- /dev/null
+++ b/crates/color/src/oklab.rs
@@ -0,0 +1,266 @@
+//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it
+//! (): lightness L from 0 to 1, chroma
+//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take
+//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`].
+
+use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab};
+
+/// The chroma CSS reads as 100%.
+pub const CHROMA_FULL: f64 = 0.4;
+
+/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there.
+pub const POWERLESS_CHROMA: f64 = 0.000_004;
+
+/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
+const GAMUT_SLACK: f64 = 1e-4;
+
+/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
+/// are. The hue is in 0..360, and 0 while the chroma is powerless.
+pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] {
+ let [l, a, b] = srgb_to_oklab(rgb);
+ let c = a.hypot(b);
+ if c <= POWERLESS_CHROMA {
+ return [l, 0.0, 0.0];
+ }
+ [l, c, b.atan2(a).to_degrees().rem_euclid(360.0)]
+}
+
+/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped.
+pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] {
+ let (sin, cos) = h.to_radians().sin_cos();
+ oklab_to_srgb(l, c * cos, c * sin)
+}
+
+/// Whether sRGB `rgb` lies inside the sRGB gamut.
+pub fn in_srgb(rgb: [f64; 3]) -> bool {
+ rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v))
+}
+
+/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white.
+pub fn max_chroma(l: f64, h: f64) -> f64 {
+ largest_fitting_chroma(l, h, f64::INFINITY)
+}
+
+/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or
+/// outside black and white.
+///
+/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
+/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
+/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
+/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
+/// search finds each such chroma between the cubic's turning points and takes the largest one that
+/// fits.
+fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
+ if !(l > 0.0 && l < 1.0) || !h.is_finite() {
+ return 0.0;
+ }
+ let top = limit.min(0.5);
+ if top <= 0.0 {
+ return 0.0;
+ }
+ let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h));
+ if fits(top) {
+ return top;
+ }
+ let (sin, cos) = h.to_radians().sin_cos();
+ let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin);
+ // The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s.
+ let s = top / 3.0;
+ let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
+ let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
+ let mut ends = vec![0.0];
+ for ch in 0..3 {
+ let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
+ let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
+ let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
+ let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
+ // The cubic rises or falls on each stretch between its turning points.
+ let mut cuts = vec![0.0, 3.0];
+ cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0));
+ cuts.sort_by(f64::total_cmp);
+ ends.extend(cuts.iter().map(|t| t * s));
+ for w in cuts.windows(2) {
+ for bound in bounds {
+ let (mut a, mut b) = (w[0], w[1]);
+ let fa = p(a) - bound;
+ if fa * (p(b) - bound) > 0.0 {
+ continue;
+ }
+ for _ in 0..60 {
+ let mid = (a + b) / 2.0;
+ if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid }
+ }
+ ends.extend([a * s, b * s]);
+ }
+ }
+ }
+ ends.sort_by(|a, b| b.total_cmp(a));
+ ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0)
+}
+
+/// The real roots of `a t² + b t + c`.
+fn turning_points(a: f64, b: f64, c: f64) -> Vec {
+ if a.abs() < 1e-15 {
+ return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] };
+ }
+ let disc = b * b - 4.0 * a * c;
+ if disc < 0.0 {
+ return Vec::new();
+ }
+ let r = disc.sqrt();
+ vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)]
+}
+
+/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
+/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
+/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
+pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
+ let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
+ let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
+ let h = if h.is_finite() { h } else { 0.0 };
+ let exact = oklch_to_srgb(l, c, h);
+ let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
+ (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn eight(rgb: [f32; 3]) -> [u8; 3] {
+ rgb.map(|v| (v * 255.0).round() as u8)
+ }
+
+ #[test]
+ fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() {
+ let [l, c, h] = to_oklch([1.0, 0.0, 0.0]);
+ assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}");
+ let (rgb, lowered) = from_oklch(l, c, h);
+ assert_eq!((eight(rgb), lowered), ([255, 0, 0], false));
+ }
+
+ /// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give.
+ #[test]
+ fn the_polar_form_matches_the_css_examples() {
+ for ([l, a, b], [cl, cc, ch]) in
+ [([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])]
+ {
+ let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32);
+ let [ol, oc, oh] = to_oklch(rgb);
+ assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}");
+ }
+ }
+
+ #[test]
+ fn the_216_web_colors_round_trip() {
+ let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff];
+ for r in steps {
+ for g in steps {
+ for b in steps {
+ let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
+ let [l, c, h] = to_oklch(rgb);
+ assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn grays_have_no_chroma_and_hue_zero() {
+ for v in [0.0, 0.5, 1.0] {
+ let [_, c, h] = to_oklch([v, v, v]);
+ assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}");
+ }
+ }
+
+ /// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so.
+ #[test]
+ fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() {
+ let (l, h) = (0.7, 150.0);
+ let max = max_chroma(l, h);
+ assert!(max > 0.05 && max < CHROMA_FULL, "{max}");
+ assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h)));
+ let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
+ assert!(lowered);
+ let [ol, oc, oh] = to_oklch(rgb);
+ assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}");
+ assert!(!from_oklch(l, max * 0.5, h).1);
+ }
+
+ /// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the
+ /// largest chroma is blue's, and a chroma past it gives blue.
+ #[test]
+ fn the_largest_chroma_at_blues_hue_is_blues() {
+ let [l, c, h] = to_oklch([0.0, 0.0, 1.0]);
+ let max = max_chroma(l, h);
+ assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}");
+ let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
+ assert_eq!((eight(rgb), lowered), ([0, 0, 255], true));
+ // A chroma between the two stretches takes the end of the first one, inside sRGB.
+ let (rgb, lowered) = from_oklch(l, 0.29, h);
+ let [_, gc, _] = to_oklch(rgb);
+ assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
+ // A hue just past blue's: a narrow second stretch ends just below the line from black to blue.
+ let (l, h) = (0.44, 264.06);
+ let max = max_chroma(l, h);
+ assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}");
+ let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0);
+ assert!(got > 0.303, "{got}");
+ // A darker blue on the line from black to blue.
+ let [l, c, h] = to_oklch([0.0, 0.0, 0.25]);
+ assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h));
+ }
+
+ /// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a
+ /// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color
+ /// inside sRGB with the lightness and hue asked for.
+ #[test]
+ fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() {
+ let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]);
+ let l = bl * 0.3125 / bc;
+ let (rgb, lowered) = from_oklch(l, 0.29, h);
+ let [gl, gc, gh] = to_oklch(rgb);
+ assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
+ assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}");
+ }
+
+ /// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's
+ /// extended sRGB does, in both directions.
+ #[test]
+ fn negative_channels_use_the_signed_transfer_curve() {
+ let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4);
+ let [l, c, _] = to_oklch([-0.5; 3]);
+ assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}");
+ for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) {
+ assert!((v + 0.5).abs() < 1e-4, "{v}");
+ }
+ // Small values near 0 keep the straight part of the curve.
+ let [l, _, _] = to_oklch([-0.01; 3]);
+ assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}");
+ }
+
+ /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
+ /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
+ /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
+ #[test]
+ fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
+ let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
+ assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
+ for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
+ for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
+ let max = max_chroma(l, h);
+ assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h));
+ }
+ }
+ }
+
+ #[test]
+ fn black_white_and_bad_numbers_hold_no_chroma() {
+ assert_eq!(max_chroma(0.0, 30.0), 0.0);
+ assert_eq!(max_chroma(1.0, 30.0), 0.0);
+ assert_eq!(max_chroma(f64::NAN, 30.0), 0.0);
+ assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0);
+ assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
+ assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
+ }
+}
diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs
index 7c7429acc2..02458af8c5 100644
--- a/crates/doc/src/blend.rs
+++ b/crates/doc/src/blend.rs
@@ -1156,6 +1156,17 @@ impl Lerp {
(NodeKind::PlacedDocument(o), NodeKind::PlacedDocument(x), NodeKind::PlacedDocument(y)) => o.xf = lerp_affine(x.xf, y.xf, t),
_ => {}
}
+ // Between distorted images, each step's corners lie between the keys' corners. A
+ // step whose corners would fold keeps the nearer key's.
+ if (a.is_distorted_image() || b.is_distorted_image())
+ && let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners())
+ {
+ let near = if t < 0.5 { qa } else { qb };
+ if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() {
+ // The nearer key's corners passed the same check when it was distorted.
+ let _ = n.set_image_corners(near);
+ }
+ }
n.extras_mut().mask = None;
n
}
@@ -2297,6 +2308,43 @@ mod tests {
assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0));
}
+ /// A step between two distorted images has its corners between the keys' corners.
+ #[test]
+ fn steps_between_distorted_images_have_corners_between_theirs() {
+ let image = |q: [(f64, f64); 4]| {
+ let im = crate::ImageObject {
+ key: "k".into(),
+ width: 10,
+ height: 10,
+ xf: Affine::IDENTITY,
+ link: None,
+ placement: Default::default(),
+ pixels: None,
+ };
+ let mut n = Node::new(NodeId(1), NodeKind::Image(Box::new(im)));
+ n.set_image_corners(q.map(|(x, y)| Point::new(x, y))).unwrap();
+ n
+ };
+ let a = image([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ let b = image([(200.0, 0.0), (300.0, 0.0), (280.0, 100.0), (220.0, 100.0)]);
+ let mid = Lerp::new(&a, &b, (None, None)).at(0.5);
+ let want = [(120.0, 0.0), (180.0, 0.0), (190.0, 100.0), (110.0, 100.0)];
+ let got = mid.image_corners().unwrap();
+ for (g, (x, y)) in got.iter().zip(want) {
+ assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?}");
+ }
+ // Toward a key flipped left to right, the middle step's corners would meet: each step
+ // there keeps the nearer key's corners, whether that key is distorted or not.
+ let flipped = image([(60.0, 0.0), (40.0, 0.0), (0.0, 100.0), (100.0, 100.0)]);
+ let mirror = image([(100.0, 0.0), (0.0, 0.0), (0.0, 100.0), (100.0, 100.0)]);
+ assert!(!mirror.is_distorted_image());
+ for (b, t) in [(&flipped, 0.5), (&mirror, 0.5), (&mirror, 0.45)] {
+ let got = Lerp::new(&a, b, (None, None)).at(t).image_corners().unwrap();
+ let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap();
+ assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}");
+ }
+ }
+
fn key(x: f64) -> Arc {
Arc::new(Node::path(NodeId(1), vectorcraft_geom::shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()))
}
diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs
index ba6e4dc428..ba203610d6 100644
--- a/crates/doc/src/document_guides.rs
+++ b/crates/doc/src/document_guides.rs
@@ -500,11 +500,73 @@ impl Document {
self.patterns.iter_mut().find(|p| p.name == name)
}
+ /// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`.
+ /// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and
+ /// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy.
+ pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity";
+
+ /// The Symbol Set Densities recorded for `nodes` and their descendants, by id.
+ pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap {
+ let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() };
+ let mut out = std::collections::BTreeMap::new();
+ let mut stack: Vec<&Node> = nodes.iter().collect();
+ while let Some(n) = stack.pop() {
+ if let Some(v) = record.get(&n.id.0.to_string()) {
+ out.insert(n.id, v.clone());
+ }
+ stack.extend(n.children().into_iter().flatten().map(|c| &**c));
+ }
+ out
+ }
+
+ /// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set
+ /// Densities that `densities` holds for `source` and its descendants, and none for those it
+ /// holds none for (whatever [`Self::reid`] recorded).
+ pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap) {
+ if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) {
+ return;
+ }
+ let mut pairs = vec![(source, copy)];
+ while let Some((s, c)) = pairs.pop() {
+ match densities.get(&s.id) {
+ Some(v) => {
+ if let serde_json::Value::Object(m) =
+ self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default()))
+ {
+ m.insert(c.id.0.to_string(), v.clone());
+ }
+ }
+ None => {
+ if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) {
+ m.remove(&c.id.0.to_string());
+ }
+ }
+ }
+ if let (Some(sc), Some(cc)) = (s.children(), c.children()) {
+ pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b)));
+ }
+ }
+ }
+
/// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken
/// in ([`Self::adopt_pixels`]).
pub fn reid(&mut self, node: &Node) -> Node {
let mut n = node.clone();
n.id = self.alloc_id();
+ // A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source
+ // is this document's node with that id; a node from another document may share the id of an
+ // unrelated set here.
+ let density = self
+ .unknown
+ .get(Self::SYMBOL_SET_DENSITY_KEY)
+ .and_then(|m| m.get(node.id.0.to_string()))
+ .filter(|_| self.node(node.id) == Some(node))
+ .cloned();
+ if let Some(v) = density
+ && let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY)
+ {
+ m.insert(n.id.0.to_string(), v);
+ }
if let NodeKind::Image(im) = &mut n.kind {
self.adopt_image_pixels(im);
}
diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs
index c996699391..fcbe2f9db1 100644
--- a/crates/doc/src/hit.rs
+++ b/crates/doc/src/hit.rs
@@ -1503,14 +1503,17 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
// own fills and strokes paint ([`image_paint`]) except in outline mode.
- NodeKind::Image(im) => {
+ NodeKind::Image(_) => {
+ // The frame joins the image's corners ([`Node::image_frame`]); a plain image is picked
+ // inside by its bounds, without building it.
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
- use vectorcraft_geom::kurbo::Shape;
- let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
- frame.apply_affine(im.xf);
- if stroke_contains(&frame, 0.0, opt.tol, p) {
+ if n.image_frame().is_some_and(|frame| stroke_contains(&frame, 0.0, opt.tol, p)) {
return Some(HitKind::Outline);
}
+ } else if let Some(frame) = n.is_distorted_image().then(|| n.image_frame()).flatten() {
+ if fill_contains(&frame, FillRule::NonZero, p) || stroke_contains(&frame, 0.0, opt.tol, p) {
+ return Some(HitKind::Bounds);
+ }
} else if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs
new file mode 100644
index 0000000000..e07fd47760
--- /dev/null
+++ b/crates/doc/src/image_quad.rs
@@ -0,0 +1,599 @@
+//! Perspective Distort and Free Distort on an image: its pixel rectangle's corners placed anywhere
+//! on the page, as long as they make a strictly convex quadrilateral.
+//!
+//! An image whose corners make a parallelogram is placed by its transform alone
+//! ([`crate::ImageObject::xf`]). Other corners are kept in the image's extras
+//! ([`crate::NodeExtras::image_quad`]), and the image is then drawn through the projective map
+//! that takes its pixel rectangle to them. The renderer, the exporters and printing draw it as a
+//! raster mesh warp ([`crate::live::mesh_warp_image`]) made from that map ([`distorted_art`]): no
+//! warped copy of the pixels is kept. The quad stays with the image's transform: moving, scaling,
+//! rotating or shearing the image maps its corners too ([`crate::Node::transform`]).
+//!
+//! The convexity rule, the tolerance of the mesh and its cell limit are VectorCraft's own.
+
+use std::sync::Arc;
+
+use vectorcraft_geom::kurbo::BezPath;
+use vectorcraft_geom::{Affine, Homography, PathData, Point, Rect, SubPath};
+
+use crate::{Appearance, ImageObject, Node, NodeKind};
+
+/// Most cells along each side of the mesh an image is drawn with ([`cells`]).
+pub const MAX_CELLS: usize = 64;
+
+/// The cells along each side an image with fewer pixels than this may still take ([`cells`]).
+pub const MIN_CELL_CAP: usize = 8;
+
+/// How far (in points) the mesh an image is drawn with in files and print may stray from the exact
+/// projective map ([`Density::PAGE`]).
+pub const TOLERANCE: f64 = 0.05;
+
+/// How finely [`distorted_art_at`] cuts a distorted image ([`cells`]), and how far each piece
+/// reaches into its neighbors. A pixel inside the image draws opaque only when one piece covers
+/// it whole, so pieces much smaller than a pixel would let the page show through.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Density {
+ /// How far (in points) the mesh may stray from the exact projective map.
+ pub tolerance: f64,
+ /// The shortest a cell may be along the longest side of the corners, in points.
+ pub min_cell: f64,
+ /// How far (in points) each piece reaches past its triangle.
+ pub overlap: f64,
+}
+
+impl Density {
+ /// For files and print, whose viewing size is not known: within [`TOLERANCE`], cells of at
+ /// least 2 pt, and pieces that reach half a point past their triangles.
+ pub const PAGE: Density = Density { tolerance: TOLERANCE, min_cell: 2.0, overlap: 0.5 };
+
+ /// For drawing at `scale` device pixels a point: within a quarter of a pixel, cells of at least
+ /// 4 pixels, and pieces that reach 2 pixels past their triangles.
+ pub fn at_scale(scale: f64) -> Density {
+ let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 };
+ Density { tolerance: 0.25 / s, min_cell: 4.0 / s, overlap: 2.0 / s }
+ }
+
+ /// [`Density::PAGE`] for art that is drawn `scale` times its size (a symbol's art in an
+ /// instance that scales it): the tolerance, the cell size and the overlap measured on the page.
+ pub fn page_at(scale: f64) -> Density {
+ let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 };
+ let p = Density::PAGE;
+ Density { tolerance: p.tolerance / s, min_cell: p.min_cell / s, overlap: p.overlap / s }
+ }
+}
+
+/// How much `a` stretches its most stretched direction: the larger singular value of its linear
+/// part.
+pub fn max_stretch(a: Affine) -> f64 {
+ let [m0, m1, m2, m3, _, _] = a.as_coeffs();
+ let sum = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3;
+ let det = m0 * m3 - m1 * m2;
+ ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
+}
+
+/// Why corners cannot be an image's.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum QuadError {
+ /// A corner is not a finite point.
+ NotFinite,
+ /// The corners fold over, meet, or lie on one line: the quadrilateral is not strictly convex.
+ NotConvex,
+ /// The corners are convex but so close to a line that the perspective map through them cannot
+ /// place every corner.
+ TooNarrow,
+}
+
+impl std::fmt::Display for QuadError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Self::NotFinite => "the corners of a distorted image must be finite points",
+ Self::NotConvex => "the corners of a distorted image must make a convex shape: an image cannot fold over itself or collapse to a line",
+ Self::TooNarrow => "the corners of a distorted image are too close together for a perspective map",
+ })
+ }
+}
+
+/// `im`'s pixel rectangle: (0, 0) to its width and height.
+fn pixel_rect(im: &ImageObject) -> Rect {
+ Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))
+}
+
+/// The corners of `r` in the order a quad keeps them: top left, top right, bottom right, bottom
+/// left.
+fn rect_corners(r: Rect) -> [Point; 4] {
+ [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
+}
+
+/// Whether the corners `q` (in order around the shape) are finite and make a strictly convex
+/// quadrilateral, turning either way round. Each turn must be larger than 1e-9 times the product
+/// of the two sides it joins, a test that gives the same answer at any scale.
+pub fn check(q: &[Point; 4]) -> Result<(), QuadError> {
+ if q.iter().any(|p| !p.is_finite()) {
+ return Err(QuadError::NotFinite);
+ }
+ let mut sign = 0.0;
+ for i in 0..4 {
+ let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]);
+ let (u, v) = (b - a, c - b);
+ let cross = u.cross(v);
+ let scale = u.hypot() * v.hypot();
+ if !cross.is_finite() || !scale.is_finite() || cross.abs() <= 1e-9 * scale || scale == 0.0 {
+ return Err(QuadError::NotConvex);
+ }
+ if sign == 0.0 {
+ sign = cross.signum();
+ } else if cross.signum() != sign {
+ return Err(QuadError::NotConvex);
+ }
+ }
+ // Four turns the same way round can still wind twice (a star); a convex quadrilateral's
+ // diagonals cross.
+ let crosses = |a: Point, b: Point, c: Point, d: Point| (b - a).cross(c - a).signum() != (b - a).cross(d - a).signum();
+ if !crosses(q[0], q[2], q[1], q[3]) || !crosses(q[1], q[3], q[0], q[2]) {
+ return Err(QuadError::NotConvex);
+ }
+ Ok(())
+}
+
+/// Whether `q` can be image `im`'s corners: [`check`], and either a parallelogram or corners the
+/// perspective map from its pixels ([`pixel_map`]) places, each within a millionth of `q`'s
+/// shortest side plus the rounding error of coordinates as far from the origin as `q`'s.
+pub fn check_for(im: &ImageObject, q: &[Point; 4]) -> Result<(), QuadError> {
+ check(q)?;
+ if parallelogram(im, q).is_some() {
+ return Ok(());
+ }
+ let tol = placement_tolerance(q);
+ let map = pixel_map(im, q);
+ let placed = rect_corners(pixel_rect(im)).iter().zip(q).all(|(c, want)| map.apply(*c).is_some_and(|p| p.distance(*want) <= tol));
+ if placed { Ok(()) } else { Err(QuadError::TooNarrow) }
+}
+
+/// How far a map may place a corner from `q`'s: a millionth of `q`'s shortest side plus the
+/// rounding error of coordinates as far from the origin as `q`'s.
+fn placement_tolerance(q: &[Point; 4]) -> f64 {
+ let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
+ let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
+ side * 1e-6 + far * 1e-12
+}
+
+/// The affine map from `im`'s pixel space that places its corners at `q`, when `q` is a
+/// parallelogram (within 1e-9 of the quad's size): the map puts the fourth corner within
+/// [`placement_tolerance`] of `q`'s. `None` otherwise.
+fn parallelogram(im: &ImageObject, q: &[Point; 4]) -> Option {
+ let size = q.iter().fold(0.0_f64, |m, p| m.max((*p - q[0]).hypot()));
+ // The affine map through the other three corners misses the bottom right one by this much.
+ let gap = (q[0].to_vec2() + q[2].to_vec2() - q[1].to_vec2() - q[3].to_vec2()).hypot();
+ if gap > 1e-9 * size || gap > placement_tolerance(q) {
+ return None;
+ }
+ let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
+ let (x, y) = ((q[1] - q[0]) / w, (q[3] - q[0]) / h);
+ let a = Affine::new([x.x, x.y, y.x, y.y, q[0].x, q[0].y]);
+ a.is_finite().then_some(a)
+}
+
+/// The homography taking the unit square's corners (0,0), (1,0), (1,1), (0,1) to `q`.
+fn square_to(q: &[Point; 4]) -> Homography {
+ let [p0, p1, p2, p3] = *q;
+ let (sx, sy) = (p0.x - p1.x + p2.x - p3.x, p0.y - p1.y + p2.y - p3.y);
+ let (dx1, dx2, dy1, dy2) = (p1.x - p2.x, p3.x - p2.x, p1.y - p2.y, p3.y - p2.y);
+ let den = dx1 * dy2 - dx2 * dy1;
+ let (g, h) = if den.abs() < 1e-300 { (0.0, 0.0) } else { ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den) };
+ Homography([[p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x], [p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y], [g, h, 1.0]])
+}
+
+impl Node {
+ /// This image's distortion: where its pixel rectangle's corners stand (top left, top right,
+ /// bottom right, bottom left) when they do not make a parallelogram. `None` for an image placed
+ /// by its transform alone, for anything that is not an image, and for corners a file holds
+ /// that [`check_for`] refuses (the image is then placed by its transform).
+ pub fn image_quad(&self) -> Option<[Point; 4]> {
+ let NodeKind::Image(im) = &self.kind else { return None };
+ let q = **self.extras().image_quad.as_ref()?;
+ check_for(im, &q).is_ok().then_some(q)
+ }
+
+ /// Whether this is an image with a distortion ([`Self::image_quad`]).
+ pub fn is_distorted_image(&self) -> bool {
+ self.image_quad().is_some()
+ }
+
+ /// Where this image's pixel rectangle's corners stand: its distortion, or its transform's
+ /// corners. `None` for anything that is not an image.
+ pub fn image_corners(&self) -> Option<[Point; 4]> {
+ let NodeKind::Image(im) = &self.kind else { return None };
+ Some(self.image_quad().unwrap_or_else(|| rect_corners(pixel_rect(im)).map(|p| im.xf * p)))
+ }
+
+ /// Place this image's corners at `q` (top left, top right, bottom right, bottom left): by its
+ /// transform when they make a parallelogram (and the distortion is cleared), else as its
+ /// distortion. An error, and nothing changes, when `q` fails [`check_for`] or this is not an
+ /// image.
+ pub fn set_image_corners(&mut self, q: [Point; 4]) -> Result<(), QuadError> {
+ let NodeKind::Image(im) = &mut self.kind else { return Err(QuadError::NotConvex) };
+ check_for(im, &q)?;
+ match parallelogram(im, &q) {
+ Some(xf) => {
+ im.xf = xf;
+ if self.extras().image_quad.is_some() {
+ self.extras_mut().image_quad = None;
+ }
+ }
+ None => self.extras_mut().image_quad = Some(Box::new(q)),
+ }
+ Ok(())
+ }
+
+ /// The outline of this image's frame on the page: its corners joined by straight lines.
+ /// `None` for anything that is not an image.
+ pub fn image_frame(&self) -> Option {
+ let q = self.image_corners()?;
+ let mut bp = BezPath::new();
+ bp.move_to(q[0]);
+ for p in &q[1..] {
+ bp.line_to(*p);
+ }
+ bp.close_path();
+ Some(bp)
+ }
+
+ /// The map from this image's pixel space to the page: projective for a distorted image, its
+ /// transform otherwise. `None` for anything that is not an image.
+ pub fn image_map(&self) -> Option {
+ let NodeKind::Image(im) = &self.kind else { return None };
+ Some(match self.image_quad() {
+ Some(q) => pixel_map(im, &q),
+ None => Homography::from_affine(im.xf),
+ })
+ }
+}
+
+/// The projective map from `im`'s pixel space to the page that puts its corners at `q`.
+fn pixel_map(im: &ImageObject, q: &[Point; 4]) -> Homography {
+ let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
+ square_to(q).then_after(&Homography::from_affine(Affine::scale_non_uniform(1.0 / w, 1.0 / h)))
+}
+
+/// How many cells along each side the mesh of a distorted image takes: the fewest (a power of two
+/// up to [`MAX_CELLS`]) for which the mesh's triangles, each mapped by the affine map through its
+/// corners, stay within `density`'s tolerance of `map` at the middle of every cell and every cell
+/// side. An image takes no more cells than it has pixels along its longer side, or
+/// [`MIN_CELL_CAP`] when that is more, and no more than leave each cell `density.min_cell` along
+/// the longest side of its corners. A perspective that needs more cells than these limits allow is
+/// drawn with the cells they allow.
+pub fn cells(map: &Homography, im: &ImageObject, density: Density) -> usize {
+ let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
+ let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| map.apply(p));
+ let longest =
+ corners.iter().zip(corners.iter().cycle().skip(1)).filter_map(|(a, b)| Some(a.as_ref()?.distance(*b.as_ref()?))).fold(0.0, f64::max);
+ let by_size = longest / density.min_cell;
+ let by_size = if by_size.is_finite() { (by_size as usize).max(1) } else { MAX_CELLS };
+ let most = MAX_CELLS.min((im.width.max(im.height) as usize).max(MIN_CELL_CAP)).min(by_size);
+ let at = |x: f64, y: f64| map.apply(Point::new(x, y));
+ let mut k = 1;
+ while k < most {
+ let fits = (0..k * k).all(|c| {
+ let (i, j) = ((c % k) as f64, (c / k) as f64);
+ let (x0, y0, x1, y1) = (w * i / k as f64, h * j / k as f64, w * (i + 1.0) / k as f64, h * (j + 1.0) / k as f64);
+ let (Some(a), Some(b), Some(cc), Some(d)) = (at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)) else { return false };
+ let near = |exact: Option, m: Point| exact.is_some_and(|e| e.distance(m) <= density.tolerance);
+ near(at((x0 + x1) / 2.0, (y0 + y1) / 2.0), a.midpoint(cc))
+ && near(at((x0 + x1) / 2.0, y0), a.midpoint(b))
+ && near(at(x1, (y0 + y1) / 2.0), b.midpoint(cc))
+ && near(at((x0 + x1) / 2.0, y1), d.midpoint(cc))
+ && near(at(x0, (y0 + y1) / 2.0), a.midpoint(d))
+ });
+ if fits {
+ break;
+ }
+ k *= 2;
+ }
+ k.min(most)
+}
+
+/// For a format that cannot clip an image into the pieces of [`distorted_art`]: the affine
+/// placement nearest distorted image `n`'s projective map, the one that matches it at the middle
+/// of its pixels. `None` when `n` is not a distorted image.
+pub fn nearest_affine(n: &Node) -> Option {
+ let NodeKind::Image(im) = &n.kind else { return None };
+ let q = n.image_quad()?;
+ pixel_map(im, &q).affine_at(pixel_rect(im).center())
+}
+
+/// Distorted image `n` as the art that draws it in files and print: [`distorted_art_at`] with
+/// [`Density::PAGE`].
+pub fn distorted_art(n: &Node) -> Option {
+ distorted_art_at(n, Density::PAGE)
+}
+
+/// Distorted image `n` as the art that draws it: a clip group, clipped by its corners, around the
+/// raster mesh warp ([`crate::live::mesh_warp_image`]) of its pixels through its projective map,
+/// with [`cells`] cells along each side for `density` and each piece reaching `density.overlap`
+/// past its triangle. The art has `n`'s id but not its name and transparency (which the caller
+/// keeps on the object around the art). `None` when `n` is not a distorted image.
+pub fn distorted_art_at(n: &Node, density: Density) -> Option {
+ let NodeKind::Image(im) = &n.kind else { return None };
+ let q = n.image_quad()?;
+ let map = pixel_map(im, &q);
+ let k = cells(&map, im, density);
+ let mut plain = n.clone();
+ // Whether the image shows is the image's to decide: a hidden source image that a view draws
+ // anyway (Image Trace's Source Image) draws its art.
+ plain.visible = true;
+ // The image's own fills and strokes paint by the image's rules, not on the mesh's group.
+ plain.appearance = Default::default();
+ plain.name = None;
+ plain.opacity = 1.0;
+ plain.blend = Default::default();
+ plain.isolate = false;
+ plain.knockout = Default::default();
+ plain.knockout_shape = false;
+ if let Some(e) = plain.extras_if_any() {
+ e.mask = None;
+ }
+ let mut art = crate::live::mesh_warp_image_with(&plain, im, &|p| p, k, n.extras().pixelated, false, Some(density.overlap));
+ // The pieces along the image's edges reach past its corners too: the corners clip them.
+ let mut edge = Node::path(n.id, PathData::single(SubPath::polyline(&q, true)), Appearance::default());
+ if let NodeKind::Path { clipping, .. } = &mut edge.kind {
+ *clipping = true;
+ }
+ let pieces = std::mem::replace(&mut art.kind, NodeKind::Group { children: vec![], clip: true });
+ let mut mesh = art.clone();
+ mesh.kind = pieces;
+ art.knockout = Default::default();
+ art.kind = NodeKind::Group { children: vec![Arc::new(edge), Arc::new(mesh)], clip: true };
+ Some(art)
+}
+
+/// The pieces of [`distorted_art_at`]'s art: the children of its mesh group.
+pub fn distorted_pieces(art: &Node) -> &[Arc] {
+ art.children().and_then(|c| c.get(1)).and_then(|m| m.children()).map_or(&[], Vec::as_slice)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::NodeId;
+
+ fn image(w: u32, h: u32) -> Node {
+ let im = ImageObject { key: "k".into(), width: w, height: h, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
+ Node::new(NodeId(1), NodeKind::Image(Box::new(im)))
+ }
+
+ fn pts(v: [(f64, f64); 4]) -> [Point; 4] {
+ v.map(|(x, y)| Point::new(x, y))
+ }
+
+ #[test]
+ fn a_convex_quad_either_way_round_passes_and_a_fold_or_line_does_not() {
+ assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Ok(()));
+ assert_eq!(check(&pts([(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)])), Ok(()));
+ // Two corners swapped: the sides cross.
+ assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])), Err(QuadError::NotConvex));
+ // A dent.
+ assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (2.0, 2.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
+ // Three on a line, and two corners at one point.
+ assert_eq!(check(&pts([(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
+ assert_eq!(check(&pts([(0.0, 0.0), (0.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
+ assert_eq!(check(&pts([(f64::NAN, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotFinite));
+ }
+
+ /// A convex quad with one edge so short that the perspective map through it cannot place the
+ /// other corners: refused when set, and a file's copy of it leaves the image undistorted.
+ #[test]
+ fn corners_the_perspective_map_cannot_place_are_refused() {
+ let q = pts([(50.0, 0.0), (50.000000005, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ assert_eq!(check(&q), Ok(()));
+ let mut n = image(100, 100);
+ assert_eq!(n.set_image_corners(q), Err(QuadError::TooNarrow));
+ assert!(n.extras().image_quad.is_none());
+ n.extras_mut().image_quad = Some(Box::new(q));
+ assert_eq!(n.image_quad(), None);
+ assert!(distorted_art(&n).is_none());
+ assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0))));
+ }
+
+ #[test]
+ fn a_parallelogram_goes_into_the_transform_and_other_corners_into_the_quad() {
+ let mut n = image(100, 50);
+ n.set_image_corners(pts([(10.0, 0.0), (110.0, 10.0), (100.0, 60.0), (0.0, 50.0)])).unwrap();
+ assert_eq!(n.image_quad(), None);
+ let NodeKind::Image(im) = &n.kind else { panic!("an image") };
+ assert!((im.xf * Point::new(100.0, 50.0)).distance(Point::new(100.0, 60.0)) < 1e-9);
+ let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ n.set_image_corners(q).unwrap();
+ assert_eq!(n.image_quad(), Some(q));
+ assert_eq!(n.image_corners(), Some(q));
+ let map = n.image_map().unwrap();
+ for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 50.0)).iter().zip(q) {
+ assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}");
+ }
+ // Back to a rectangle: the quad is cleared.
+ n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)])).unwrap();
+ assert!(n.extras().image_quad.is_none());
+ }
+
+ /// Corners whose gap from a parallelogram is tiny next to the quad's size but not next to its
+ /// shortest side stay a distortion: the affine map would put the bottom right corner twice as
+ /// low as asked.
+ #[test]
+ fn corners_the_affine_map_misses_stay_a_distortion() {
+ let mut n = image(100, 100);
+ let q = pts([(0.0, 0.0), (100000.0, 0.0), (100000.0, 0.00005), (0.0, 0.0001)]);
+ n.set_image_corners(q).unwrap();
+ assert_eq!(n.image_quad(), Some(q));
+ let map = n.image_map().unwrap();
+ for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q) {
+ assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}");
+ }
+ }
+
+ /// A scale that squeezes valid corners past what a perspective map can place leaves the image
+ /// at the placement nearest them, scaled, not at the rectangle it had before.
+ #[test]
+ fn a_scale_past_the_perspective_limit_keeps_the_nearest_placement() {
+ let mut n = image(100, 100);
+ n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 2e-7), (0.0, 2e-7)])).unwrap();
+ assert!(n.is_distorted_image());
+ n.transform(Affine::scale_non_uniform(1.0, 0.25), false);
+ assert!(n.extras().image_quad.is_none());
+ let b = n.geometric_bounds().unwrap();
+ assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}");
+ }
+
+ /// A file's corners that the image cannot take are dropped as it is read, so a later scale
+ /// that would make them valid leaves the image placed by its transform; a list of three
+ /// points is dropped too, and the rest of the image is read.
+ #[test]
+ fn corners_a_file_holds_that_are_refused_or_not_four_are_dropped_as_it_is_read() {
+ let mut n = image(100, 100);
+ n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 5e-8), (0.0, 5e-8)])));
+ assert_eq!(n.image_quad(), None);
+ let mut read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
+ assert!(read.extras().image_quad.is_none());
+ read.transform(Affine::scale_non_uniform(1.0, 4.0), false);
+ assert!(!read.is_distorted_image());
+ assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 400.0)));
+ let mut v = serde_json::to_value(&n).unwrap();
+ v["image_quad"] = serde_json::json!([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]);
+ let read: Node = serde_json::from_value(v).unwrap();
+ assert!(read.extras().image_quad.is_none());
+ assert!(matches!(read.kind, NodeKind::Image(_)));
+ // Past a fourth point the rest is skipped without being read as points.
+ for extra in [serde_json::json!([5.0, 5.0]), serde_json::json!("not a point")] {
+ let mut v = serde_json::to_value(&n).unwrap();
+ v["image_quad"] = serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], [0.0, 100.0], extra, {"x": 1}]);
+ let read: Node = serde_json::from_value(v).unwrap();
+ assert!(read.extras().image_quad.is_none());
+ }
+ // Valid corners read back.
+ let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ n.set_image_corners(q).unwrap();
+ let read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
+ assert_eq!(read.image_quad(), Some(q));
+ }
+
+ #[test]
+ fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() {
+ let mut n = image(10, 10);
+ let before = n.clone();
+ assert!(n.set_image_corners(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])).is_err());
+ assert_eq!(n, before);
+ n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])));
+ assert_eq!(n.image_quad(), None);
+ assert_eq!(n.image_corners(), Some(pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])));
+ }
+
+ #[test]
+ fn the_mesh_is_as_fine_as_the_perspective_needs() {
+ let mut n = image(400, 400);
+ n.set_image_corners(pts([(10.0, 0.0), (400.0, 5.0), (390.0, 400.0), (0.0, 395.0)])).unwrap();
+ let NodeKind::Image(im) = n.kind.clone() else { panic!("an image") };
+ let gentle = cells(&n.image_map().unwrap(), &im, Density::PAGE);
+ n.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap();
+ let strong = cells(&n.image_map().unwrap(), &im, Density::PAGE);
+ assert!(gentle < strong && strong <= MAX_CELLS, "{gentle} {strong}");
+ // Three by two pixels drawn as large still bend, in up to MIN_CELL_CAP cells.
+ let mut tiny = image(3, 2);
+ tiny.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap();
+ let NodeKind::Image(tim) = &tiny.kind else { panic!("an image") };
+ assert_eq!(cells(&tiny.image_map().unwrap(), tim, Density::PAGE), MIN_CELL_CAP.min(strong));
+ // Drawn small, the same corners take only cells of at least 4 pixels: their longest side,
+ // about 431 pt, is about 17 pixels at 1/25 px a point, room for 4 cells.
+ let map = n.image_map().unwrap();
+ assert!(cells(&map, &im, Density::at_scale(1.0 / 25.0)) <= 4);
+ // Drawn large, a quarter of a pixel is finer than 0.05 pt, so no fewer cells than on the page.
+ assert!(cells(&map, &im, Density::at_scale(8.0)) >= strong);
+ // Each cell of the page's mesh is at least 2 pt along the longest side: about 32 pt takes
+ // 16 at most.
+ let mut small = image(400, 400);
+ small.set_image_corners(pts([(12.0, 0.0), (18.0, 0.0), (30.0, 30.0), (0.0, 30.0)])).unwrap();
+ assert!(cells(&small.image_map().unwrap(), &im, Density::PAGE) <= 16);
+ }
+
+ /// Each piece of the art reaches the density's overlap past its triangle, and the corners clip
+ /// the art, so nothing draws outside them.
+ #[test]
+ fn the_pieces_overlap_and_the_corners_clip_them() {
+ let mut n = image(100, 100);
+ let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ n.set_image_corners(q).unwrap();
+ let art = distorted_art_at(&n, Density { tolerance: 1.0, min_cell: 1.0, overlap: 3.0 }).unwrap();
+ let Some([edge, _]) = art.children().map(Vec::as_slice) else { panic!("an edge and a mesh") };
+ assert!(matches!(edge.kind, NodeKind::Path { clipping: true, .. }));
+ assert_eq!(edge.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
+ let pieces = distorted_pieces(&art);
+ assert!(pieces.len() >= 2);
+ // The first piece's clip triangle reaches 3 pt past the image's top left corner.
+ let Some([clip, _]) = pieces[0].children().map(Vec::as_slice) else { panic!("a clip and an image") };
+ let b = clip.geometric_bounds().unwrap();
+ assert!(b.y0 < -2.0, "{b:?}");
+ }
+
+ #[test]
+ fn the_art_puts_the_pixel_corners_on_the_quad() {
+ let mut n = image(100, 100);
+ n.opacity = 0.5;
+ let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ n.set_image_corners(q).unwrap();
+ let art = distorted_art(&n).unwrap();
+ assert_eq!(art.opacity, 1.0);
+ let mut corners_seen = [false; 4];
+ art.walk(&mut |c| {
+ if let NodeKind::Image(im) = &c.kind {
+ for (i, (p, want)) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q).enumerate() {
+ if (im.xf * *p).distance(want) < 1e-9 {
+ corners_seen[i] = true;
+ }
+ }
+ }
+ });
+ assert_eq!(corners_seen, [true; 4]);
+ assert!(distorted_art(&image(4, 4)).is_none());
+ // A hidden image that a view draws anyway gives art that draws.
+ n.visible = false;
+ assert!(distorted_art(&n).unwrap().visible);
+ // The image's own fills and strokes stay off the mesh's group.
+ let stroke = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
+ n.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, stroke, 1.0).into();
+ assert!(distorted_art(&n).unwrap().appearance.items.is_empty());
+ }
+
+ #[test]
+ fn deep_expansion_reaches_a_distorted_image_inside_a_group() {
+ let mut n = image(100, 100);
+ n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap();
+ let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n)], clip: false });
+ let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false });
+ let out = crate::live::expand_deep(&outer, None);
+ let mut distorted = 0;
+ let mut pieces = 0;
+ out.walk(&mut |c| {
+ distorted += usize::from(c.is_distorted_image());
+ pieces += usize::from(matches!(c.kind, NodeKind::Image(_)));
+ });
+ assert_eq!(distorted, 0);
+ assert!(pieces > 1, "{pieces}");
+ }
+
+ /// A distorted image with an effect of its own stays an image with its appearance when the
+ /// art around it is expanded, so the effect still applies where the art is drawn.
+ #[test]
+ fn deep_expansion_keeps_a_distorted_image_with_its_own_appearance() {
+ let mut n = image(100, 100);
+ n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap();
+ let effect = crate::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 40}), visible: true };
+ n.appearance = crate::Appearance { effects: vec![effect], ..Default::default() }.into();
+ let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n.clone())], clip: false });
+ let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false });
+ let out = crate::live::expand_deep(&outer, None);
+ let mut kept = vec![];
+ out.walk(&mut |c| {
+ if c.is_distorted_image() {
+ kept.push(c.appearance.clone());
+ }
+ });
+ assert_eq!(kept, vec![n.appearance]);
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 3f53bc693f..0578474c99 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -22,6 +22,7 @@ pub mod graph;
mod halftone_radii;
pub mod hit;
mod id_index;
+pub mod image_quad;
pub use id_index::{path_lookups, tree_walks};
pub mod inks;
mod inline;
diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs
index 337634db2e..3813b24950 100644
--- a/crates/doc/src/live.rs
+++ b/crates/doc/src/live.rs
@@ -57,11 +57,11 @@ pub use envelope::{
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
};
-pub(crate) use expand::max_outset;
pub use expand::{
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
- expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
+ expanded_group, expanded_group_hooks, is_drawn_live, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
};
+pub(crate) use expand::{max_outset, mesh_warp_image_with};
#[cfg(test)]
use mesh::grid_eval;
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs
index d87d7a28c4..e1eb3acc3d 100644
--- a/crates/doc/src/live/expand.rs
+++ b/crates/doc/src/live/expand.rs
@@ -212,12 +212,26 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
/// partly transparent image keeps its own alpha there. More cells than [`MAX_GENERATED`] objects
/// allow make an empty group.
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
+ mesh_warp_image_with(n, im, f, cells, pixelated, masked, None)
+}
+
+/// [`mesh_warp_image`], each piece reaching `overlap` points past its edges when given.
+pub(crate) fn mesh_warp_image_with(
+ n: &Node,
+ im: &ImageObject,
+ f: &dyn Fn(Point) -> Point,
+ cells: usize,
+ pixelated: bool,
+ masked: bool,
+ overlap: Option,
+) -> Node {
let k = cells.max(1);
let mut g = n.clone();
g.kind = NodeKind::Group { children: vec![], clip: false };
g.knockout = crate::Knockout::On;
if let Some(e) = g.extras_if_any() {
e.colorize = None;
+ e.image_quad = None;
}
if mesh_warp_cost(k) > MAX_GENERATED {
return g;
@@ -228,24 +242,31 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
let color_mask = n.extras().color_mask.clone();
let (pw, ph) = (im.width as f64, im.height as f64);
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
+ // A distorted image's pixels reach the page through its projective map.
+ let to_page = n.image_map().filter(|_| n.is_distorted_image());
+ let place = |p: Point| to_page.and_then(|m| m.apply(p)).unwrap_or(im.xf * p);
let mut pieces = Vec::with_capacity(2 * k * k);
for j in 0..k {
for i in 0..k {
let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
- let d = s.map(|p| f(im.xf * p));
+ let d = s.map(|p| f(place(p)));
for t in [[0, 1, 2], [0, 2, 3]] {
let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v]));
let Some(xf) = affine_between(st, dt) else { continue };
let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0);
- let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
- let tri: Vec = dt
- .iter()
- .map(|p| {
- let v = *p - c;
- let len = v.hypot();
- if len > 1e-12 { *p + v * (grow / len) } else { *p }
- })
- .collect();
+ let tri: Vec = match overlap {
+ Some(g) => grown_triangle(dt, g),
+ None => {
+ let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
+ dt.iter()
+ .map(|p| {
+ let v = *p - c;
+ let len = v.hypot();
+ if len > 1e-12 { *p + v * (grow / len) } else { *p }
+ })
+ .collect()
+ }
+ };
let shape = PathData::single(SubPath::polyline(&tri, true));
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
image.extras_mut().pixelated = pixelated;
@@ -274,6 +295,23 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
g
}
+/// Triangle `t` with each side moved `g` outward: `t` scaled about its incenter. A corner moves
+/// at most 8 `g`, so a very thin triangle's sides move less than `g`.
+fn grown_triangle(t: [Point; 3], g: f64) -> Vec {
+ let side = |i: usize| t[(i + 1) % 3].distance(t[(i + 2) % 3]);
+ let (a, b, c) = (side(0), side(1), side(2));
+ let perimeter = a + b + c;
+ let area = ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs();
+ if !(perimeter > 1e-12 && area > 0.0 && g.is_finite() && g > 0.0) {
+ return t.to_vec();
+ }
+ let center = Point::new((a * t[0].x + b * t[1].x + c * t[2].x) / perimeter, (a * t[0].y + b * t[1].y + c * t[2].y) / perimeter);
+ let r = 2.0 * area / perimeter;
+ let far = t.iter().map(|p| p.distance(center)).fold(0.0, f64::max);
+ let grow = (g / r).min(8.0 * g / far.max(1e-12));
+ t.iter().map(|p| center + (*p - center) * (1.0 + grow)).collect()
+}
+
/// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the
/// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its
/// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None`
@@ -353,6 +391,13 @@ pub fn is_live(n: &Node) -> bool {
)
}
+/// Is this drawn and written as evaluated art: a live object ([`is_live`]) or a distorted image
+/// ([`Node::image_quad`]), whose art is [`crate::image_quad::distorted_art`]. Effects and
+/// container paint treat a distorted image as an image, not as live art.
+pub fn is_drawn_live(n: &Node) -> bool {
+ is_live(n) || n.is_distorted_image()
+}
+
/// Mesh tessellation as flat-filled paths (no stroke): each patch cut `n`×`n`, its quads joined
/// where the colour hardly changes ([`GradientMesh::pieces`]).
pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec {
@@ -388,6 +433,7 @@ pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec {
NodeKind::Repeat(r) => r.expand(hooks.symbols),
NodeKind::PlacedDocument(p) => p.art(n),
NodeKind::Intertwine { children } => crate::intertwine::expand(children),
+ NodeKind::Image(_) => vec![crate::image_quad::distorted_art(n).unwrap_or_else(|| n.clone())],
_ => vec![n.clone()],
}
}
@@ -429,7 +475,7 @@ pub fn expand_deep(n: &Node, outline: Outliner) -> Node {
/// expands to nothing.
pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
let _generating = Generating::enter();
- let mut out = if is_live(n) {
+ let mut out = if is_drawn_live(n) {
let g = expanded_group_hooks(n, hooks);
if !Generating::charge(g.count()) {
return Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
@@ -440,7 +486,12 @@ pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
};
if let Some(ch) = out.children_mut() {
for c in ch.iter_mut() {
- if subtree_has_live(c) {
+ // A distorted image with fills, strokes or effects of its own stays an image: whoever
+ // draws the art draws it with them, as it draws a distorted image anywhere else.
+ if c.is_distorted_image() && !(c.appearance.items.is_empty() && c.appearance.effects.is_empty()) {
+ continue;
+ }
+ if subtree_has_drawn_live(c) {
*c = Arc::new(expand_deep_hooks(c, hooks));
}
}
@@ -497,6 +548,13 @@ pub fn subtree_has_live(n: &Node) -> bool {
any
}
+/// Does `n` or any descendant draw as evaluated art ([`is_drawn_live`])?
+fn subtree_has_drawn_live(n: &Node) -> bool {
+ let mut any = false;
+ n.walk(&mut |c| any |= is_drawn_live(c));
+ any
+}
+
/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the
/// reach of symbol art), type's character strokes included as type's own visual bounds measure them
/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight
diff --git a/crates/doc/src/node/clip.rs b/crates/doc/src/node/clip.rs
index b26fa52e1c..25f716460e 100644
--- a/crates/doc/src/node/clip.rs
+++ b/crates/doc/src/node/clip.rs
@@ -44,8 +44,12 @@ impl Node {
}
}
NodeKind::Image(im) => {
- let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
- out.push((frame.to_bezpath(), FillRule::NonZero));
+ // A distorted image's frame joins its corners.
+ let frame = match self.image_frame().filter(|_| self.is_distorted_image()) {
+ Some(bp) => bp,
+ None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf).to_bezpath(),
+ };
+ out.push((frame, FillRule::NonZero));
}
NodeKind::PlacedDocument(p) => {
let frame = shapes::rectangle(p.natural()).transformed(p.xf);
diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs
index f953deda71..439d3605fd 100644
--- a/crates/doc/src/node/extras.rs
+++ b/crates/doc/src/node/extras.rs
@@ -3,6 +3,7 @@ use super::kind::NodeKind;
use super::live_shape::LiveShape;
use super::opacity::OpacityMask;
use super::{Node, PathData};
+use vectorcraft_geom::Point;
/// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without
/// them stay small ([`Node::extras`]).
@@ -87,6 +88,10 @@ pub struct NodeExtras {
/// 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,
+ /// As an image after Perspective Distort or Free Distort, where its pixel rectangle's corners
+ /// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they
+ /// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]).
+ pub image_quad: Option>,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -118,6 +123,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
color_mask: None,
warp_piece: false,
clip_pieces: false,
+ image_quad: None,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs
index e83aae1b09..20dae6ec4b 100644
--- a/crates/doc/src/node/ops.rs
+++ b/crates/doc/src/node/ops.rs
@@ -386,6 +386,10 @@ impl Node {
.filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. }))
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))),
NodeKind::Text(t) => self.projected(t.bounds()),
+ // A distorted image is bounded by its corners.
+ NodeKind::Image(_) if self.is_distorted_image() => {
+ self.image_corners().map(|q| q[1..].iter().fold(Rect::from_points(q[0], q[0]), |r, p| r.union_pt(*p)))
+ }
NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))),
NodeKind::SymbolInstance { symbol, xf } => {
let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric);
@@ -528,6 +532,9 @@ impl Node {
}
// The path the objects are attached to, before it is transformed.
let on_path_before = self.on_path_data().cloned();
+ // A distorted image's placement nearest its corners, before they are transformed (`None`
+ // within when its stored corners are refused, and `None` for anything else).
+ let image_before = self.extras().image_quad.is_some().then(|| crate::image_quad::nearest_affine(self));
if !self.is_layer() {
self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a);
}
@@ -637,7 +644,8 @@ impl Node {
{
Arc::make_mut(&mut m.art).transform_scaled(a, sc);
}
- // The area where an Intertwine member is drawn over the others moves with it.
+ // The area where an Intertwine member is drawn over the others moves with it, and so do a
+ // distorted image's corners.
if let Some(e) = self.extras_if_any() {
if let Some(area) = e.intertwine.as_mut() {
area.transform(a);
@@ -645,6 +653,23 @@ impl Node {
for area in &mut e.intertwine_tiers {
area.transform(a);
}
+ if let Some(q) = e.image_quad.as_mut() {
+ for p in q.iter_mut() {
+ *p = a * *p;
+ }
+ }
+ }
+ // Corners that a scale squeezes past what a perspective map can place (or that were
+ // refused already) leave the image placed by its transform: for valid corners, the
+ // placement that was nearest them, transformed, rather than the rectangle it had before
+ // it was distorted.
+ if let Some(before) = image_before
+ && self.image_quad().is_none()
+ {
+ if let (Some(near), NodeKind::Image(im)) = (before, &mut self.kind) {
+ im.xf = a * near;
+ }
+ self.extras_mut().image_quad = None;
}
}
diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs
index 2b473f0cc7..9027c80b09 100644
--- a/crates/doc/src/node/wire.rs
+++ b/crates/doc/src/node/wire.rs
@@ -59,6 +59,7 @@ impl Serialize for Node {
e.color_mask.is_none(),
is_default(&e.warp_piece),
is_default(&e.clip_pieces),
+ e.image_quad.is_none(),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -106,6 +107,7 @@ impl Serialize for Node {
field!("color_mask", &e.color_mask);
field!("warp_piece", &e.warp_piece);
field!("clip_pieces", &e.clip_pieces);
+ field!("image_quad", &e.image_quad);
st.end()
}
}
@@ -257,10 +259,55 @@ pub(super) struct NodeWire {
warp_piece: bool,
#[serde(default)]
clip_pieces: bool,
+ #[serde(default, deserialize_with = "image_corners")]
+ image_quad: Option>,
+}
+
+/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the
+/// image is then placed by its transform). At most five points of a longer list are kept while it
+/// is read.
+fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result>, D::Error> {
+ use vectorcraft_geom::Point;
+ struct Corners;
+ impl<'de> serde::de::Visitor<'de> for Corners {
+ type Value = Option>;
+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.write_str("a list of points")
+ }
+ fn visit_none(self) -> Result {
+ Ok(None)
+ }
+ fn visit_unit(self) -> Result {
+ Ok(None)
+ }
+ fn visit_some>(self, d: D) -> Result {
+ d.deserialize_seq(Corners)
+ }
+ fn visit_seq>(self, mut seq: A) -> Result {
+ let mut points = Vec::with_capacity(4);
+ while points.len() < 4
+ && let Some(p) = seq.next_element::()?
+ {
+ points.push(p);
+ }
+ // A fifth entry drops the field, so the rest is skipped without decoding it.
+ let mut extra = false;
+ while seq.next_element::()?.is_some() {
+ extra = true;
+ }
+ Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) })
+ }
+ }
+ d.deserialize_option(Corners)
}
impl From for Node {
fn from(w: NodeWire) -> Self {
+ // Corners an image cannot take are dropped, so a later transform cannot make them its own.
+ let image_quad = match &w.kind {
+ NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()),
+ _ => None,
+ };
let extras = NodeExtras {
mask: w.mask,
trace: w.trace,
@@ -289,6 +336,7 @@ impl From for Node {
color_mask: w.color_mask,
warp_piece: w.warp_piece,
clip_pieces: w.clip_pieces,
+ image_quad,
};
Node {
id: w.id,
diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs
index dcbcd87028..0801187b6d 100644
--- a/crates/doc/src/tests.rs
+++ b/crates/doc/src/tests.rs
@@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() {
assert!(!ids.contains(&a) && !ids.contains(&b));
}
+/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
+/// another document with the same id does not.
+#[test]
+fn reid_copies_the_set_density_of_the_documents_own_node() {
+ let (mut d, a, _) = doc_with_rects();
+ d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
+ let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
+ let own = d.node(a).cloned().unwrap();
+ let copy = d.reid(&own);
+ assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
+ let foreign = Node::group(a, vec![]);
+ let copy = d.reid(&foreign);
+ assert_eq!(density(&d, copy.id), None);
+}
+
+/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy
+/// recorded none, whatever [`Document::reid`] found for an identical node in the document.
+#[test]
+fn carry_set_densities_gives_the_densities_recorded_at_copy() {
+ let (mut d, a, b) = doc_with_rects();
+ d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
+ let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
+ let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap());
+ // Copy recorded nothing for `a`: the copy reid gave a density loses it.
+ let copy = d.reid(&na);
+ assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
+ d.carry_set_densities(&na, ©, &Default::default());
+ assert_eq!(density(&d, copy.id), None);
+ // Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7.
+ let g = d.alloc_id();
+ let group = Node::group(g, vec![Arc::new(nb)]);
+ let copy = d.reid(&group);
+ d.carry_set_densities(&group, ©, &[(b, serde_json::json!(7.0))].into_iter().collect());
+ let inner = copy.children().unwrap()[0].id;
+ assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0))));
+}
+
#[test]
fn setup_round_trips_and_old_files_load() {
let (mut d, _, _) = doc_with_rects();
diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs
index 746c0b69d5..c0e305aeeb 100644
--- a/crates/doc/src/text/object.rs
+++ b/crates/doc/src/text/object.rs
@@ -451,12 +451,25 @@ impl TextObject {
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
+ self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false)
+ }
+ /// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor
+ /// in document space, preserving the anchor kind. `independent` takes precedence, and at an
+ /// open end of the path, where no segment leaves the anchor on that side, the handle moves as
+ /// it would without `symmetric`. Both handles are edited in one reshape, using the same validated
+ /// document-to-text map.
+ pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
+ let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out));
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
+ if mirror {
+ let opposite = drawn.p - (pos - drawn.p);
+ if out { drawn.h_in = opposite } else { drawn.h_out = opposite }
+ }
*a = drawn.transform(to_text);
true
})
diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs
index 8e45364857..3f7c979e8b 100644
--- a/crates/effects/src/catalog.rs
+++ b/crates/effects/src/catalog.rs
@@ -111,6 +111,8 @@ fn lengths_of(id: &str) -> Lengths {
"sketch.tornEdges" => always(&["smoothness"]),
"sketch.waterPaper" => always(&["fiberLength"]),
TRAP => always(&["thickness", "precision"]),
+ // The Pathfinder Options' refit tolerance.
+ id if crate::takes_pathfinder_options(id) => always(&["precision"]),
RASTERIZE => always(&["addAround"]),
// The points one unit of the filter measures.
crate::SVG_FILTER => always(&["scale"]),
@@ -832,15 +834,11 @@ pub fn effect_catalog() -> Vec {
}
for (id, label, _) in PATHFINDER_EFFECTS {
if id == "pathfinder.softMix" {
- v.push(g(
- id,
- label,
- PATHFINDER,
- "{mixingRate?: 1..100 % (50)} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)",
- json!({"mixingRate": 50.0}),
- ));
+ v.push(g(id, label, PATHFINDER, crate::group::SOFT_MIX_PARAMS_DOC, json!({"mixingRate": 50.0})));
} else {
- v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({})));
+ // No dialog defaults, so the Effect menu applies it directly; effect.apply fills its
+ // Pathfinder Options in.
+ v.push(g(id, label, PATHFINDER, crate::group::PATHFINDER_PARAMS_DOC, json!({})));
}
}
v.extend(crate::addons::color::catalog());
diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs
index a6f5af916b..aeffaacfb6 100644
--- a/crates/effects/src/group.rs
+++ b/crates/effects/src/group.rs
@@ -51,6 +51,80 @@ fn op_of(id: &str) -> Option {
PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2)
}
+/// Does effect `id` keep Pathfinder Options of its own ([`PathfinderEffectOptions`]): one of
+/// [`PATHFINDER_EFFECTS`] (Trap has options of its own)?
+pub fn takes_pathfinder_options(id: &str) -> bool {
+ op_of(id).is_some()
+}
+
+/// The parameters holding a Pathfinder effect's Pathfinder Options.
+pub const PATHFINDER_OPTION_KEYS: [&str; 3] = ["precision", "removeRedundantPoints", "removeUnpainted"];
+
+/// The range of a Pathfinder effect's `precision` (pt), the Pathfinder panel's range.
+pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive = 0.001..=10.0;
+
+/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`.
+macro_rules! options_doc {
+ () => {
+ "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
+ };
+}
+
+/// The documentation of [`PATHFINDER_OPTION_KEYS`], shared by the Pathfinder effects' parameters.
+pub const PATHFINDER_OPTIONS_DOC: &str = options_doc!();
+
+/// The parameters of a Pathfinder effect other than Soft Mix.
+pub const PATHFINDER_PARAMS_DOC: &str = concat!("{", options_doc!(), "} (groups and layers: live Pathfinder over the members)");
+
+/// The parameters of Effect › Pathfinder › Soft Mix.
+pub const SOFT_MIX_PARAMS_DOC: &str = concat!(
+ "{mixingRate?: 1..100 % (50), ",
+ options_doc!(),
+ "} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)"
+);
+
+/// The Pathfinder Options a Pathfinder effect evaluates with, read from its parameters. An effect
+/// without them (saved before effects kept their own) evaluates as it did then: the default
+/// precision, with no points or pieces removed.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PathfinderEffectOptions {
+ /// Refit tolerance of the results, in points ([`PATHFINDER_EFFECT_PRECISION`]).
+ pub precision: f64,
+ /// Drop anchors that don't change a result's shape.
+ pub remove_redundant_points: bool,
+ /// Divide and Outline leave out the pieces of members with no visible fill.
+ pub remove_unpainted: bool,
+}
+
+impl Default for PathfinderEffectOptions {
+ fn default() -> Self {
+ PathfinderEffectOptions { precision: po::DEFAULT_PRECISION, remove_redundant_points: false, remove_unpainted: false }
+ }
+}
+
+impl PathfinderEffectOptions {
+ /// The options in `p`: a missing or non-numeric value takes its default and a precision out of
+ /// range its nearest bound, so a live effect always evaluates.
+ pub fn from_params(p: &Value) -> Self {
+ let d = PathfinderEffectOptions::default();
+ let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end());
+ PathfinderEffectOptions {
+ precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi),
+ remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points),
+ remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted),
+ }
+ }
+
+ /// These options as the parameters [`PATHFINDER_OPTION_KEYS`] name.
+ pub fn to_params(self) -> Value {
+ serde_json::json!({
+ "precision": self.precision,
+ "removeRedundantPoints": self.remove_redundant_points,
+ "removeUnpainted": self.remove_unpainted,
+ })
+ }
+}
+
/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape?
pub fn has_pathfinder(n: &Node) -> bool {
n.is_compound_shape()
@@ -503,6 +577,23 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option Option {
+ let a = area_style.as_ref().filter(|_| s.id == group.id && s.appearance.items.is_empty())?;
+ let mut a = a.clone();
+ (a.opacity, a.blend) = (s.opacity, s.blend);
+ Some(a)
+ };
let mut stack: Vec> = if group.is_compound_shape() {
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
match compound_shape_area(doc, group, hook) {
@@ -535,6 +626,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option, group: &Node, hook: Option = parts.iter().map(|(p, r)| (p, *r)).collect();
let key = sources.len() as u64;
if let Some(top) = lv.pop() {
- shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, key));
+ shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key));
sources.push(top);
}
} else {
@@ -574,24 +666,40 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option !own_fill,
+ PathfinderOp::Outline => true,
+ _ => false,
+ };
+ let fill_sources: Vec> = sources.iter().map(style_of).collect();
+ let fill_source = |k: u64| fill_sources[k as usize].as_ref().unwrap_or(&sources[k as usize]);
+ po::pathfinder_with(op, &shapes, options.precision)
.into_iter()
- .filter(|r| !r.path.is_empty())
- .map(|r| Arc::new(styled(&sources[r.key as usize], r.path, op == PathfinderOp::Outline)))
+ .filter(|r| !r.path.is_empty() && !(unpainted && !has_visible_fill(fill_source(r.key))))
+ .map(|r| {
+ let outline = op == PathfinderOp::Outline;
+ let src = if outline { fill_source(r.key) } else { &sources[r.key as usize] };
+ Arc::new(styled(src, tidy(r.path), outline))
+ })
.collect()
};
}
@@ -676,6 +784,11 @@ pub fn paints(item: &AppearanceItem) -> bool {
}
}
+/// Has `n` a visible fill that paints, as the Pathfinder panel's Remove Unpainted Artwork counts it?
+fn has_visible_fill(n: &Node) -> bool {
+ n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()))
+}
+
/// Do the own fills or strokes of `n`, a group or layer, paint anything?
pub(crate) fn has_own_paint(n: &Node) -> bool {
is_container(n) && n.appearance.items.iter().any(paints)
diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs
index 3b8addadea..1c62508347 100644
--- a/crates/effects/src/group/tests.rs
+++ b/crates/effects/src/group/tests.rs
@@ -213,6 +213,81 @@ fn divide_and_outline_draw_nothing_for_unpainted_members() {
}
}
+/// With Remove Unpainted Artwork, Divide and Outline keep the area of a compound shape whose own
+/// appearance has a visible fill and leave out the area of one without.
+#[test]
+fn remove_unpainted_keeps_a_filled_compound_shapes_area() {
+ for effect in ["pathfinder.divide", "pathfinder.outline"] {
+ for filled in [true, false] {
+ let mut g = compound_shape(ShapeMode::Add);
+ if !filled {
+ g.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
+ }
+ g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true });
+ let out = pathfinder_children(None, &g, None).unwrap();
+ assert_eq!(!out.is_empty(), filled, "{effect}, filled {filled}: {out:#?}");
+ }
+ }
+}
+
+/// Outline strokes a compound shape's area in the shape's own fill (its top visible one that
+/// paints), with Remove Unpainted Artwork on or off, and Divide leaves the area's pieces
+/// unpainted for the shape's fill to paint.
+#[test]
+fn outline_strokes_a_compound_shapes_area_in_its_fill() {
+ let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0));
+ for (remove, covered) in [(false, false), (true, false), (false, true), (true, true)] {
+ for effect in ["pathfinder.divide", "pathfinder.outline"] {
+ let mut g = compound_shape(ShapeMode::Add);
+ if covered {
+ // A hidden fill and an unpainted fill above the green one.
+ let mut hidden = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
+ hidden.visible = false;
+ let mut a = (*g.appearance).clone();
+ a.insert_item(a.items.len(), AppearanceItem::Fill(hidden));
+ a.insert_item(a.items.len(), AppearanceItem::Fill(FillLayer::new(Paint::None)));
+ g.appearance = a.into();
+ }
+ g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": remove}), visible: true });
+ let out = pathfinder_children(None, &g, None).unwrap();
+ assert!(!out.is_empty(), "{effect}, remove {remove}");
+ for n in &out {
+ if effect == "pathfinder.outline" {
+ assert_eq!(n.appearance.stroke_paint(), green, "{effect}, remove {remove}: {n:#?}");
+ assert!(n.appearance.fill_paint().is_none(), "{effect}, remove {remove}: {n:#?}");
+ } else {
+ assert!(n.appearance.items.is_empty(), "{effect}, remove {remove}: {n:#?}");
+ }
+ }
+ }
+ }
+}
+
+/// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's
+/// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out
+/// the member's segments either way.
+#[test]
+fn remove_unpainted_keeps_members_a_groups_own_fill_paints() {
+ let unfilled = Arc::new(Node::path(
+ NodeId(2),
+ shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)),
+ Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0),
+ ));
+ for effect in ["pathfinder.divide", "pathfinder.outline"] {
+ for filled in [true, false] {
+ let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unfilled.clone()]);
+ if filled {
+ g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into();
+ }
+ g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true });
+ let out = pathfinder_children(None, &g, None).unwrap();
+ assert!(out.iter().any(|n| n.id == NodeId(1)), "{effect}, filled {filled}: {out:#?}");
+ let kept = filled && effect == "pathfinder.divide";
+ assert_eq!(out.iter().any(|n| n.id == NodeId(2)), kept, "{effect}, filled {filled}: {out:#?}");
+ }
+ }
+}
+
/// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either
/// side of x = 100.
fn type_h() -> Node {
diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs
index fff4705333..574097624a 100644
--- a/crates/effects/src/lib.rs
+++ b/crates/effects/src/lib.rs
@@ -75,8 +75,9 @@ pub use bake::{
};
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
pub use group::{
- OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
- is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
+ OutlineHook, PATHFINDER_EFFECT_PRECISION, PATHFINDER_EFFECTS, PATHFINDER_OPTION_KEYS, PATHFINDER_OPTIONS_DOC, PathfinderEffectOptions,
+ compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves,
+ member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, takes_pathfinder_options,
};
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs
index 1e3c8c1d31..ab588838a6 100644
--- a/crates/effects/src/params.rs
+++ b/crates/effects/src/params.rs
@@ -120,7 +120,10 @@ pub fn new_effect(id: &str, params: &Value) -> Option {
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
/// keep their share of the object so. A distance left at its default is written out scaled; one
-/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
+/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. A Pathfinder
+/// effect without a `precision` gets the precision it evaluates with, scaled. Values are scaled
+/// as stored, out of range or not, so a scale and its inverse restore them; evaluation applies
+/// each effect's range.
pub fn scale_effect(e: &mut Effect, s: f64) {
let Some(info) = catalog_index().get(e.id.as_str()) else { return };
let merged = merged_params(&e.id, &e.params);
@@ -128,7 +131,9 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
for k in keys {
- let v = util::num(&merged, k, f64::NAN);
+ let missing =
+ if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN };
+ let v = util::num(&merged, k, missing);
if v.is_finite() {
if !e.params.is_object() {
e.params = Value::Object(Map::new());
diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs
index 85c36f2d89..a57c2085f6 100644
--- a/crates/effects/src/reshape.rs
+++ b/crates/effects/src/reshape.rs
@@ -1248,15 +1248,20 @@ fn as_art_opts(
let fx = geometry_effects(n);
let mut art = match &n.kind {
NodeKind::Image(im) => {
- let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
+ // A distorted image's frame joins its corners.
+ let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
+ Some(bp) => PathData::from_bezpath(&bp),
+ None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
+ };
let mut image = Node::new(n.id, n.kind.clone());
// Its pixels draw as the image's do: colorized by a grayscale image's fill color,
- // smoothed or not, and with its color mask's masked pixels.
+ // smoothed or not, with its color mask's masked pixels, and distorted.
{
let mut e = image.extras_mut();
e.colorize = n.extras().colorize.clone();
e.pixelated = n.extras().pixelated;
e.color_mask = n.extras().color_mask.clone();
+ e.image_quad = n.extras().image_quad.clone();
}
let clipped = || {
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
@@ -1276,6 +1281,17 @@ fn as_art_opts(
clipped()
} else {
let opaque = std::cell::OnceCell::new();
+ // A distorted image's opaque area, traced in its pixels, goes to the page through
+ // its projective map.
+ let opaque_on_page = || match n.image_map().filter(|_| n.is_distorted_image()) {
+ Some(map) => {
+ let plain = ImageObject { xf: Affine::IDENTITY, ..(**im).clone() };
+ let piece = f64::from(im.width.max(im.height).max(1)) / 64.0;
+ opaque_area(&[symbols, paint_doc], &plain)
+ .map(|p| vectorcraft_doc::live::map_nonlinear(&p, piece, |q| map.apply(q).unwrap_or(q)))
+ }
+ None => opaque_area(&[symbols, paint_doc], im),
+ };
let rows = |items: Vec| {
let mut out = vec![];
let mut items = items.into_iter().peekable();
@@ -1285,7 +1301,7 @@ fn as_art_opts(
while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) {
run.push(next);
}
- let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None };
+ let path = if follows { opaque.get_or_init(opaque_on_page).as_ref() } else { None };
let path = path.unwrap_or(&frame);
if !path.is_empty() {
out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() })));
@@ -3718,8 +3734,21 @@ fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) {
// The pieces start from the image as it was placed when it took its first warp.
let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() });
let map = warped_map(warps, own.xf);
+ // A placement with no inverse cannot take a distorted image's corners back.
+ let det = own.xf.determinant();
+ let back = warps.first().filter(|_| det.is_finite() && det != 0.0).map(|(_, at)| *at * own.xf.inverse()).filter(Affine::is_finite);
+ let distorted = image.extras().image_quad.is_some();
*c = Arc::new(match (first, map) {
- (Some(first), Some(map)) if cut => {
+ (Some(first), Some(map)) if cut && (back.is_some() || !distorted) => {
+ // A distorted image's corners go back to where they stood at its first warp, as
+ // its placement does: the moves since then are in `map`.
+ if let Some(back) = back
+ && let Some(q) = image.extras_if_any().and_then(|e| e.image_quad.as_mut())
+ {
+ for p in q.iter_mut() {
+ *p = back * *p;
+ }
+ }
let pixelated = image.extras().pixelated;
vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false)
}
@@ -3787,6 +3816,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc:
NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at,
_ => {}
}
+ // A distorted image's corners move with it.
+ if let Some(q) = one.extras_if_any().and_then(|e| e.image_quad.as_mut()) {
+ for p in q.iter_mut() {
+ *p = xf * *p;
+ }
+ }
// The placed gradients of its own fills and strokes move with it, as a path's do.
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
one.appearance.transform_gradients(xf);
diff --git a/crates/effects/src/solids/source.rs b/crates/effects/src/solids/source.rs
index d71b2993af..b789a05782 100644
--- a/crates/effects/src/solids/source.rs
+++ b/crates/effects/src/solids/source.rs
@@ -8,7 +8,7 @@ use std::borrow::Cow;
use std::sync::Arc;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
-use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
+use vectorcraft_geom::{FillRule, PathData, Rect, SubPath};
use vectorcraft_pathops as po;
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
@@ -144,18 +144,17 @@ impl Resolver<'_> {
}
/// Does the plain image `c` lie wholly outside what the clips around it show together, each
- /// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places
- /// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts
- /// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
+ /// clipping path with its own fill rule? Its frame, the quadrilateral of its corners
+ /// ([`Node::image_corners`]: a distorted image's corners, else the pixel rectangle as its
+ /// transform places it), is cut to each clip in turn until nothing is left. An error when a
+ /// cut fails or the cuts pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
fn hidden(&mut self, c: &Node) -> Result {
let Some(shown) = &self.shown else { return Ok(false) };
- let NodeKind::Image(im) = &c.kind else { return Ok(false) };
+ let Some(corners) = c.image_corners() else { return Ok(false) };
let Some(b) = c.visual_bounds() else { return Ok(true) };
if b.intersect(shown.bounds).area() <= 0.0 {
return Ok(true);
}
- let (w, h) = (f64::from(im.width), f64::from(im.height));
- let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y));
if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return Err(image_refusal(self.label));
}
diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs
index 2a34fb1d07..348d21ba38 100644
--- a/crates/effects/src/tests.rs
+++ b/crates/effects/src/tests.rs
@@ -504,6 +504,38 @@ fn warped_images_keep_document_keys_and_hidden_images_apart() {
}
}
+/// A distorted image that a later effect leaves with no area after its warp is not cut, and its
+/// corners stay finite.
+#[test]
+fn a_distorted_image_left_with_no_area_after_its_warp_keeps_finite_corners() {
+ use std::rc::Rc;
+ use std::sync::Arc;
+
+ use vectorcraft_doc::NodeId;
+ let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1));
+ let mut image = (*warp_test_image(2)).clone();
+ image.set_image_corners([(10.0, 0.0), (30.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y))).unwrap();
+ let mut art = Node::group(NodeId(1), vec![Arc::new(image)]);
+ let mut warped = crate::reshape::WarpedImages::new();
+ warped.reserve(&art);
+ crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::new(), false, &mut 0, &mut warped);
+ // A later effect squeezes the placement flat.
+ if let Some(c) = art.children_mut()
+ && let NodeKind::Image(im) = &mut Arc::make_mut(&mut c[0]).kind
+ {
+ im.xf = Affine::scale_non_uniform(1.0, 0.0);
+ }
+ crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
+ let mut finite = true;
+ art.walk(&mut |c| {
+ if let Some(q) = c.extras().image_quad.as_deref() {
+ finite &= q.iter().all(|p| p.x.is_finite() && p.y.is_finite());
+ }
+ });
+ assert!(finite);
+ assert_eq!(warp_test_images(&art).0, 1, "not cut");
+}
+
/// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its
/// pixels as they are; within the budget, both bend.
#[test]
@@ -2121,3 +2153,27 @@ fn color_halftones_radius_is_in_raster_pixels_not_a_distance() {
crate::scale_effect(&mut e, 2.0);
assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0)));
}
+
+#[test]
+fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() {
+ for (id, _, _) in PATHFINDER_EFFECTS {
+ assert!(is_length(id, "precision", false), "{id}");
+ assert_eq!(length_range(id, "precision"), Some(PATHFINDER_EFFECT_PRECISION), "{id}");
+ assert!(!is_length(id, "removeRedundantPoints", false) && !is_length(id, "removeUnpainted", false), "{id}");
+ // Scale Strokes & Effects scales the tolerance with the geometry it is refit to.
+ let mut e = crate::new_effect(id, &json!({"precision": 0.5, "removeUnpainted": true})).unwrap();
+ crate::scale_effect(&mut e, 4.0);
+ assert_eq!(e.params["precision"].as_f64(), Some(2.0), "{id}");
+ assert_eq!(e.params["removeUnpainted"], json!(true), "{id}");
+ // An effect saved without the options scales the precision it evaluates with.
+ let mut e = crate::new_effect(id, &json!({})).unwrap();
+ crate::scale_effect(&mut e, 3.0);
+ let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN);
+ assert!((scaled - PathfinderEffectOptions::default().precision * 3.0).abs() < 1e-12, "{id}: {scaled}");
+ // A scale past the range and its inverse restore the precision, as with other distances.
+ let mut e = crate::new_effect(id, &json!({"precision": 8.0})).unwrap();
+ crate::scale_effect(&mut e, 2.0);
+ crate::scale_effect(&mut e, 0.5);
+ assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}");
+ }
+}
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index 9a1531ede9..c012e1cc3f 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -890,6 +890,9 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
/// Pathfinder Options (`Prefs::pathfinder`).
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
+/// The Pathfinder Options a new Pathfinder effect takes (`effect.apply`).
+pub use effectcmd::pathfinder_effect_options;
+
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
pub use attributes::RECENT_URLS;
pub use overprint::AttributesInfo;
diff --git a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs
index 0db89fb2ee..cb2c1c071d 100644
--- a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs
+++ b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs
@@ -109,11 +109,11 @@ impl<'a> Reader<'a> {
Ok(union(parts))
}
}
- NodeKind::Image(im) => {
- let (w, h) = (f64::from(im.width), f64::from(im.height));
- let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p);
- self.polygon(&corners)
- }
+ // A distorted image's frame joins its corners.
+ NodeKind::Image(_) => match n.image_corners() {
+ Some(corners) => self.polygon(&corners),
+ None => Ok(None),
+ },
// An instance of a symbol the document doesn't have draws nothing.
NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) {
Some(art) => self.node(&art, depth + 1),
diff --git a/crates/engine/src/cmd/addons/cutting/weed/tests.rs b/crates/engine/src/cmd/addons/cutting/weed/tests.rs
index 69114f8991..4af36f30ee 100644
--- a/crates/engine/src/cmd/addons/cutting/weed/tests.rs
+++ b/crates/engine/src/cmd/addons/cutting/weed/tests.rs
@@ -663,6 +663,29 @@ fn an_image_is_measured_by_its_frame_as_turned() {
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
}
+#[test]
+fn a_distorted_image_is_measured_by_the_frame_through_its_corners() {
+ let mut s = session();
+ let im = vectorcraft_doc::ImageObject {
+ key: "image".into(),
+ width: 100,
+ height: 100,
+ xf: Affine::IDENTITY,
+ link: None,
+ placement: Default::default(),
+ pixels: None,
+ };
+ insert(&mut s, |id| {
+ let mut n = Node::new(id, NodeKind::Image(Box::new(im)));
+ n.set_image_corners([Point::new(40.0, 0.0), Point::new(60.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]).unwrap();
+ n
+ });
+ let (b, end) = diamond_weeding(&mut s);
+ assert!((b.x0 + 10.0).abs() < 1e-3 && (b.y1 - 110.0).abs() < 1e-3, "{b:?}");
+ // A quarter of the box down (y = 20), the line meets the side from (40, 0) to (0, 100).
+ assert!((end - 32.0).abs() < 0.01, "{end}");
+}
+
#[test]
fn a_placed_file_is_measured_by_the_art_it_shows() {
let dir = crate::tests_links::Folder::new("weed-placed");
diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs
index 48c78f3839..bef56dfd94 100644
--- a/crates/engine/src/cmd/brushlib.rs
+++ b/crates/engine/src/cmd/brushlib.rs
@@ -175,7 +175,9 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
+ BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
+ BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
@@ -185,6 +187,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
+ BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic },
];
/// Built-in library `id`, made once.
@@ -238,6 +241,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
+/// Artistic: four original vector compositions that stretch along a path and take its color.
+fn artistic() -> BrushLibrary {
+ let orbit = group(vec![
+ black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
+ black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
+ ]);
+ let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))];
+ for i in 0..6 {
+ let x = 9.0 + 16.0 * i as f64;
+ let side = if i % 2 == 0 { 1.0 } else { -1.0 };
+ petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)])));
+ }
+ let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))];
+ for i in 0..5 {
+ let x = 20.0 * i as f64;
+ lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)])));
+ lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)])));
+ }
+ let mut facets = Vec::new();
+ for i in 0..8 {
+ let x = 12.5 * i as f64;
+ let high = if i % 2 == 0 { 6.0 } else { 3.5 };
+ facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)])));
+ }
+ built(
+ "Artistic Brushes",
+ Document::new(100.0, 100.0),
+ vec![
+ art("Orbit Lines", orbit, Colorization::Tints),
+ art("Petal Garland", group(petals), Colorization::Tints),
+ art("Lattice Braid", group(lattice), Colorization::Tints),
+ art("Facet Sweep", group(facets), Colorization::Tints),
+ ],
+ )
+}
+
/// Original fine-line art for an engraving-style brush library.
fn engraving() -> BrushLibrary {
let lines = |count: usize, width: f64, spacing: f64| {
@@ -594,6 +633,45 @@ fn spacer(r: Rect) -> Node {
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
}
+/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one
+/// stroke stretched along the path, with an intentionally different edge and paint distribution.
+fn paint() -> BrushLibrary {
+ let flat_sweep = group(vec![
+ black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())),
+ black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])),
+ black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])),
+ ]);
+ let mut dry_drag = vec![];
+ for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] {
+ dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8))));
+ dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8))));
+ dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8))));
+ }
+ let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))];
+ for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] {
+ loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5))));
+ }
+ let mut fan_sweep = vec![];
+ for i in -2..=2 {
+ let offset = i as f64;
+ fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin())));
+ }
+ let paint_art = |name: &str, art: Node| Brush {
+ name: name.into(),
+ kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }),
+ };
+ built(
+ "Paint",
+ Document::new(100.0, 100.0),
+ vec![
+ paint_art("Flat Sweep", flat_sweep),
+ paint_art("Dry Drag", group(dry_drag)),
+ paint_art("Loaded Stroke", group(loaded_stroke)),
+ paint_art("Fan Sweep", group(fan_sweep)),
+ ],
+ )
+}
+
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
fn pattern_borders() -> BrushLibrary {
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
@@ -613,6 +691,47 @@ fn pattern_borders() -> BrushLibrary {
built("Pattern Borders", Document::new(100.0, 100.0), brushes)
}
+/// Decorative: repeating plant, flower and hanging ornaments drawn as original vector tiles.
+/// Every tile joins the next at x = 0 and 48 so open and closed paths stay continuous.
+fn decorative() -> BrushLibrary {
+ let stem = || black(shapes::rectangle(Rect::new(0.0, -0.65, 48.0, 0.65)));
+ let vine = group(vec![
+ stem(),
+ black(polygon(&[(8.0, -0.2), (12.0, -5.0), (24.0, -8.0), (20.0, -1.0)])),
+ black(polygon(&[(28.0, 0.2), (32.0, 5.0), (44.0, 8.0), (40.0, 1.0)])),
+ ]);
+ let mut blossoms = vec![stem()];
+ for x in [12.0, 36.0] {
+ for (dx, dy) in [(0.0, -4.0), (4.0, 0.0), (0.0, 4.0), (-4.0, 0.0)] {
+ blossoms.push(black(shapes::ellipse(Rect::new(x + dx - 2.5, dy - 2.5, x + dx + 2.5, dy + 2.5))));
+ }
+ blossoms.push(black(shapes::ellipse(Rect::new(x - 1.3, -1.3, x + 1.3, 1.3))));
+ }
+ let flowers = group(blossoms);
+ let pennants = group(vec![
+ black(shapes::rectangle(Rect::new(0.0, -5.2, 48.0, -4.2))),
+ black(polygon(&[(4.0, -4.2), (20.0, -4.2), (12.0, 10.0)])),
+ black(polygon(&[(28.0, -4.2), (44.0, -4.2), (36.0, 10.0)])),
+ ]);
+ let lanterns = group(vec![
+ black(shapes::rectangle(Rect::new(0.0, -5.0, 48.0, -4.0))),
+ black(shapes::rectangle(Rect::new(11.4, -4.0, 12.6, -1.0))),
+ black(shapes::ellipse(Rect::new(7.0, -1.0, 17.0, 9.0))),
+ black(shapes::rectangle(Rect::new(35.4, -4.0, 36.6, -1.0))),
+ black(shapes::ellipse(Rect::new(31.0, -1.0, 41.0, 9.0))),
+ ]);
+ built(
+ "Decorative",
+ Document::new(100.0, 100.0),
+ vec![
+ border("Leaf Vine", vine, None, PatternFit::Stretch),
+ border("Blossom Chain", flowers, None, PatternFit::Stretch),
+ border("Pennant Garland", pennants, None, PatternFit::Stretch),
+ border("Lantern String", lanterns, None, PatternFit::Stretch),
+ ],
+ )
+}
+
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
}
@@ -1036,10 +1155,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc
return Some(found);
}
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
- return Some((builtin_info(b), builtin_library(key)?));
+ return Some((builtin_info(b), builtin_library(b.id)?));
}
- let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
- library(s, &id)
+ if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) {
+ return library(s, &id);
+ }
+ // Keep the short built-in alias, but let a user or loaded library own its display name.
+ let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?;
+ Some((builtin_info(b), builtin_library(b.id)?))
}
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc)> {
diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs
index 6c0f651c00..fbd4512fa3 100644
--- a/crates/engine/src/cmd/brushsym.rs
+++ b/crates/engine/src/cmd/brushsym.rs
@@ -362,7 +362,7 @@ pub fn specs() -> Vec {
"Symbol Sprayer",
[],
None,
- "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
+ "{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
has_doc,
symbol_spray
),
@@ -380,7 +380,7 @@ pub fn specs() -> Vec {
"Symbolism Tool",
[],
None,
- "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error",
+ "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error",
has_doc,
symbol_adjust
),
diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs
index 0199b7b13d..21fe71a644 100644
--- a/crates/engine/src/cmd/brushsym/symbolism.rs
+++ b/crates/engine/src/cmd/brushsym/symbolism.rs
@@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 {
}
/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written
-/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it.
-const SET_DENSITY_KEY: &str = "symbolSetDensity";
+/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a
+/// copy of a set by [`Document::reid`].
+const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY;
/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded).
fn set_density_of(d: &Document, set: NodeId) -> Option {
@@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option {
cos += l.angle.cos();
opacity += l.opacity;
middle += l.center.to_vec2();
- if let Some((p, o)) = &l.fill {
+ // A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken.
+ if let Some((p, o)) = &l.fill
+ && *o > 0.0
+ {
amount += o;
let far = l.center.distance(at);
if paint.is_none_or(|(_, nearest)| far < nearest) {
diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs
index 6f1b96b52f..14e52ffe4f 100644
--- a/crates/engine/src/cmd/brushsym/symbols.rs
+++ b/crates/engine/src/cmd/brushsym/symbols.rs
@@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec {
v
}
+/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in
+/// turn first reaches them.
+fn instances_in<'a>(nodes: impl IntoIterator- ) -> Vec
{
+ let (mut v, mut seen) = (vec![], std::collections::HashSet::new());
+ for n in nodes {
+ n.walk(&mut |c| {
+ if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) {
+ v.push(c.id);
+ }
+ });
+ }
+ v
+}
+
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
fn art_symbols(n: &Node, out: &mut Vec) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
@@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result> {
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
let mut v = Vec::with_capacity(a.len());
for q in a {
- let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
+ // The pressure is checked first: a point skipped for its coordinates still has a bad one refused.
let pressure = match q.get(2) {
None | Some(Value::Null) => 1.0,
Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?,
};
+ let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
v.push((Point::new(x, y), pressure.clamp(0.0, 1.0)));
}
if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) {
@@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result> {
Ok(v)
}
-/// The fill of the graphic style `p` names with `style`, else of the document's first style after
-/// the default one.
+/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no
+/// style for, such as the Symbol Styler's style from another document) of the document's first
+/// style after the default one.
fn style_paint(d: &Document, p: &Value) -> Option {
- match str_param(p, "style") {
- Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
- None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
- }
+ str_param(p, "style")
+ .and_then(|n| d.graphic_styles.iter().find(|g| g.name == n))
+ .or(d.graphic_styles.get(1))
+ .or(d.graphic_styles.first())
+ .map(|g| g.appearance.fill_paint())
}
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
@@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result {
}
let style = style_paint(&st.doc, p);
// Style: User Defined uses the style `style` names, so one the document does not have is an error.
- if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) {
+ if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) {
return Err(bad(C, format!("unknown graphic style `{n}`")));
}
let size = natural_size(&st.doc, &name);
@@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
let use_pressure = switch_or(p, "usePressure", false, C)?;
let proportional = switch_or(p, "proportional", true, C)?;
let affects_density = switch_or(p, "affectsDensity", false, C)?;
+ let shift = switch_or(p, "shift", false, C)?;
// The Symbol Shifter has no Method.
let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? };
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
@@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
let style_paint = style_paint(&st.doc, p);
let candidates: Vec = {
let d = &st.doc;
- let mut v = vec![];
- if st.selection.is_empty() {
- v = instances_of(d, None);
- } else {
- for id in &st.selection.objects {
- if let Some(n) = d.node(*id) {
- n.walk(&mut |c| {
- if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) {
- v.push(c.id);
- }
- });
- }
- }
- }
+ let mut v =
+ if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) };
let editable = d.editable();
v.retain(|id| editable(*id));
v
@@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
// for the whole stroke (and for every preview of it).
let first = pts.first().map_or(Point::ZERO, |(q, _)| *q);
let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 };
+ // Shift with the Symbol Shifter: the instances under the brush come one place forward among
+ // their siblings (with `alt`, go one place backward), once for the whole stroke.
+ if tool == "shift" && shift {
+ let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| {
+ let under: std::collections::HashSet = candidates
+ .iter()
+ .copied()
+ .filter(|id| {
+ d.node(*id).and_then(instance_center).is_some_and(|c| {
+ pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius)
+ })
+ })
+ .collect();
+ let moved = restack(d, &under, alt)?;
+ Ok((moved, moved > 0))
+ })?;
+ return Ok(json!({ "count": count }));
+ }
+ // Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style
+ // moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer
+ // keeps the instances where they are, Resizing Affects Density included.
+ let recolor = match tool.as_str() {
+ "stain" if shift => Some((Paint::solid(color), 0.15)),
+ "style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)),
+ _ => None,
+ };
+ let spread = affects_density && !shift;
// No undo step when no instance changes (none under the brush, or Average with each at the mean).
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| {
let mut touched = std::collections::BTreeSet::new();
let mut sides = Sides::new();
for (j, (q, pressure)) in pts.iter().enumerate() {
- let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO };
+ let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev);
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
let strength = if use_pressure { *pressure } else { intensity };
// Average: the mean of the instances under the brush, as they are at this point.
@@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
if w <= 0.0 {
continue;
}
+ // Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount
+ // of its stain or style, and its paint moves toward the color or the style. An
+ // instance without one, or without a size, is left as it is.
+ if let Some((to, step)) = &recolor {
+ let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill);
+ touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id));
+ continue;
+ }
// Average needs the instance's own values, so it leaves an instance without a size
// as it is; the other methods change it as before.
// The instance's own values are read for Average only.
@@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
};
n.transform(about(Affine::scale_non_uniform(kx, ky)), false);
// Resizing Affects Density: instances move away from the brush's center as
- // they grow and toward it as they shrink.
- if affects_density {
+ // they grow and toward it as they shrink. Shift keeps the instances where
+ // they are, so the set's density stays as it was.
+ if spread {
n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false);
}
}
@@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
"stain" | "style" => {
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
let (paint, o) = match &avg {
- // Toward the mean amount, keeping the stain or style the instance has.
+ // Toward the mean amount, keeping the stain or style the instance has
+ // (one at no opacity is none).
Some((t, look)) => {
- let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o));
+ let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o));
(own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32)
}
// Alt with the Symbol Styler removes the instance's appearance.
@@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
}
None => {
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
+ // The style goes on gradually, by the brush's strength there: in
+ // full at the center at full intensity or pressure.
let step = match (tool.as_str(), method) {
- // Random: the instance's share of the style, scaled by the
- // brush strength there.
- ("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32,
- ("style", _) => 1.0,
+ ("style", Method::Random) => (w * share / 2.0) as f32,
+ ("style", _) => w as f32,
_ => (0.15 * w * share) as f32,
};
(paint, if alt { cur - step } else { cur + step })
@@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result {
}
}
}
- // An instance the stroke moved away and back again is not counted.
+ // An instance the stroke moved away and back again, or reached but left as it was (at a
+ // limit already), is not counted.
touched.retain(|id| d.node(*id) != orig.node(*id));
Ok((touched.len(), !touched.is_empty()))
})?;
Ok(json!({ "count": count }))
}
+
+/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount)
+/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's
+/// other appearance items stay as they are. A paint with no form between it and `to` (a solid
+/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still
+/// reach it. An instance without a stain or style, or one whose paint does not change, is left as
+/// it is. Returns whether it changed.
+fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool {
+ use vectorcraft_doc::blend::lerp_paint;
+ let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false };
+ let t = t.clamp(0.0, 1.0) as f32;
+ let mut paint = lerp_paint(&own, to, t);
+ // `lerp_paint` switches such a pair halfway, so just below half it still gives `own`.
+ if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own {
+ paint = to.clone();
+ }
+ if paint == own {
+ return false;
+ }
+ let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false };
+ f.paint = paint;
+ true
+}
+
+/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them
+/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and
+/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how
+/// many moved.
+fn restack(d: &mut Document, ids: &std::collections::HashSet, back: bool) -> Result {
+ let parents: std::collections::BTreeSet> = ids.iter().map(|id| d.parent_of(*id)).collect();
+ let mut moved = 0;
+ for par in parents {
+ let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
+ let ch = d.children_mut(par)?;
+ let len = Node::guide_run_start(ch);
+ if len <= floor + 1 {
+ continue;
+ }
+ let picked = |n: &Arc| ids.contains(&n.id);
+ if back {
+ for i in floor + 1..len {
+ if picked(&ch[i]) && !picked(&ch[i - 1]) {
+ ch.swap(i - 1, i);
+ moved += 1;
+ }
+ }
+ } else {
+ for i in (floor..len - 1).rev() {
+ if picked(&ch[i]) && !picked(&ch[i + 1]) {
+ ch.swap(i, i + 1);
+ moved += 1;
+ }
+ }
+ }
+ }
+ Ok(moved)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn instance(id: u64) -> Arc {
+ Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }))
+ }
+
+ /// The instances come out in the order a search of the list built so far gives: nested
+ /// groups, a group listed twice, a member listed after its group and one listed before it.
+ #[test]
+ fn instances_in_matches_searching_the_list_so_far() {
+ let groups: Vec = (0..40u64)
+ .map(|g| {
+ let base = g * 100;
+ let mut children: Vec> = (0..40).map(|i| instance(base + i)).collect();
+ let inner = (40..50).map(|i| instance(base + i)).collect();
+ children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner)));
+ children.push(Arc::new(Node::group(NodeId(base + 91), vec![])));
+ Node::group(NodeId(base + 99), children)
+ })
+ .collect();
+ let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
+ let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
+ let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect();
+ let mut searched = vec![];
+ for n in &nodes {
+ n.walk(&mut |c| {
+ if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) {
+ searched.push(c.id);
+ }
+ });
+ }
+ let found = instances_in(nodes.iter().copied());
+ assert_eq!(found, searched);
+ assert_eq!(found.len(), 2_000);
+ assert_eq!(found[0], NodeId(1_245));
+ assert!(instances_in([]).is_empty());
+ }
+}
diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs
index f0f2557ded..765c6ca77e 100644
--- a/crates/engine/src/cmd/buildcmds/trace.rs
+++ b/crates/engine/src/cmd/buildcmds/trace.rs
@@ -58,9 +58,10 @@ fn view_param(cmd: &str, p: &Value) -> Result> {
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
}
-/// The `split` param (the Split view's divider, 0 to 1), if given.
+/// The `split` param (the Split view's divider, 0 to 1), if given. A null divider is an error, as
+/// any other value that is not such a number is; only an omitted one keeps the divider.
fn split_param(cmd: &str, p: &Value) -> Result > {
- let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
+ let Some(v) = p.get("split") else { return Ok(None) };
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
}
@@ -649,7 +650,16 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result {
None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(),
None => "Custom".to_string(),
};
+ // The image (inside a trace group, or selected directly).
let (target, image) = target_image(s, c, p)?;
+ // The traced shapes are placed by the image's transform, which a distortion overrides: the
+ // command stops before any pixels are read.
+ let distorted = s.doc()?.doc.node(target).is_some_and(|n| {
+ n.is_distorted_image() || (is_trace_group(n) && n.children().and_then(|c| c.first()).is_some_and(|i| i.is_distorted_image()))
+ });
+ if distorted {
+ return Err(crate::cmd::xform::distorted_image_error(c, target));
+ }
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
}
diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs
index 5603037e72..c6c1da2980 100644
--- a/crates/engine/src/cmd/clipboard.rs
+++ b/crates/engine/src/cmd/clipboard.rs
@@ -112,6 +112,9 @@ pub struct Clipboard {
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
pub guides: Vec,
+ /// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in
+ /// [`Self::nodes`]: a pasted set packs from it.
+ pub set_densities: BTreeMap,
/// The RGB and CMYK profiles the objects' colors showed through in the document they were
/// copied from (its assigned profiles, else the working spaces then), by name; none for objects
/// from outside an open document. Paste compares them with the destination's
@@ -489,6 +492,7 @@ impl Clipboard {
})
.collect(),
guides: self.guides.clone(),
+ set_densities: self.set_densities.clone(),
source_profiles: self.source_profiles.clone(),
colors_converted: self.colors_converted,
}
diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs
index 051ad4e109..55e9b5061c 100644
--- a/crates/engine/src/cmd/clipboard/resources.rs
+++ b/crates/engine/src/cmd/clipboard/resources.rs
@@ -1201,6 +1201,7 @@ impl Clipboard {
para_styles: pick(Res::ParaStyle, &src.para_styles),
brushes,
graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(),
+ set_densities: src.set_densities_of(&nodes),
nodes,
..Default::default()
}
diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs
index 00852cbde9..1b394fa95c 100644
--- a/crates/engine/src/cmd/colormgmt.rs
+++ b/crates/engine/src/cmd/colormgmt.rs
@@ -26,6 +26,8 @@ use vectorcraft_render::proof;
use super::EngineError;
use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param};
+pub mod proof_file;
+
/// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated
/// to `Document::color_profiles` on load).
pub const PROFILES_KEY: &str = vectorcraft_doc::profiles::LEGACY_PROFILES_KEY;
@@ -82,7 +84,7 @@ pub fn specs() -> Vec {
"Convert Color",
[],
None,
- "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
+ "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first",
always,
convert_color
),
@@ -104,6 +106,42 @@ pub fn specs() -> Vec {
always,
proof_setup
),
+ cmd!(
+ query "view.proofSetup.save",
+ "Save Proof Setup…",
+ [],
+ None,
+ "{path?: file | name?: a setup in the Proof Setups folder next to the preferences (at most 100 characters and no path characters; exactly one of the two), target?, intent?, simulatePaper?, preserveNumbers?, simulateBlack? (as view.proofSetup; default: the current proof setup's)} write a custom proof setup to a VectorCraft proof setup file (.vcproof, JSON) without changing the proof view. The target must be a device: workingCmyk, cmyk: or rgb: → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}",
+ always,
+ proof_file::save
+ ),
+ cmd!(
+ query "view.proofSetup.load",
+ "Load Proof Setup…",
+ [],
+ None,
+ "{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} read a proof setup file of at most 64 KiB that view.proofSetup.save wrote, make it the proof setup and turn Proof Colors on → {path} and the proof state. A file whose device names a profile that is not loaded is refused and nothing changes",
+ always,
+ proof_file::load
+ ),
+ cmd!(
+ query "view.proofSetup.read",
+ "Read Proof Setup",
+ [],
+ None,
+ "{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} the settings of a proof setup file, read as view.proofSetup.load reads it, without changing the proof view → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}",
+ always,
+ proof_file::read
+ ),
+ cmd!(
+ query "view.proofSetup.list",
+ "Saved Proof Setups",
+ [],
+ None,
+ "{} the proof setup files in the Proof Setups folder next to the preferences, by name, at most 100 → {folder (null without the folder), setups: [{name, path}], truncated}",
+ always,
+ proof_file::list
+ ),
cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| {
toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
}),
@@ -1324,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result {
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
let lab = c.lab(&col);
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
- "rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
- "cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
- "gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
- "lab" => ("lab", vec![lab.l, lab.a, lab.b]),
+ "rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))),
+ "cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))),
+ "gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))),
+ "lab" => ("lab", json!([lab.l, lab.a, lab.b])),
+ "oklch" => {
+ // RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them.
+ let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0)));
+ ("oklch", json!([l * 100.0, ch, h]))
+ }
other => return Err(bad(C, format!("unknown model `{other}`"))),
};
let de = c.gamut_error(&col);
@@ -1403,26 +1446,7 @@ fn view_json(v: &proof::ProofView) -> Value {
fn proof_setup(s: &mut Session, p: &Value) -> Result {
const C: &str = "view.proofSetup";
let mut v = proof::view();
- if let Some(t) = text_param(p, "target", C)? {
- let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?;
- if let ProofTarget::Cmyk(name) = &t
- && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
- {
- return Err(bad(C, format!("unknown CMYK profile `{name}`")));
- }
- if let ProofTarget::Rgb(name) = &t
- && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Rgb)
- {
- return Err(bad(C, format!("unknown RGB profile `{name}`")));
- }
- v.setup.target = t;
- }
- if let Some(i) = intent_param(p, C)? {
- v.setup.intent = i;
- }
- v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?;
- v.setup.preserve_numbers = switch_or(p, "preserveNumbers", v.setup.preserve_numbers, C)?;
- v.setup.simulate_black = switch_or(p, "simulateBlack", v.setup.simulate_black, C)?;
+ setup_params(p, &mut v.setup, C)?;
if let Some(on) = on_param(p, "proof", C)? {
v.proof_colors = on;
}
@@ -1430,6 +1454,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result {
Ok(view_json(&v))
}
+/// Take the proof setup settings `p` gives (`target`, `intent`, `simulatePaper`, `preserveNumbers`
+/// and `simulateBlack`, as `view.proofSetup` reads them) into `setup`. A `cmyk:` or `rgb:` target
+/// must name a CMYK or RGB profile that is loaded.
+fn setup_params(p: &Value, setup: &mut cms::ProofSetup, cmd: &str) -> Result<()> {
+ if let Some(t) = text_param(p, "target", cmd)? {
+ let t = ProofTarget::parse(t).ok_or_else(|| bad(cmd, format!("unknown proof target `{t}`")))?;
+ if let ProofTarget::Cmyk(name) = &t
+ && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
+ {
+ return Err(bad(cmd, format!("unknown CMYK profile `{name}`")));
+ }
+ if let ProofTarget::Rgb(name) = &t
+ && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Rgb)
+ {
+ return Err(bad(cmd, format!("unknown RGB profile `{name}`")));
+ }
+ setup.target = t;
+ }
+ if let Some(i) = intent_param(p, cmd)? {
+ setup.intent = i;
+ }
+ setup.simulate_paper = switch_or(p, "simulatePaper", setup.simulate_paper, cmd)?;
+ setup.preserve_numbers = switch_or(p, "preserveNumbers", setup.preserve_numbers, cmd)?;
+ setup.simulate_black = switch_or(p, "simulateBlack", setup.simulate_black, cmd)?;
+ Ok(())
+}
+
/// Make `v` the proof view and redraw every document. When `v` equals the current view, the view
/// and the revisions stay as they are; Separations Preview's visible plates are compared as a set.
fn store_view(s: &mut Session, v: proof::ProofView) {
diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs
new file mode 100644
index 0000000000..7f92bed6b4
--- /dev/null
+++ b/crates/engine/src/cmd/colormgmt/proof_file.rs
@@ -0,0 +1,288 @@
+//! View → Proof Setup → Customize…'s Save… and Load…: a custom proof setup (the device to simulate,
+//! Preserve Numbers, the rendering intent, Simulate Paper Color and Simulate Black Ink) in a file,
+//! and the setups saved in the `Proof Setups` folder next to the preferences, which View → Proof
+//! Setup lists ([`Session::attach_proof_setups`]). `view.proofSetup.read` reads a file without
+//! applying it, which is how Load… fills the dialog.
+//!
+//! The file format is VectorCraft's own: JSON with `format` [`FORMAT`], `version` 1, `target`,
+//! `intent`, `simulatePaper`, `preserveNumbers` and `simulateBlack`, as `view.proofSetup` names
+//! them, at most [`MAX_FILE`] bytes.
+
+use serde_json::{Value, json};
+use vectorcraft_color::cms::{self, Intent, ProofSetup, ProofTarget};
+use vectorcraft_render::proof;
+
+use super::super::{EngineError, fileio};
+use super::{Result, Session, bad, setup_params, store_view, text_param, view_json};
+
+/// The extension of a proof setup file.
+pub const EXT: &str = "vcproof";
+/// The `format` a proof setup file names.
+pub const FORMAT: &str = "vectorcraft-proof-setup";
+/// The format version this build writes and reads.
+const VERSION: u64 = 1;
+/// The largest proof setup file `view.proofSetup.load` reads, bytes (VectorCraft's own limit).
+pub const MAX_FILE: usize = 64 << 10;
+/// The most setups `view.proofSetup.list` lists.
+pub const MAX_LISTED: usize = 100;
+/// The most folder entries `view.proofSetup.list` looks at, setup files or not.
+const MAX_SCANNED: usize = 100_000;
+/// The longest `name`, in characters.
+const MAX_NAME: usize = 100;
+
+impl Session {
+ /// Keep the proof setups that `view.proofSetup.save` saves by name in the folder `dir` (`Proof
+ /// Setups` next to the preferences), which `view.proofSetup.list` lists. The folder is made
+ /// when a setup is first saved there.
+ pub fn attach_proof_setups(&mut self, dir: std::path::PathBuf) {
+ self.proof_setup_dir = Some(dir);
+ }
+
+ /// The saved proof setups' folder ([`Session::attach_proof_setups`]); none on the web.
+ pub fn proof_setup_dir(&self) -> Option<&std::path::Path> {
+ self.proof_setup_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
+ }
+
+ /// How many proof setup files `view.proofSetup.save` wrote in this session; the menus list the
+ /// Proof Setups folder again when it changes.
+ pub fn proof_setup_saves(&self) -> u64 {
+ self.proof_setup_saves
+ }
+}
+
+/// The file `p` names for `cmd`: its `path`, or the setup `name` in the Proof Setups folder.
+fn file_path(s: &Session, p: &Value, cmd: &str) -> Result<(String, bool)> {
+ match (text_param(p, "path", cmd)?, text_param(p, "name", cmd)?) {
+ (Some(path), None) if path.trim().is_empty() => Err(bad(cmd, "`path` is empty")),
+ (Some(path), None) => Ok((path.to_string(), false)),
+ (None, Some(name)) => {
+ let name = setup_name(name, cmd)?;
+ let dir = s.proof_setup_dir().ok_or_else(|| bad(cmd, "saved proof setups need the preferences folder, which this run doesn't have"))?;
+ let path = dir.join(format!("{name}.{EXT}"));
+ let path = path.to_str().ok_or_else(|| bad(cmd, format!("{}: the folder's path is not valid Unicode", dir.display())))?;
+ Ok((path.to_string(), true))
+ }
+ (Some(_), Some(_)) => Err(bad(cmd, "give `path` or `name`, not both")),
+ (None, None) => Err(bad(cmd, "missing `path` or `name`")),
+ }
+}
+
+/// `name` trimmed, when it can name a file in the Proof Setups folder: not empty, at most
+/// [`MAX_NAME`] characters, no path or control characters, and not starting with a dot.
+fn setup_name<'a>(name: &'a str, cmd: &str) -> Result<&'a str> {
+ let name = name.trim();
+ if name.is_empty() {
+ return Err(bad(cmd, "`name` is empty"));
+ }
+ if name.chars().count() > MAX_NAME {
+ return Err(bad(cmd, format!("`name` is longer than {MAX_NAME} characters")));
+ }
+ if name.starts_with('.') || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) {
+ return Err(bad(cmd, format!("`name` can't hold path characters: `{name}`")));
+ }
+ Ok(name)
+}
+
+/// `Ok` when `t` is a device a custom proof setup can simulate and its profile is loaded.
+fn check_device(t: &ProofTarget) -> std::result::Result<(), String> {
+ let loaded = |name: &str, kind| cms::profile(name).is_some_and(|k| k.kind == kind);
+ match t {
+ ProofTarget::WorkingCmyk => Ok(()),
+ ProofTarget::Cmyk(name) if loaded(name, cms::ProfileKind::Cmyk) => Ok(()),
+ ProofTarget::Rgb(name) if loaded(name, cms::ProfileKind::Rgb) => Ok(()),
+ ProofTarget::Cmyk(name) => Err(format!("the device to simulate is the CMYK profile `{name}`, which is not loaded")),
+ ProofTarget::Rgb(name) => Err(format!("the device to simulate is the RGB profile `{name}`, which is not loaded")),
+ t => Err(format!("`{}` is not a device to simulate: a custom proof setup simulates workingCmyk, cmyk: or rgb:", t.id())),
+ }
+}
+
+/// The settings of `setup`, as `view.proofSetup` names them.
+fn setup_json(setup: &ProofSetup) -> serde_json::Map {
+ let v = json!({
+ "target": setup.target.id(),
+ "intent": setup.intent.id(),
+ "simulatePaper": setup.simulate_paper,
+ "preserveNumbers": setup.preserve_numbers,
+ "simulateBlack": setup.simulate_black,
+ });
+ match v {
+ Value::Object(m) => m,
+ _ => serde_json::Map::new(),
+ }
+}
+
+/// The proof setup in a file's `bytes`, or why it can't be read.
+pub fn parse(bytes: &[u8]) -> std::result::Result {
+ let v: Value = serde_json::from_slice(bytes).map_err(|e| format!("not a proof setup file: {e}"))?;
+ if v.get("format").and_then(Value::as_str) != Some(FORMAT) {
+ return Err("not a VectorCraft proof setup file".into());
+ }
+ match v.get("version").and_then(Value::as_u64) {
+ Some(VERSION) => {}
+ Some(n) if n > VERSION => return Err(format!("the file is version {n}, made by a newer VectorCraft")),
+ _ => return Err("the file has no version VectorCraft reads".into()),
+ }
+ let text = |key: &str| v.get(key).and_then(Value::as_str);
+ let target = text("target").ok_or("the file names no device to simulate")?;
+ let target = ProofTarget::parse(target).ok_or_else(|| format!("unknown proof target `{target}`"))?;
+ let intent = text("intent").ok_or("the file names no rendering intent")?;
+ let intent = Intent::parse(intent).ok_or_else(|| format!("unknown intent `{intent}`"))?;
+ let on = |key: &str| match v.get(key) {
+ None | Some(Value::Null) => Ok(false),
+ Some(Value::Bool(b)) => Ok(*b),
+ Some(_) => Err(format!("`{key}` must be true or false")),
+ };
+ Ok(ProofSetup {
+ target,
+ intent,
+ simulate_paper: on("simulatePaper")?,
+ preserve_numbers: on("preserveNumbers")?,
+ simulate_black: on("simulateBlack")?,
+ separations: None,
+ })
+}
+
+/// A proof setup file holding `setup`.
+pub fn encode(setup: &ProofSetup) -> Vec {
+ let mut m = serde_json::Map::new();
+ m.insert("format".into(), json!(FORMAT));
+ m.insert("version".into(), json!(VERSION));
+ m.extend(setup_json(setup));
+ let mut bytes = serde_json::to_vec_pretty(&Value::Object(m)).unwrap_or_default();
+ bytes.push(b'\n');
+ bytes
+}
+
+pub(super) fn save(s: &mut Session, p: &Value) -> Result {
+ const C: &str = "view.proofSetup.save";
+ let (path, named) = file_path(s, p, C)?;
+ let mut setup = proof::view().setup;
+ setup_params(p, &mut setup, C)?;
+ check_device(&setup.target).map_err(|e| bad(C, e))?;
+ // A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
+ let bytes = encode(&setup);
+ if bytes.len() > MAX_FILE {
+ return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
+ }
+ if named
+ && let Some(dir) = std::path::Path::new(&path).parent()
+ && !dir.is_dir()
+ {
+ crate::file_access::check_write(&path).map_err(EngineError::Other)?;
+ std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
+ }
+ fileio::write_file(&path, &bytes)?;
+ s.proof_setup_saves += 1;
+ let mut r = setup_json(&setup);
+ r.insert("path".into(), json!(path));
+ Ok(Value::Object(r))
+}
+
+/// The file `p` names for `cmd` and the usable proof setup in it.
+fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
+ let (path, _) = file_path(s, p, cmd)?;
+ // One byte past the limit shows a file over it, which is not read further.
+ let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
+ if bytes.len() > MAX_FILE {
+ return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
+ }
+ let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
+ check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
+ Ok((path, setup))
+}
+
+pub(super) fn read(s: &mut Session, p: &Value) -> Result {
+ let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
+ let mut r = setup_json(&setup);
+ r.insert("path".into(), json!(path));
+ Ok(Value::Object(r))
+}
+
+pub(super) fn load(s: &mut Session, p: &Value) -> Result {
+ let (path, setup) = read_setup(s, p, "view.proofSetup.load")?;
+ let mut v = proof::view();
+ // Separations Preview's plates are not part of a proof setup file.
+ v.setup = ProofSetup { separations: v.setup.separations.take(), ..setup };
+ v.proof_colors = true;
+ store_view(s, v.clone());
+ let mut r = view_json(&v);
+ r["path"] = json!(path);
+ Ok(r)
+}
+
+pub(super) fn list(s: &mut Session, _: &Value) -> Result {
+ let none = json!({"folder": null, "setups": [], "truncated": false});
+ let Some(dir) = s.proof_setup_dir() else { return Ok(none) };
+ listed(dir).map(|l| l.unwrap_or(none))
+}
+
+/// The web keeps no saved setups ([`Session::proof_setup_dir`]).
+#[cfg(target_arch = "wasm32")]
+pub fn listed(_: &std::path::Path) -> Result> {
+ Ok(None)
+}
+
+/// The listing of the Proof Setups folder `dir`, as `view.proofSetup.list` gives it; `None` for a
+/// request that may not read it. The app calls it on another thread, without a session.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn listed(dir: &std::path::Path) -> Result > {
+ const C: &str = "view.proofSetup.list";
+ let folder = dir.to_string_lossy().into_owned();
+ // A request that may not read the folder learns nothing of it, nor where it is.
+ if crate::file_access::check_read(&folder).is_err() {
+ return Ok(None);
+ }
+ // The listed paths are text: a folder whose path is not valid Unicode can't be named in them.
+ if dir.to_str().is_none() {
+ return Err(bad(C, format!("{folder}: the folder's path is not valid Unicode")));
+ }
+ let entries = match std::fs::read_dir(dir) {
+ Ok(entries) => entries,
+ // No folder yet: nothing has been saved.
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Some(json!({"folder": folder, "setups": [], "truncated": false}))),
+ Err(e) => return Err(bad(C, format!("{folder}: {e}"))),
+ };
+ // The setups' names, the first MAX_LISTED by name; other entries are passed over before the
+ // limit applies. A link is not followed. A file is listed only when it is named
+ // `.vcproof` and `name` takes that name unchanged, so each listed name loads its own
+ // file. An entry that can't be read, or whose file name is not valid Unicode, leaves the
+ // listing incomplete.
+ let (mut names, mut truncated) = (Vec::::new(), false);
+ for (i, e) in entries.enumerate() {
+ if i == MAX_SCANNED {
+ truncated = true;
+ break;
+ }
+ let Ok(e) = e else {
+ truncated = true;
+ continue;
+ };
+ let Ok(file) = e.file_name().into_string() else {
+ truncated = true;
+ continue;
+ };
+ let Some(name) = file.strip_suffix(EXT).and_then(|s| s.strip_suffix('.')) else { continue };
+ if setup_name(name, C).ok() != Some(name) {
+ continue;
+ }
+ match e.file_type() {
+ Ok(t) if t.is_file() => {}
+ Ok(_) => continue,
+ Err(_) => {
+ truncated = true;
+ continue;
+ }
+ }
+ names.push(name.to_string());
+ if names.len() > 2 * MAX_LISTED {
+ names.sort();
+ names.truncate(MAX_LISTED);
+ truncated = true;
+ }
+ }
+ names.sort();
+ truncated |= names.len() > MAX_LISTED;
+ names.truncate(MAX_LISTED);
+ let setups: Vec = names.iter().map(|name| json!({"name": name, "path": dir.join(format!("{name}.{EXT}")).to_string_lossy()})).collect();
+ Ok(Some(json!({"folder": folder, "setups": setups, "truncated": truncated})))
+}
diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs
index 89752c1b33..f012bcfc82 100644
--- a/crates/engine/src/cmd/create.rs
+++ b/crates/engine/src/cmd/create.rs
@@ -105,6 +105,15 @@ pub fn specs() -> Vec {
has_doc,
arc
),
+ cmd!(
+ "shape.threePointArc",
+ "Three-Point Arc",
+ [],
+ None,
+ "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
+ has_doc,
+ three_point_arc
+ ),
cmd!(
"shape.rectangularGrid",
"Rectangular Grid",
@@ -680,6 +689,50 @@ fn arc(s: &mut Session, p: &Value) -> Result {
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
}
+/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
+/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
+fn three_point_arc(s: &mut Session, p: &Value) -> Result {
+ const C: &str = "shape.threePointArc";
+ let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
+ let (start, end) = (point("start")?, point("end")?);
+ let from_end = match p.get("at") {
+ None => false,
+ Some(Value::String(v)) if v == "start" || v == "end" => v == "end",
+ Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")),
+ };
+ // The arc, and the point it passes through (an anchor of the path, so the path meets it exactly).
+ let (arc, via) = match (p.get("through"), p.get("toward")) {
+ (Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")),
+ (Some(_), None) => {
+ let through = point("through")?;
+ (shapes::CircularArc::through(start, end, through), Some(through))
+ }
+ (None, Some(_)) if from_end => {
+ let toward = point("toward")?;
+ (shapes::CircularArc::arriving(start, end, end - toward), None)
+ }
+ (None, Some(_)) => {
+ let toward = point("toward")?;
+ (shapes::CircularArc::leaving(start, toward - start, end), None)
+ }
+ _ => return Err(bad(C, "give exactly one of `through` and `toward`")),
+ };
+ let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
+ let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
+ let look = s.new_art_look(
+ vectorcraft_color::Paint::None,
+ if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
+ s.paint.stroke_width.max(0.1),
+ );
+ // Not pixel-aligned: the ends stay on the given points.
+ let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?;
+ out["cx"] = json!(arc.center.x);
+ out["cy"] = json!(arc.center.y);
+ out["radius"] = json!(arc.radius);
+ out["sweep"] = json!(arc.sweep.to_degrees());
+ Ok(out)
+}
+
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
/// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group
/// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle).
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index adfd0458f9..ccebbfac88 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
for xf in placements {
for (k, n) in clip.nodes.iter().enumerate() {
let mut c = d.reid(n);
+ // A pasted symbol set packs from the density recorded for it at Copy.
+ d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs
index 5ea3efd950..831c56063a 100644
--- a/crates/engine/src/cmd/effectcmd.rs
+++ b/crates/engine/src/cmd/effectcmd.rs
@@ -442,6 +442,17 @@ fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> {
pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first.";
+/// The Pathfinder Options that `effect.apply` gives a Pathfinder effect for the keys its `params`
+/// leave out: the preferences' Pathfinder Options in force.
+pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOptions {
+ let current = super::pathops::current_pf_options(s);
+ effects::PathfinderEffectOptions {
+ precision: current.precision,
+ remove_redundant_points: current.remove_redundant_points,
+ remove_unpainted: current.remove_unpainted,
+ }
+}
+
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
@@ -465,10 +476,23 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result {
super::params::check_effect_color(C, id, ¶ms)?;
super::params::check_effect_channel(C, id, ¶ms)?;
super::params::check_effect_center(C, id, ¶ms)?;
+ super::params::check_effect_pathfinder(C, id, ¶ms)?;
// Crop Marks take their style from the preferences when applied.
if id == effects::CROP_MARKS && params.get("style").is_none() {
params["style"] = json!(s.crop_mark_style().id());
}
+ // A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those `params`
+ // give aside. They join the journal entry, so replaying it gives the same effect.
+ if effects::takes_pathfinder_options(id) {
+ if let Value::Object(filled) = pathfinder_effect_options(s).to_params() {
+ for (key, v) in filled {
+ if params.get(&key).is_none() {
+ params[key.as_str()] = v;
+ }
+ }
+ }
+ s.note_journal("params", params.clone());
+ }
if texture_load_effect(id) {
load_texture(&mut params, C)?;
}
@@ -789,6 +813,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result {
super::params::check_effect_color(C, effect, ¶ms)?;
super::params::check_effect_channel(C, effect, ¶ms)?;
super::params::check_effect_center(C, effect, ¶ms)?;
+ super::params::check_effect_pathfinder(C, effect, ¶ms)?;
}
if edited.iter().any(|e| texture_load_effect(e)) {
load_texture(&mut params, C)?;
@@ -808,6 +833,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result {
return Ok(json!({ "ids": [] }));
}
}
+ // Pathfinder effects given the values they already evaluate with, and nothing else to change,
+ // are no edit and record no undo step.
+ if kind.is_none() && warp_id.is_none() && visible.is_none() {
+ let d = &s.doc()?.doc;
+ let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
+ if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) {
+ return Ok(json!({ "ids": [] }));
+ }
+ }
// An SVG filter is named by its id: another filter renames the effect.
if edited.iter().any(|e| e == effects::SVG_FILTER)
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
@@ -876,6 +910,30 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result {
Ok(json!({ "ids": ids_json(&ids) }))
}
+/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
+/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
+/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
+/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every
+/// other value given equal to the one it has?
+fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
+ if !effects::takes_pathfinder_options(&e.id) {
+ return false;
+ }
+ let Some(given) = params.as_object().filter(|m| !m.is_empty()) else { return true };
+ let current = effects::merged_params(&e.id, &e.params);
+ let mut after = current.clone();
+ if let Value::Object(m) = &mut after {
+ m.extend(given.clone());
+ }
+ let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
+ let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x));
+ let stored_same = given
+ .iter()
+ .filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
+ .all(|(k, v)| e.params.get(k).is_none_or(|stored| same_value(stored, v)));
+ others_same && stored_same && effects::PathfinderEffectOptions::from_params(¤t) == effects::PathfinderEffectOptions::from_params(&after)
+}
+
// ---------- Load Texture ----------
/// Effect › Distort › Glass.
diff --git a/crates/engine/src/cmd/flatten/compose.rs b/crates/engine/src/cmd/flatten/compose.rs
index fef23f86ae..ee245f16d2 100644
--- a/crates/engine/src/cmd/flatten/compose.rs
+++ b/crates/engine/src/cmd/flatten/compose.rs
@@ -141,7 +141,11 @@ impl Builder {
if fills.is_empty() { Body::Complex } else { Body::Fills { shape: self.shape(path, rule, Kind::Vector)?, fills } }
}
NodeKind::Image(im) => {
- let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
+ // A distorted image's frame joins its corners.
+ let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
+ Some(bp) => PathData::from_bezpath(&bp),
+ None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
+ };
self.shape(frame, FillRule::NonZero, Kind::Other)?;
Body::Complex
}
diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs
index 746749235b..3f9d749a6c 100644
--- a/crates/engine/src/cmd/gradient.rs
+++ b/crates/engine/src/cmd/gradient.rs
@@ -24,7 +24,7 @@ pub fn specs() -> Vec {
"Gradient",
["Window", "Gradient"],
None,
- "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)",
+ "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)",
has_doc,
edit_gradient
),
@@ -63,7 +63,7 @@ fn select_stop(s: &mut Session, p: &Value) -> Result {
// No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`.
// While the Live Paint Bucket is active the proxies show the default paint, whose stops can be
// selected with a part picked.
- if s.tool_id() != super::paint::LIVE_PAINT_BUCKET && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
+ if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
return Err(super::brushsym::part_only());
}
let index = match p.get("index") {
@@ -111,12 +111,23 @@ impl StopOwner {
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
fill: s.fill_active,
item: s.appearance_item(),
- bucket: s.tool_id() == super::paint::LIVE_PAINT_BUCKET,
+ bucket: s.bucket_paints(),
}
}
}
impl Session {
+ /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not
+ /// while the Live Paint Bucket is active or when nothing it can paint is selected (a Live Paint group stands
+ /// only for its faces in a fill edit and its edges in a stroke edit): it then edits no object and takes no
+ /// `aspect`.
+ pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool {
+ let p = json!({ "stroke": stroke });
+ !super::paint::for_bucket(self, &p)
+ && item_target(self, &p, "paint.editGradient")
+ .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty()))
+ }
+
/// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on
/// is still the one behind the active proxy. Callers check it against the stop count (an undo
/// can remove stops).
@@ -547,6 +558,12 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result {
// Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts
// of the other kind left out above: the stroke mode is then not one for new art.
let selected = !ids.is_empty() || skipped;
+ // The default gradient for new art (and the bucket's) is fitted to each object, so it has no aspect of its own. A
+ // Live Paint group with no part of the edited kind gives no object either. Graph design art is left out below
+ // without an error, as for every other param.
+ if ids.is_empty() && p.get("aspect").is_some() {
+ return Err(bad(C, "`aspect` needs objects to place the gradient on: give ids or select objects"));
+ }
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
// How the gradient lies on a stroke (the panel's Stroke buttons).
let mode = match str_param(p, "strokeMode") {
diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs
index 392d6340c6..abb1a2d2aa 100644
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@ -1211,6 +1211,16 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
install(d, &[id], read, Some(Preserve::Bounds), None)
}
+/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its
+/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader
+/// that places it by the transform still gives it its old size.
+fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) {
+ if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
+ im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
+ }
+ (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
+}
+
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
@@ -1235,7 +1245,12 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
let mut n = n.clone();
let mut clip = ClipTo::Keep;
+ let distorted = n.is_distorted_image();
if let NodeKind::Image(im) = &mut n.kind {
+ if distorted {
+ refill_distorted(im, &link, &img);
+ return (n, clip);
+ }
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
let (old_pt, old_clip) = match old.get(&im.key) {
@@ -1251,6 +1266,14 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
for id in ids {
+ if d.node(*id).is_some_and(Node::is_distorted_image) {
+ if let Some(n) = d.node_mut(*id)
+ && let NodeKind::Image(im) = &mut n.kind
+ {
+ refill_distorted(im, &link, &img);
+ }
+ continue;
+ }
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
@@ -2068,6 +2091,9 @@ fn relink(s: &mut Session, p: &Value) -> Result {
_ => None,
})
};
+ // Whether the images were found as the missing links (nothing selected, a folder given) rather
+ // than named or selected.
+ let mut found_missing = false;
let mut ids: Vec = match (&each, ids_param(p, "ids", C)?) {
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
(None, Some(ids)) => ids,
@@ -2075,6 +2101,7 @@ fn relink(s: &mut Session, p: &Value) -> Result {
let selected: Vec = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
match folder_param {
Some(_) if selected.is_empty() => {
+ found_missing = true;
groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect()
}
_ => selected,
@@ -2087,6 +2114,11 @@ fn relink(s: &mut Session, p: &Value) -> Result {
if ids.is_empty() {
return Err(bad(C, "select the images to relink, or pass ids"));
}
+ // A named or selected distorted image is refused before a folder is searched, whether or not
+ // its file is found there.
+ if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
+ return Err(super::xform::distorted_image_error(C, *id));
+ }
// All Instances: the other stored objects linked to the same files, each once.
if scope == Scope::All {
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
@@ -2131,6 +2163,11 @@ fn relink(s: &mut Session, p: &Value) -> Result {
}
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
}
+ // A new file's placement options place a plain image: a distorted one is left as it is.
+ let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image));
+ if let Some(id) = distorted {
+ return Err(super::xform::distorted_image_error(C, *id));
+ }
// Every file is read and checked before any is copied.
let mut checked = vec![];
for (ids, path) in files {
@@ -2593,6 +2630,9 @@ fn embed(s: &mut Session, p: &Value) -> Result {
if ids.is_empty() {
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
}
+ if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
+ return Err(super::xform::distorted_image_error(C, *id));
+ }
// A DCS file's plates print from its file.
let separated = |id: &NodeId| match kind(id) {
Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated),
@@ -2721,6 +2761,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result {
if im.link.is_some() {
return Err(bad(C, format!("image {} is linked already", id.0)));
}
+ if n.is_distorted_image() {
+ return Err(super::xform::distorted_image_error(C, id));
+ }
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
let stored = stored_extension(blob);
@@ -2772,6 +2815,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re
skipped.push(id);
continue;
}
+ if n.is_distorted_image() {
+ return Err(super::xform::distorted_image_error(C, id));
+ }
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
embedded.push((id, n.display_name(), blob));
}
@@ -2984,7 +3030,9 @@ fn info(s: &mut Session, p: &Value) -> Result {
let (px, py) = file_pt(&st.doc, &im.key);
out["effectivePpi"] = out["ppi"].take();
out["ppi"] = json!([72.0 / px, 72.0 / py]);
- (out["scale"], out["rotation"]) = scale_rotation(im.xf, (px, py));
+ // A distorted image is measured at its middle, as its effective resolution is.
+ let xf = stored(&doc, id).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf);
+ (out["scale"], out["rotation"]) = scale_rotation(xf, (px, py));
out["format"] = json!(format_label(&st.doc, im));
out["placement"] = placement_json(im.placement);
out["status"] = json!("embedded");
diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs
index cfb87afdb3..d2e3f7b95a 100644
--- a/crates/engine/src/cmd/live/blend.rs
+++ b/crates/engine/src/cmd/live/blend.rs
@@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result {
Some(_) => return Err(bad(C, "handle must be in or out")),
};
let independent = switch_or(p, "independent", false, C)?;
+ let symmetric = switch_or(p, "symmetric", false, C)?;
let link = switch_or(p, "link", false, C)?;
let with = spine_points_param(p, C)?;
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`with` moves points, not a handle"));
}
+ if symmetric && independent {
+ return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
+ }
+ if symmetric && handle.is_none() {
+ return Err(bad(C, "`symmetric` places a handle: give `handle`"));
+ }
+ if link && symmetric {
+ return Err(bad(C, "`link` and `symmetric` cannot both be true"));
+ }
if link && independent {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
@@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result {
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
+ // At an open end of the spine the handle moves as it would without `symmetric`.
+ let symmetric = symmetric && pull_out;
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
if let Some(out) = handle {
if link {
@@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result {
} else {
a.set_handle(out, q, independent);
}
+ if symmetric {
+ let opposite = a.p - (q - a.p);
+ if out { a.h_in = opposite } else { a.h_out = opposite }
+ }
return Ok(());
}
let delta = q - a.p;
diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs
index 991ebf103c..7d23f34a77 100644
--- a/crates/engine/src/cmd/live/commands.rs
+++ b/crates/engine/src/cmd/live/commands.rs
@@ -99,7 +99,7 @@ pub fn specs() -> Vec {
"Move Spine Point",
[],
None,
- "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
+ "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
has_doc,
spine_move_anchor
),
diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs
index 97b6160718..70d31c2a34 100644
--- a/crates/engine/src/cmd/live/mesh.rs
+++ b/crates/engine/src/cmd/live/mesh.rs
@@ -25,14 +25,23 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result {
};
let (rows, cols) = if at.is_some() { (1, 1) } else { (rows, cols) };
let roots = roots_param(s, p)?;
+ // The distorted images left as they are, each with why.
+ let mut distorted = vec![];
let (ids, index) = s.edit("Create Gradient Mesh", |d, sel| {
let mut out = vec![];
let mut index = None;
let mut refused = None;
let model = d.color_mode.model();
+ distorted.clear();
for id in &roots {
let Some(n) = d.node(*id).cloned() else { continue };
let m = if let NodeKind::Image(im) = &n.kind {
+ if n.is_distorted_image() {
+ let e = super::super::xform::distorted_image_error(C, *id);
+ distorted.push(json!({"id": id.0, "reason": e.to_string()}));
+ refused.get_or_insert(e);
+ continue;
+ }
// An embedded image: the points take the picture's colours there.
match image_mesh(d, im, rows, cols) {
Ok(mut m) => {
@@ -40,7 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result {
Some(m)
}
Err(why) => {
- refused.get_or_insert(why);
+ refused.get_or_insert_with(|| bad(C, why));
continue;
}
}
@@ -60,7 +69,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result {
match m.add_lines_at(q, tol) {
Some(i) => index = Some(i),
None => {
- refused.get_or_insert("point is outside the object");
+ refused.get_or_insert_with(|| bad(C, "point is outside the object"));
continue;
}
}
@@ -75,7 +84,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result {
out.push(*id);
}
if out.is_empty() {
- return Err(bad(C, refused.unwrap_or("select a path, a compound path or an embedded image")));
+ return Err(refused.unwrap_or_else(|| bad(C, "select a path, a compound path or an embedded image")));
}
sel.set(out.iter().copied());
Ok((out, index))
@@ -84,6 +93,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result {
if let Some(i) = index {
r["index"] = json!(i);
}
+ if !distorted.is_empty() {
+ r["skipped"] = json!(distorted);
+ }
Ok(r)
}
diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs
index a1464ebcef..aa330e11ea 100644
--- a/crates/engine/src/cmd/menucmds.rs
+++ b/crates/engine/src/cmd/menucmds.rs
@@ -998,6 +998,9 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result {
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
+ if node.is_distorted_image() {
+ return Err(super::xform::distorted_image_error(C, id));
+ }
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
return Err(bad(C, "the image has no embedded pixels"));
}
@@ -1285,6 +1288,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result {
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
+ if node.is_distorted_image() {
+ return Err(super::xform::distorted_image_error(C, id));
+ }
if switch_or(p, "trim", false, C)? {
if p.get("ppi").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
@@ -1495,11 +1501,16 @@ fn mask_image(s: &mut Session, _: &Value) -> Result {
.selection
.objects
.iter()
- .find_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
- Some(NodeKind::Image(im)) => {
- Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
+ .find_map(|id| {
+ let n = st.doc.node(*id)?;
+ match &n.kind {
+ // A distorted image's outline joins its corners.
+ NodeKind::Image(_) if n.is_distorted_image() => Some((*id, PathData::from_bezpath(&n.image_frame()?))),
+ NodeKind::Image(im) => {
+ Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
+ }
+ _ => None,
}
- _ => None,
})
.ok_or_else(|| bad("object.maskImage", "select an image"))?;
let (gid, pid) = s.edit("Mask", |d, sel| {
diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs
index d9d0905140..a42088e7e3 100644
--- a/crates/engine/src/cmd/newart.rs
+++ b/crates/engine/src/cmd/newart.rs
@@ -209,7 +209,7 @@ impl Session {
/// the first selected object (so the last selection's once nothing is selected). Not while the
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
pub(crate) fn inherit_new_art(&mut self) {
- if self.prefs.new_art_basic || self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
+ if self.prefs.new_art_basic || self.bucket_paints() {
return;
}
let Some(st) = self.active() else { return };
diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs
index 071c5f9862..56d9f1379f 100644
--- a/crates/engine/src/cmd/paint.rs
+++ b/crates/engine/src/cmd/paint.rs
@@ -203,10 +203,11 @@ impl Session {
/// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With
/// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that
- /// object as the instance draws it. None while the Live Paint Bucket is the active tool: the
- /// proxies show the colors it paints with.
+ /// object as the instance draws it. None while the Live Paint Bucket is the active tool (or
+ /// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it
+ /// paints with.
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option)> {
- if self.tool_id() == LIVE_PAINT_BUCKET {
+ if self.bucket_paints() {
return None;
}
let st = self.active()?;
@@ -378,11 +379,28 @@ impl DocState {
}
impl Session {
+ /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
+ /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
+ /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
+ /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
+ /// sample its click takes before it switches back to the bucket.
+ pub fn bucket_paints(&self) -> bool {
+ let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
+ // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
+ self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
+ }
+
+ /// The tool the active tool's armed one-shot pick switches back to after its click
+ /// ([`vectorcraft_tools::Tool::returns_to`]).
+ pub fn tool_returns_to(&self) -> Option {
+ self.tool.returns_to().map(str::to_string)
+ }
+
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
/// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]).
pub fn proxy_mixed(&self) -> (bool, bool) {
- if self.tool_id() == LIVE_PAINT_BUCKET {
+ if self.bucket_paints() {
return (false, false);
}
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
@@ -737,12 +755,13 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
Ok(json!({"objects": ids.iter().collect::>().len()}))
}
-/// Is the Live Paint Bucket the active tool while `p` names no `ids`, `id` or `item`? A fill,
+/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`,
+/// `id` or `item`? A fill,
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
/// and the selection keeps its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
- s.tool_id() == LIVE_PAINT_BUCKET && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
+ s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
}
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs
index 8e7d7f7b0f..ff66759b5a 100644
--- a/crates/engine/src/cmd/params.rs
+++ b/crates/engine/src/cmd/params.rs
@@ -516,7 +516,30 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
}
check_effect_color(id, effect, params)?;
check_effect_channel(id, effect, params)?;
- check_effect_center(id, effect, params)
+ check_effect_center(id, effect, params)?;
+ check_effect_pathfinder(id, effect, params)
+}
+
+/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given
+/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and
+/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves
+/// before they edit, as they run [`check_effect_color`].
+pub(crate) fn check_effect_pathfinder(id: &str, effect: &str, params: &Value) -> Result<()> {
+ use vectorcraft_render::effects;
+ if !effects::takes_pathfinder_options(effect) {
+ return Ok(());
+ }
+ if let Some(v) = params.get("precision")
+ && !v.as_f64().is_some_and(|p| effects::PATHFINDER_EFFECT_PRECISION.contains(&p))
+ {
+ return Err(bad(id, "precision must be from 0.001 to 10 pt"));
+ }
+ for key in ["removeRedundantPoints", "removeUnpainted"] {
+ if params.get(key).is_some_and(|v| !v.is_boolean()) {
+ return Err(bad(id, format!("`{key}` must be true or false")));
+ }
+ }
+ Ok(())
}
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
@@ -557,9 +580,10 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
-/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels
-/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop
-/// Marks have checks of their own; they aren't listed.
+/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and
+/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough
+/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of
+/// Crop Marks have checks of their own; they aren't listed.
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option {
use vectorcraft_render::effects;
let number = || Some(Value::from(0.0));
@@ -568,6 +592,8 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option {
"variation" if effect == "stylize.scribble" => number(),
"width" if effect == "path.outlineStroke" => number(),
"linear" if effect == "blur.gaussian" => Some(Value::Bool(false)),
+ "precision" if effects::takes_pathfinder_options(effect) => number(),
+ "removeRedundantPoints" | "removeUnpainted" if effects::takes_pathfinder_options(effect) => Some(Value::Bool(false)),
_ => None,
}
}
diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs
index 6d01cabd2a..d32594d92d 100644
--- a/crates/engine/src/cmd/path.rs
+++ b/crates/engine/src/cmd/path.rs
@@ -50,7 +50,7 @@ pub fn specs() -> Vec {
"Move Direction Handle",
[],
None,
- "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
+ "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
has_doc,
set_handle
),
@@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result {
return link_handle(s, p, id, si, ai, out, pos);
}
let independent = switch_or(p, "independent", false, "path.setHandle")?;
+ let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?;
+ if symmetric && independent {
+ return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true"));
+ }
+ // The other handle is mirrored only where a segment leaves the anchor on its side: at an open
+ // end the handle moves as it would without `symmetric`.
+ let symmetric = symmetric && has_segment(s, id, si, ai, !out)?;
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
@@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result {
&& at.is_none_or(|to| to == a.p)
&& (if out { a.h_out } else { a.h_in }) == pos
&& !(independent && a.kind != AnchorKind::Corner)
+ && (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p))
{
return ok();
}
@@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result {
} else {
a.set_handle(out, pos, independent);
}
+ if symmetric {
+ let opposite = a.p - (pos - a.p);
+ if out { a.h_in = opposite } else { a.h_out = opposite }
+ }
Ok(())
})?;
ok()
@@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
if switch_or(p, "independent", false, C)? {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
+ if switch_or(p, "symmetric", false, C)? {
+ return Err(bad(C, "`link` and `symmetric` cannot both be true"));
+ }
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
return Err(bad(C, "x and y must be finite"));
}
@@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result Result {
+ if s.script_running() {
+ return Err(EngineError::Busy);
+ }
+ let d = &s.doc()?.doc;
+ Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
+}
+
fn set_anchors(s: &mut Session, p: &Value) -> Result {
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs
index cb60409f17..96b9e51f99 100644
--- a/crates/engine/src/cmd/pathops.rs
+++ b/crates/engine/src/cmd/pathops.rs
@@ -685,14 +685,21 @@ fn pf_label(op: PathfinderOp) -> &'static str {
}
}
-/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
-/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
-fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result {
+/// The Pathfinder Options in the preferences, as the panel's operations and a new Pathfinder effect
+/// take them.
+pub(crate) fn current_pf_options(s: &Session) -> PathfinderOptions {
let mut stored = s.prefs.pathfinder;
if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) {
// A preferences file edited by hand: the default, rather than refitting everything away.
stored.precision = po::DEFAULT_PRECISION;
}
+ stored
+}
+
+/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
+/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
+fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result {
+ let stored = current_pf_options(s);
let keys = ["precision", "removeRedundantPoints", "removeUnpainted"];
let given: serde_json::Map =
p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs
index 9ff644ca6d..b97109026f 100644
--- a/crates/engine/src/cmd/place.rs
+++ b/crates/engine/src/cmd/place.rs
@@ -630,19 +630,7 @@ fn at_param(p: &Value) -> Result> {
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
/// its file's clipping path or not (`new_image`); other objects keep their centre.
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
- // An image alone in a clip group (as a PSD or PSB file's clipping path places it,
- // [`fileio::file_clipped`]) is measured as the image when the new art is an image; a DCS
- // file's plates are not.
- let image = match &old.kind {
- NodeKind::Group { children, clip: true } if new_image => match &children[..] {
- [path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
- NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
- _ => old,
- },
- _ => old,
- },
- _ => old,
- };
+ let image = replace_measured(d, old, new_image);
if image_xf && let NodeKind::Image(im) = &image.kind {
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
let full = Affine::scale_non_uniform(sx, sy);
@@ -655,6 +643,22 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
Affine::translate(c - natural.center())
}
+/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
+/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
+/// image (`new_image`), except a DCS file's plates; else `old` itself.
+fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
+ match &old.kind {
+ NodeKind::Group { children, clip: true } if new_image => match &children[..] {
+ [path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
+ NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
+ _ => old,
+ },
+ _ => old,
+ },
+ _ => old,
+ }
+}
+
/// `rect` fitted with `natural`'s aspect, centred.
fn fit(natural: Rect, r: Rect) -> Affine {
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
@@ -814,6 +818,17 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result {
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
}
let natural = loaded.natural;
+ // Replace keeps the transform of the image it measures (`replace_measured`), which a
+ // distortion's corners do not follow. Type, and any other object it measures, is placed by the
+ // bounds of what it replaces, so a distorted image there is not refused.
+ if let Some(o) = old_node
+ && !is_text
+ {
+ let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
+ if image.is_distorted_image() {
+ return Err(super::xform::distorted_image_error(PLACE, image.id));
+ }
+ }
let m = match (old_node, rect) {
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
(None, Some(r)) => fit(natural, r),
@@ -1173,6 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result {
let doc = super::links::with_brush_art(&st.doc);
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
+ // Effective resolution, taken at the middle of a distorted image.
+ let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf));
let size = n.geometric_bounds().unwrap_or_default();
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
let doc_path = super::links::LinkBase::of(st).doc;
@@ -1184,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result {
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
"pixelWidth": im.width,
"pixelHeight": im.height,
- "ppi": effective_ppi(im.xf),
+ "ppi": ppi,
"width": size.width(),
"height": size.height(),
}))
diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs
index 92e2aa8589..fa41a609c8 100644
--- a/crates/engine/src/cmd/plugin_call/reviewed.rs
+++ b/crates/engine/src/cmd/plugin_call/reviewed.rs
@@ -572,6 +572,7 @@ pub(super) const ALLOWED: &[&str] = &[
"shape.rectangularGrid",
"shape.spiral",
"shape.star",
+ "shape.threePointArc",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs
index f66322498e..46cdee28a5 100644
--- a/crates/engine/src/cmd/prefscmds.rs
+++ b/crates/engine/src/cmd/prefscmds.rs
@@ -404,6 +404,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
"Update Links",
choice(&[("automatically", "Automatically"), ("manually", "Manually"), ("askWhenModified", "Ask When Modified")])
),
+ p!("pdfTextAs", "File Handling", "Files", "PDF Text", choice(&[("text", "Editable"), ("outlines", "Outlines")])),
// Clipboard Handling
p!("copyAsSvg", "Clipboard Handling", "On Copy", "Include SVG Code", bool),
p!("copyAsPdf", "Clipboard Handling", "On Copy", "PDF", bool),
@@ -752,6 +753,13 @@ impl Session {
t.set_option("cornerRadius", &r);
}
}
+ // A press of the tool that is dropped keeps the new radius, also when the tool lent a
+ // selection tool for the press.
+ if self.press_taken_by("roundedRectangle")
+ && let Some((_, saved)) = self.press_options.as_mut()
+ {
+ saved.insert("cornerRadius".into(), r);
+ }
}
if fonts_folder_changed {
let folder = self.prefs.fonts_folder.trim();
diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs
index e5c951e087..d5f90d2411 100644
--- a/crates/engine/src/cmd/rasterfx.rs
+++ b/crates/engine/src/cmd/rasterfx.rs
@@ -455,6 +455,10 @@ fn places(map: Affine) -> bool {
/// member).
pub(crate) fn replace_with_image(mut v: Node, image: Node) -> Node {
if !v.is_layer() {
+ // The new pixels already show a distorted image's distortion.
+ if let Some(e) = v.extras_if_any() {
+ e.image_quad = None;
+ }
return Node { kind: image.kind, appearance: Default::default(), ..v };
}
v.appearance = Default::default();
diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs
index 1c3acf4e73..0bce618fa3 100644
--- a/crates/engine/src/cmd/recolor.rs
+++ b/crates/engine/src/cmd/recolor.rs
@@ -130,7 +130,8 @@ type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
#[derive(Clone)]
struct ImageRead<'a> {
blob: &'a vectorcraft_doc::ImageBlob,
- xf: vectorcraft_geom::Affine,
+ /// Pixel space to the page: the image's transform, or a distorted image's projective map.
+ map: vectorcraft_geom::Homography,
size: (f64, f64),
area: Option,
clip: Option>,
@@ -261,9 +262,9 @@ impl<'a> Theme<'a> {
let keeps: Vec bool + '_>> = group
.iter()
.map(|r| {
- let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested);
+ let (map, (w, h), area, clip, cost, tested) = (r.map, r.size, r.area, &r.clip, elements(r), &tested);
Box::new(move |u: f64, v: f64| {
- let p = xf * Point::new(u * w, v * h);
+ let Some(p) = map.apply(Point::new(u * w, v * h)) else { return false };
area.is_none_or(|a| a.contains(p))
&& clip.as_ref().is_none_or(|rs| {
tested.set(tested.get().saturating_add(cost));
@@ -278,7 +279,7 @@ impl<'a> Theme<'a> {
.map(|(r, keep)| {
use vectorcraft_geom::kurbo::Shape;
let (w, h) = r.size;
- let inv = r.xf.inverse();
+ let inv = r.map.inverse();
// The box sampled: the marquee, cut to the clipping paths' bounds, so a small
// region a clip shows of a large image is still sampled densely.
let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default());
@@ -286,12 +287,16 @@ impl<'a> Theme<'a> {
(Some(a), Some(c)) => Some(a.intersect(c)),
(a, c) => a.or(c),
};
- let box_uv = region.map(|a| {
- let uv: Vec =
- [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect();
+ // A region that crosses a distorted image's horizon has no box: the whole
+ // image is sampled, and `keep` tests each pixel.
+ let box_uv = region.zip(inv).and_then(|(a, inv)| {
+ let uv: Vec = [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)]
+ .into_iter()
+ .map(|(x, y)| inv.apply(Point::new(x, y)))
+ .collect::>()?;
let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min);
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
- [low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
+ Some([low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h])
});
(box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref())
})
@@ -401,7 +406,9 @@ impl<'a> Theme<'a> {
None
};
let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
- self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize });
+ // A distorted image's pixels are where its projective map puts them.
+ let map = n.image_map().unwrap_or_else(|| vectorcraft_geom::Homography::from_affine(im.xf));
+ self.queue_image(ImageRead { blob, map, size, area, clip: self.clip.clone(), colorize });
return;
}
NodeKind::SymbolInstance { symbol, xf } => {
@@ -2051,7 +2058,14 @@ mod tests {
bp.line_to((size, size));
bp.line_to((0.0, size));
bp.close_path();
- ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None }
+ ImageRead {
+ blob,
+ map: vectorcraft_geom::Homography::from_affine(Affine::IDENTITY),
+ size: (size, size),
+ area: None,
+ clip: Some(vec![(bp, FillRule::NonZero)]),
+ colorize: None,
+ }
}
/// The reads of one image inside clip groups share the work limit: three reads of a 64 px
diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs
index cc5c7f4dce..cf46d853d8 100644
--- a/crates/engine/src/cmd/scripts.rs
+++ b/crates/engine/src/cmd/scripts.rs
@@ -32,7 +32,7 @@ pub fn specs() -> Vec {
"Run Script",
[],
None,
- "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above",
+ "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above",
always,
run
),
diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs
index f1e47b889a..daba176fb3 100644
--- a/crates/engine/src/cmd/stroke.rs
+++ b/crates/engine/src/cmd/stroke.rs
@@ -445,7 +445,7 @@ impl Session {
/// selection's stroke.
pub fn shown_stroke(&self) -> Option {
let st = self.active()?;
- if self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
+ if self.bucket_paints() {
return Some(self.new_art_stroke());
}
if let Some(part) = st.selected_symbol_part() {
diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs
index 76003551cd..511352b9a5 100644
--- a/crates/engine/src/cmd/swatch.rs
+++ b/crates/engine/src/cmd/swatch.rs
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent};
use vectorcraft_doc::pattern::pattern_paint;
use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, map_node_solid_paints, node_colors};
-use vectorcraft_doc::{Document, NodeId};
+use vectorcraft_doc::{Document, NodeId, Selection};
use super::paint::paint_from;
use super::{
@@ -77,7 +77,7 @@ pub fn specs() -> Vec {
"Add Used Colors",
["Window", "Swatches"],
None,
- "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step → {added: [names], linked}",
+ "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step (none when there is no new color; the Swatches panel menu's Add Selected Colors sends selection and global; with Global Edit on, the other members keep their colors) → {added: [names], linked}",
has_doc,
swatch_add_used
),
@@ -1037,20 +1037,41 @@ fn swatch_sort(s: &mut Session, _: &Value) -> Result {
ok()
}
+/// The colors of the art `ids` that no swatch links them to and no solid swatch has, each once, in
+/// paint order: the swatches Add Used Colors makes.
+fn new_used_colors(d: &Document, ids: &[NodeId]) -> Vec {
+ let (mut linked_to, mut colors) = (vec![], vec![]);
+ artwork_colors(d, ids, false, &mut linked_to, &mut colors);
+ // Colors a solid swatch already has are skipped.
+ let have: HashSet = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect();
+ colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k)));
+ colors
+}
+
fn swatch_add_used(s: &mut Session, p: &Value) -> Result {
const C: &str = "swatch.addUsedColors";
let global = switch_or(p, "global", false, C)?;
let only_selection = switch_or(p, "selection", false, C)?;
- let (added, linked) = s.edit("Add Used Colors", |d, sel| {
+ let used_ids = |d: &Document, sel: &Selection| -> Result> {
let ids: Vec = if only_selection { sel.objects.clone() } else { d.layers.iter().map(|l| l.id).collect() };
if only_selection && ids.is_empty() {
return Err(bad(C, "select artwork to add its colours"));
}
- let (mut linked_to, mut colors) = (vec![], vec![]);
- artwork_colors(d, &ids, false, &mut linked_to, &mut colors);
- // Colours a solid swatch already has are skipped.
- let have: HashSet = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect();
- colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k)));
+ Ok(ids)
+ };
+ // Typing in progress is its own undo step and is in the document the colors are read from.
+ super::variablecmds::settle_typing(s)?;
+ // With no new color there is nothing to add or link, so no edit and no undo step.
+ let st = s.doc()?;
+ if new_used_colors(&st.doc, &used_ids(&st.doc, &st.selection)?).is_empty() {
+ return Ok(json!({"added": [], "linked": 0}));
+ }
+ // Linking a paint to its new swatch keeps its color, so Global Edit gives the link to no other
+ // member: a member whose color differs keeps it.
+ let global_edit = s.doc_mut()?.global_edit.take();
+ let edited = s.edit("Add Used Colors", |d, sel| {
+ let ids = used_ids(&*d, &*sel)?;
+ let colors = new_used_colors(d, &ids);
let mut free = d.free_swatch_names();
let mut links = vec![];
for c in colors {
@@ -1060,7 +1081,9 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result {
}
let linked = if global { link_colors(d, &ids, &links) } else { 0 };
Ok((links.into_iter().map(|(_, n)| n).collect::>(), linked))
- })?;
+ });
+ s.doc_mut()?.global_edit = global_edit;
+ let (added, linked) = edited?;
Ok(json!({"added": added, "linked": linked}))
}
diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs
index f50a2c7364..185baf734f 100644
--- a/crates/engine/src/cmd/typecmd.rs
+++ b/crates/engine/src/cmd/typecmd.rs
@@ -122,7 +122,7 @@ pub fn specs() -> Vec {
"Move Type Path Handle",
[],
None,
- "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
+ "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
has_doc,
set_path_handle
),
@@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result {
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let independent = switch_or(p, "independent", false, C)?;
+ let symmetric = switch_or(p, "symmetric", false, C)?;
+ if symmetric && independent {
+ return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
+ }
let node = s.doc()?.doc.node(id);
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
@@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result {
let within = |t: &TextObject| {
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
};
- if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
+ if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) {
t.kind = before;
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs
index c592e552a4..cdf1d441cd 100644
--- a/crates/engine/src/cmd/xform.rs
+++ b/crates/engine/src/cmd/xform.rs
@@ -21,7 +21,7 @@ pub fn specs() -> Vec {
"Free Distort",
[],
None,
- "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
+ "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
has_doc,
distort
),
@@ -86,6 +86,15 @@ impl Projective {
Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() }
}
+ /// Whether `p` maps in front of the warp's horizon, on the side the box's own corners are.
+ fn in_front(&self, p: Point) -> bool {
+ let [.., g, h] = self.m;
+ let p = self.pre * p;
+ let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 };
+ let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 };
+ g * u + h * v + 1.0 > 1e-9
+ }
+
pub fn apply(&self, p: Point) -> Point {
let [a, b, c, d, e, f, g, h] = self.m;
let p = self.pre * p;
@@ -138,6 +147,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option {
// A clip group is bounded by its clip path.
NodeKind::Group { children, clip: true } => warp_children(children, pr, |i| i == 0),
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => warp_children(children, pr, |i| i >= skip),
+ // An image's corners follow the warp exactly ([`Node::set_image_corners`]); [`distort`]
+ // has checked that they stay convex.
+ NodeKind::Image(_) => {
+ let b = n.geometric_bounds();
+ if let Some(q) = n.image_corners() {
+ let _ = n.set_image_corners(q.map(|p| pr.apply(p)));
+ }
+ b
+ }
_ => {
// No editable points: the affine approximation (which maps the gradients too).
let b = n.geometric_bounds();
@@ -157,6 +175,21 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option {
before
}
+/// Whether the warp from `src` to `q` ([`Projective::from_box`]) takes the corners of `src` to `q`,
+/// within a millionth of `q`'s shortest side plus the rounding error of coordinates as far from `q`'s
+/// first corner as the others. The warp is solved and measured with `src` and `q` moved to the
+/// origin, so coordinates far from it do not widen the allowance.
+fn reaches_corners(src: OrientedBox, q: [Point; 4]) -> bool {
+ let origin = q[0].to_vec2();
+ let q = q.map(|p| p - origin);
+ let src = OrientedBox { rect: src.rect - src.rect.origin().to_vec2(), ..src };
+ let pr = Projective::from_box(src, q);
+ let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
+ let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
+ let tol = side * 1e-6 + far * 1e-12;
+ side.is_finite() && side > 0.0 && src.corners().iter().zip(q).all(|(c, want)| pr.apply(*c).distance(want) <= tol)
+}
+
/// Warps each of `children` and returns the union of the pre-warp bounds of those `counts` picks
/// by index.
fn warp_children(children: &mut [Arc], pr: &Projective, counts: impl Fn(usize) -> bool) -> Option {
@@ -166,6 +199,76 @@ fn warp_children(children: &mut [Arc], pr: &Projective, counts: impl Fn(us
})
}
+/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
+/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
+/// why.
+fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
+ if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
+ if !q.iter().all(|p| pr.in_front(*p)) {
+ return Some((n.id, Unwarpable::Horizon));
+ }
+ if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
+ return Some((
+ n.id,
+ match e {
+ vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
+ vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
+ },
+ ));
+ }
+ }
+ warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
+}
+
+/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
+/// masks).
+fn first_image(n: &Node) -> Option {
+ if matches!(n.kind, NodeKind::Image(_)) {
+ return Some(n.id);
+ }
+ warped_parts(n).into_iter().find_map(first_image)
+}
+
+/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
+/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
+/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
+fn warped_parts(n: &Node) -> Vec<&Node> {
+ let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
+ let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
+ let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
+ let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
+ children.chain(mask).collect()
+}
+
+/// The error of `command` on image `id`, which is distorted (Perspective Distort or Free Distort)
+/// in a way the command cannot keep.
+pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) -> EngineError {
+ bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
+}
+
+/// Why an image cannot follow the corners of a distort.
+#[derive(Clone, Copy)]
+enum Unwarpable {
+ /// Its corners would fold over, meet or fall on one line.
+ NotConvex,
+ /// A corner would cross the warp's horizon.
+ Horizon,
+ /// Its corners would be too close together for a perspective map to place them.
+ TooNarrow,
+}
+
+/// The error of `object.distort` when image `id` cannot follow its corners.
+fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
+ const C: &str = "object.distort";
+ match why {
+ Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
+ Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
+ Unwarpable::TooNarrow => {
+ bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
+ }
+ }
+}
+
fn distort(s: &mut Session, p: &Value) -> Result {
const C: &str = "object.distort";
// All four corners or nothing, each exactly [x, y]: nothing malformed is left out.
@@ -208,6 +311,26 @@ fn distort(s: &mut Session, p: &Value) -> Result {
return Ok(ids_json);
}
let pr = Projective::from_box(src, [tl, tr, br, bl]);
+ // An image's corners follow the handles exactly, so they must stay a convex shape: nothing
+ // changes when one would not.
+ let doc = &s.doc()?.doc;
+ // Corners that do not make a convex shape give no perspective map (the warp falls back to an
+ // affine one), so an image cannot follow them.
+ if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
+ && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
+ {
+ return Err(unwarpable_error(id, Unwarpable::NotConvex));
+ }
+ // Corners so close together that the map falls back to an affine one: the box's corners do
+ // not reach the handles, so an image cannot follow them either.
+ if !reaches_corners(src, [tl, tr, br, bl])
+ && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
+ {
+ return Err(unwarpable_error(id, Unwarpable::TooNarrow));
+ }
+ if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
+ return Err(unwarpable_error(id, why));
+ }
s.edit("Free Distort", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs
index 82e090a3ef..69194eba00 100644
--- a/crates/engine/src/command_sets.rs
+++ b/crates/engine/src/command_sets.rs
@@ -105,6 +105,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[
"symbol.selectInstances",
"view.guides.lock",
"view.proofSetup",
+ "view.proofSetup.load",
"view.proofColors",
"view.overprintPreview",
"view.separationsPreview",
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 83692ece54..ae757823c9 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -74,6 +74,10 @@ pub struct Session {
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
/// back as it was at the release ([`Session::pointer`]).
pub(crate) lender: Option>,
+ /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
+ /// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
+ /// colors the bucket paints with ([`Session::bucket_paints`]).
+ pub(crate) back_to_bucket: bool,
/// Pointer and key input that came while the tool computed an edit on another thread, each with
/// its number and view, made in order once the edit is applied.
held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>,
@@ -192,6 +196,11 @@ pub struct Session {
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
new_doc_profile_dir: Option,
+ /// The folder of the proof setups `view.proofSetup.save` saves by name and View → Proof Setup
+ /// lists; `None`: no folder ([`Session::attach_proof_setups`]).
+ proof_setup_dir: Option,
+ /// How many proof setup files `view.proofSetup.save` wrote ([`Session::proof_setup_saves`]).
+ proof_setup_saves: u64,
/// The folder of each script's data folder (`Folder.userData`), beside which the grants file
/// keeps the file access people allowed scripts; `None`: no folder
/// ([`Session::attach_script_data`]).
@@ -327,6 +336,9 @@ pub struct Session {
/// The id and persistent options of the tool when the press under way began, which a dropped
/// press puts back ([`Session::drop_tool_press`]).
pub(crate) press_options: Option<(String, serde_json::Map)>,
+ /// An option of the active tool was set during the press under way, which stored all of its
+ /// options, so a dropped press stores the options it puts back.
+ pub(crate) press_options_stored: bool,
/// The engine saves the selection and active layer before a Type press and restores them if it drops.
pub(crate) press_type_selection: Option<(Selection, Option)>,
/// The freeform gradient point selected once the tool took the press under way, which a
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
index 0bf8203463..2e0d0f9fe4 100644
--- a/crates/engine/src/prefs.rs
+++ b/crates/engine/src/prefs.rs
@@ -283,6 +283,11 @@ pub struct Prefs {
pub low_res_proxy_eps: bool,
pub anti_aliased_bitmaps: bool,
pub update_links: String,
+ /// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
+ /// becomes when the open or place does not say (`text`: editable type in the file's fonts;
+ /// `outlines`: the glyph outlines the file draws). The Import PDF dialog starts from it and
+ /// keeps the choice it confirms.
+ pub pdf_text_as: String,
// Clipboard Handling
pub copy_as_svg: bool,
pub copy_as_pdf: bool,
@@ -589,6 +594,7 @@ impl Default for Prefs {
low_res_proxy_eps: false,
anti_aliased_bitmaps: false,
update_links: s("askWhenModified"),
+ pdf_text_as: s("text"),
copy_as_svg: true,
copy_as_pdf: false,
copy_aicb: false,
diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs
index d811da6e2e..0e702c0076 100644
--- a/crates/engine/src/script/mod.rs
+++ b/crates/engine/src/script/mod.rs
@@ -168,6 +168,8 @@ pub fn refused_to_scripts(id: &str) -> bool {
"color.removeProfile",
"file.print",
"view.proofSetup",
+ "view.proofSetup.save",
+ "view.proofSetup.load",
"view.proofColors",
"view.overprintPreview",
"view.separationsPreview",
diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs
index 985d13edf2..d530d587b5 100644
--- a/crates/engine/src/session/documents.rs
+++ b/crates/engine/src/session/documents.rs
@@ -55,6 +55,7 @@ impl Session {
histories_seen: None,
tool: vectorcraft_tools::create("selection"),
lender: None,
+ back_to_bucket: false,
held_input: Default::default(),
input_count: 0,
edit_started_by: None,
@@ -100,6 +101,8 @@ impl Session {
scripts_dir: None,
metadata_templates_dir: None,
new_doc_profile_dir: None,
+ proof_setup_dir: None,
+ proof_setup_saves: 0,
script_data_dir: None,
plugin_output: None,
plugin_install_approval: None,
@@ -136,6 +139,7 @@ impl Session {
plane_widget_press: false,
pointer_held: false,
press_options: None,
+ press_options_stored: false,
press_type_selection: None,
press_point: None,
ruler_guide: None,
diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs
index ea697a0525..bbd20fa5bb 100644
--- a/crates/engine/src/session/edit.rs
+++ b/crates/engine/src/session/edit.rs
@@ -323,7 +323,7 @@ impl Session {
}
// While the Live Paint Bucket is active, paint previews change only the bucket's colors, so
// each preview starts from the colors the interaction began with.
- let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
+ let bucket = self.bucket_paints();
let (paint, restore_paint) = {
let menu = self.menu.clone();
let st = self.doc_mut()?;
@@ -485,7 +485,7 @@ impl Session {
self.pending_paint = None;
// While the Live Paint Bucket is active, a previewed color is the bucket's color, which the
// cancel puts back as well.
- let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
+ let bucket = self.bucket_paints();
if let Some(paint) = self
.active()
.and_then(|st| st.interaction.as_ref())
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 815a33eeae..b74d501308 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -202,12 +202,14 @@ mod symbol_nine_slice;
mod symbolbounds;
mod symboledit;
mod symbolism_options;
+mod symbolism_shift;
mod symbollib;
mod tangent_line;
mod targeting;
mod textcombos;
mod textedit;
pub(super) mod textimport;
+mod three_point_arc;
mod tileedge;
mod tints;
mod toolsettings;
diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs
index 876f9115ed..090c28e988 100644
--- a/crates/engine/src/tests/brushlib.rs
+++ b/crates/engine/src/tests/brushlib.rs
@@ -112,7 +112,9 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"calligraphic-nibs",
"pressure-sensitive",
"bristle-brushes",
+ "paint",
"pattern-borders",
+ "decorative",
"scatter-shapes",
"stipple",
"game-trails",
@@ -121,10 +123,25 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"tech-circuit",
"engraving",
"arrows",
- "image-brush"
+ "image-brush",
+ "artistic"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
+ // None of them is a default brush.
+ let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
+ for id in ids {
+ let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
+ assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
+ }
+ assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
+}
+
+#[test]
+fn the_builtin_libraries_list_their_brush_names_and_counts() {
+ let mut s = Session::new();
+ let list = run(&mut s, "brush.libraries", json!({}));
+ let libs = list["libraries"].as_array().unwrap();
// Looked up by id, so a library added to the list does not shift these checks.
let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap();
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
@@ -133,6 +150,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"]
);
assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5));
+ assert_eq!((entry("decorative")["name"].as_str(), entry("decorative")["count"].as_u64()), (Some("Decorative"), Some(4)));
let trails = run(&mut s, "brush.library", json!({"library": "game-trails"}));
assert_eq!(
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(),
@@ -162,6 +180,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
assert_eq!(strs(&added["added"]), ["Laser Bolt"]);
+}
+
+#[test]
+fn every_builtin_library_brush_has_its_kind_and_draws() {
+ let s = Session::new();
// One kind of brush per library (Ink and Wash: art brushes and a calligraphic one), every
// brush drawing something.
for (id, kind) in [
@@ -170,7 +193,9 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("calligraphic-nibs", "calligraphic"),
("pressure-sensitive", "art"),
("bristle-brushes", "bristle"),
+ ("paint", "art"),
("pattern-borders", "pattern"),
+ ("decorative", "pattern"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
("game-trails", "art"),
@@ -178,6 +203,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("dry-media", "art"),
("arrows", "art"),
("image-brush", "scatter"),
+ ("artistic", "art"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
@@ -191,6 +217,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &stroke).is_empty(), "{} draws nothing", b.name);
}
}
+}
+
+#[test]
+fn builtin_library_brushes_bring_the_resources_their_art_uses() {
+ let s = Session::new();
// The resources their art uses come with them: Striped Ribbon's pattern, Sparkles' symbol.
let (_, ribbons) = cmd::brushlib::library(&s, "art-ribbons").unwrap();
assert_eq!(art_patterns(ribbons.brush("Striped Ribbon").unwrap()), ["Pinstripes"]);
@@ -199,13 +230,46 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let BrushKind::Scatter(sparkles) = &shapes.brush("Sparkles").unwrap().kind else { panic!("not a scatter brush") };
assert!(matches!(&sparkles.art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Sparkle"));
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
- // None of them is a default brush.
- let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
- for id in ids {
- let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
- assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
+}
+
+#[test]
+fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
+ let mut s = session();
+ let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap();
+ let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap();
+ assert_eq!(alias.brushes, lib.brushes);
+ assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic");
+ let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"];
+ assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names);
+ let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap();
+ let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0);
+ for b in &lib.brushes {
+ let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
+ assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name);
+ for path in [line_to(180.0), line_to(1.0)] {
+ assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name);
+ }
+ // The art is black, so with Tints every path takes the stroke color itself.
+ let mut fills = vec![];
+ for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) {
+ piece.walk(&mut |n| {
+ if n.path_data().is_some() {
+ fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb()));
+ }
+ });
+ }
+ let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5);
+ assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name);
+ let before = undo_len(&s);
+ let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]}));
+ assert_eq!(strs(&added["added"]), [b.name.as_str()]);
+ assert_eq!(added["applied"], json!([line]));
+ assert_eq!(undo_len(&s), before + 1);
}
- assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
+ let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
+ let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
+ let reopened = vectorcraft_format::load(&bytes).unwrap();
+ assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
@@ -245,6 +309,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
assert_eq!(reopened.images, lib.doc.images);
}
+#[test]
+fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() {
+ let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
+ vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]);
+ let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
+ let mut s = session();
+ let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"}));
+ assert_eq!(loaded["name"], "Artistic");
+ let id = loaded["library"].as_str().unwrap();
+ assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id);
+ assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id);
+ assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works");
+ // A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id.
+ let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"}));
+ assert_eq!(full["name"], "Artistic Brushes");
+ let full_id = full["library"].as_str().unwrap();
+ assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic");
+ assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id);
+}
+
/// Every path of brush art `n`: (anchors, opacity).
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
let mut out = vec![];
@@ -498,6 +582,41 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
+#[test]
+fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
+ let mut s = session();
+ let (_, lib) = cmd::brushlib::library(&s, "Decorative").unwrap();
+ let names = ["Leaf Vine", "Blossom Chain", "Pennant Garland", "Lantern String"];
+ assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names);
+ let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
+ let mut signatures = std::collections::HashSet::new();
+ for b in &lib.brushes {
+ let BrushKind::Pattern(pattern) = &b.kind else { panic!("{} is not a pattern brush", b.name) };
+ assert_eq!(pattern.colorization, vectorcraft_brush::Colorization::Tints);
+ let points = |len: f64| anchors(&vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(len), &black_stroke()).iter().collect::>());
+ let (one, four) = (points(48.0), points(192.0));
+ assert!(!one.is_empty() && four.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
+ // A path four tiles long places the motif four times, each copy one tile further along.
+ assert_eq!(four.len(), 4 * one.len(), "{} repeats its motif", b.name);
+ for (i, p) in four.iter().enumerate() {
+ let q = one[i % one.len()];
+ let shift = 48.0 * (i / one.len()) as f64;
+ assert!((p.x - q.x - shift).abs() < 1e-3 && (p.y - q.y).abs() < 1e-3, "{} copy {} at {p:?}, not {q:?}", b.name, i / one.len());
+ }
+ signatures.insert(one.iter().map(|p| ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)).collect::>());
+ let before = undo_len(&s);
+ let applied = run(&mut s, "brush.addFromLibrary", json!({"library": "decorative", "name": b.name, "apply": true, "ids": [path]}));
+ assert_eq!((strs(&applied["added"]), &applied["applied"]), (vec![b.name.as_str()], &json!([path])));
+ assert_eq!(undo_len(&s), before + 1);
+ assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
+ }
+ assert_eq!(signatures.len(), names.len(), "each design produces a different repeating shape");
+ let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
+ let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
+ let reopened = vectorcraft_format::load(&bytes).unwrap();
+ assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
+}
+
#[test]
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
@@ -544,6 +663,37 @@ fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_librar
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
+#[test]
+fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() {
+ let mut s = session();
+ let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap();
+ let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"];
+ assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names);
+ let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
+ let mut curve = line_to(20.0);
+ curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
+ for b in &lib.brushes {
+ let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
+ assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
+ assert_eq!(art.width, 150.0);
+ for line in [line_to(2.0), line_to(180.0), curve.clone()] {
+ let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
+ let points = anchors(&pieces.iter().collect::>());
+ assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
+ }
+ let before = undo_len(&s);
+ let added = run(&mut s, "brush.addFromLibrary", json!({"library": "paint", "name": b.name, "apply": true, "ids": [path]}));
+ assert_eq!(strs(&added["added"]), [b.name.as_str()]);
+ assert_eq!(added["applied"], json!([path]));
+ assert_eq!(undo_len(&s), before + 1);
+ assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
+ }
+ let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
+ let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
+ let reopened = vectorcraft_format::load(&bytes).unwrap();
+ assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
+}
+
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
/// translucent washes, with names of their own and a few paths of art each.
#[test]
diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs
index 9d1447adb8..158bb02c87 100644
--- a/crates/engine/src/tests/build.rs
+++ b/crates/engine/src/tests/build.rs
@@ -3331,6 +3331,68 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() {
assert!(failed.is_empty(), "{failed:#?}");
}
+/// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient,
+/// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient
+/// fitted to each object has no aspect of its own. Named objects still take the aspect.
+#[test]
+fn edit_gradient_aspect_without_objects_is_an_error() {
+ let aspect = |n: &Node| match n.appearance.fill_paint() {
+ Paint::Gradient(g) => g.geom.map(|x| x.aspect),
+ _ => None,
+ };
+ let mut s = session();
+ let g = live(&mut s);
+ let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
+ s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap();
+ s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
+ s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap();
+ let (group, art, fill) = (node(&s, g), node(&s, rect), s.paint.fill.clone());
+ let steps = s.doc().unwrap().history.undo.len();
+ assert!(!s.gradient_edit_has_objects(false), "the bucket edits its own gradient");
+ for params in [json!({"stroke": false, "aspect": 50}), json!({"stroke": false, "aspect": 50, "reverse": true})] {
+ assert!(s.execute("paint.editGradient", ¶ms).is_err(), "{params}");
+ assert_eq!(s.paint.fill, fill, "{params}: the bucket's gradient stays");
+ }
+ assert_eq!((node(&s, g), node(&s, rect)), (group, art), "the selection keeps its paint");
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
+ // Named objects take it.
+ s.execute("paint.editGradient", &json!({"stroke": false, "kind": "radial", "aspect": 50, "ids": [rect.0]})).unwrap();
+ assert_eq!(aspect(&node(&s, rect)), Some(0.5));
+ // Without the bucket and with nothing selected, the default gradient has no aspect either.
+ s.select_tool("selection", ViewInfo::default()).unwrap();
+ s.execute("select.set", &json!({"ids": []})).unwrap();
+ let fill = s.paint.fill.clone();
+ assert!(!s.gradient_edit_has_objects(false));
+ assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
+ assert_eq!(s.paint.fill, fill, "the default gradient stays");
+ // An empty group has nothing to paint.
+ let empty = s
+ .edit("Group", |d, _| {
+ let id = d.alloc_id();
+ d.insert(d.default_layer(), 0, Node::group(id, vec![]))?;
+ Ok(id)
+ })
+ .unwrap();
+ s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
+ assert!(!s.gradient_edit_has_objects(false), "an empty group");
+ assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
+ // A fill edit of a Live Paint group with edges and no faces edits no object; a stroke edit edits its edges.
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
+ let (fill, group, steps) = (s.paint.fill.clone(), node(&s, edges_only), s.doc().unwrap().history.undo.len());
+ assert!(!s.gradient_edit_has_objects(false), "a Live Paint group without faces");
+ assert!(s.gradient_edit_has_objects(true), "its edges take a stroke edit");
+ assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
+ assert_eq!((&s.paint.fill, node(&s, edges_only)), (&fill, group), "the default and the group stay");
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
+ // A selected object takes it.
+ s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
+ assert!(s.gradient_edit_has_objects(false) && s.gradient_edit_has_objects(true));
+ s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 25})).unwrap();
+ assert_eq!(aspect(&node(&s, rect)), Some(0.25));
+}
+
/// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush
/// still goes to the selection.
#[test]
@@ -3372,6 +3434,65 @@ fn live_paint_bucket_gradient_preset_and_sampled_stop_follow_the_active_proxy()
assert_eq!(node(&s, rect), art, "the selection keeps its paint");
}
+/// The Gradient panel's eyedropper, used on a stop of the Live Paint Bucket's gradient, samples the
+/// color clicked into that stop of the bucket's fill, and the selection keeps its paint. A Cmd-click
+/// with the bucket, or with the Eyedropper armed for it, which the selection tool takes, leaves the
+/// bucket's colors as they were.
+#[test]
+fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_click() {
+ let v = ViewInfo::default();
+ let click = |s: &mut Session, mods: Mods| {
+ for kind in [PointerKind::Down, PointerKind::Up] {
+ s.pointer(&PointerEvent::new(kind, 320.0, 320.0).with_mods(mods), v).unwrap();
+ }
+ };
+ let mut s = session();
+ live(&mut s);
+ let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
+ s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
+ s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
+ s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
+ s.select_tool("livePaintBucket", v).unwrap();
+ s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap();
+ s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
+ let art = node(&s, rect);
+ // The panel's eyedropper (`stop_eyedropper`): the Eyedropper, set to switch back to the bucket.
+ s.select_tool("eyedropper", v).unwrap();
+ s.set_tool_option("stop", &json!("livePaintBucket"));
+ assert_eq!(s.selected_stop(), Some(1), "the bucket's stop stays selected for the pick");
+ // A Cmd-click while the pick is armed selects the rectangle and leaves the bucket's gradient.
+ let fill = s.paint.fill.clone();
+ s.execute("select.set", &json!({"ids": []})).unwrap();
+ click(&mut s, Mods { cmd: true, ..Mods::default() });
+ assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click");
+ assert_eq!((s.paint.fill.clone(), s.selected_stop()), (fill, Some(1)), "the bucket's fill and stop stay");
+ click(&mut s, Mods::default());
+ let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") };
+ assert_eq!(g.gradient.stops[1].color, Color::from_hex("#00ff00").unwrap(), "the sampled stop");
+ assert_eq!(node(&s, rect), art, "the selection keeps its paint");
+ // A Cmd-click selects the rectangle; the bucket keeps its gradient.
+ s.select_tool("livePaintBucket", v).unwrap();
+ let fill = s.paint.fill.clone();
+ s.execute("select.set", &json!({"ids": []})).unwrap();
+ click(&mut s, Mods { cmd: true, ..Mods::default() });
+ assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click");
+ assert_eq!(s.paint.fill, fill, "the bucket's fill stays");
+ // Armed again, a Cmd-click on another object deselects the stop; the next click (a Shift-click,
+ // which would sample a color) ends the pick and leaves the bucket's gradient.
+ let other = self::rect(&mut s, 400.0, 400.0, 40.0, 40.0);
+ s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
+ s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
+ s.select_tool("eyedropper", v).unwrap();
+ s.set_tool_option("stop", &json!("livePaintBucket"));
+ for mods in [Mods { cmd: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() }] {
+ for kind in [PointerKind::Down, PointerKind::Up] {
+ s.pointer(&PointerEvent::new(kind, 420.0, 420.0).with_mods(mods), v).unwrap();
+ }
+ }
+ assert_eq!(s.doc().unwrap().selection.objects, vec![other], "the Cmd-click selected the other object");
+ assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample");
+}
+
/// A gradient stop selected on the selection's gradient is not selected once the Live Paint
/// Bucket is active (its proxies show the default paint), and one selected on the bucket's
/// gradient is not selected once another tool is chosen.
@@ -9429,9 +9550,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() {
assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25));
// Bad dividers are refused and change nothing.
let steps = s.doc().unwrap().history.undo.len();
- for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] {
+ for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] {
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
}
+ // A null divider with another view is refused too, and the view stays.
+ assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err());
+ assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split);
assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25));
for edge in [0.0, 1.0] {
s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap();
diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs
index dbc2a0bdeb..3e64f1557d 100644
--- a/crates/engine/src/tests/colormgmt.rs
+++ b/crates/engine/src/tests/colormgmt.rs
@@ -318,6 +318,45 @@ fn convert_query_and_intents() {
assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err());
}
+/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color;
+/// a CMYK color's display color, not its naive separation, sets them.
+#[test]
+fn convert_to_oklch_answers_lightness_chroma_and_hue() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let mut s = session();
+ let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap();
+ assert_eq!(r["model"], "oklch");
+ let v: Vec = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}");
+ let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]);
+ assert!(!lowered);
+ assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000");
+ assert_eq!(r["hex"], "#ff0000");
+ let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap();
+ assert_eq!(gray["values"][2], 0.0, "{gray}");
+ let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0});
+ let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap();
+ let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
+ let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
+ let c: Vec = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ let got = [c[0] / 100.0, c[1], c[2]];
+ assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}");
+ assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}");
+ // A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB.
+ let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap();
+ let w: Vec = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0));
+ let clipped = vectorcraft_color::oklab::to_oklch(shown);
+ assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}");
+ assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}");
+ assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}");
+ // RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white.
+ let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap();
+ assert_eq!(past["hex"], "#ffffff");
+ let l = past["values"][0].as_f64().unwrap();
+ assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
+}
+
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
@@ -720,6 +759,235 @@ fn proof_setup_takes_the_custom_proof_settings() {
assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws");
}
+/// A custom proof setup saved to a file loads back as the same setup with Proof Colors on; saving
+/// leaves the proof view as it is, and `view.proofSetup.read` only reads the file.
+#[test]
+fn a_saved_proof_setup_loads_back() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let _v = DefaultView::new();
+ let dir = vectorcraft_testkit::TempDir::new("proof-setup-file");
+ let path = dir.join("press.vcproof").to_string_lossy().to_string();
+ let mut s = session();
+ let device = format!("cmyk:{}", cms::GENERIC_CMYK);
+ let r = s
+ .execute(
+ "view.proofSetup.save",
+ &json!({"path": path, "target": device, "intent": "perceptual", "preserveNumbers": true, "simulateBlack": true}),
+ )
+ .unwrap();
+ assert_eq!((r["path"].as_str(), r["target"].as_str(), r["intent"].as_str()), (Some(path.as_str()), Some(device.as_str()), Some("perceptual")));
+ assert_eq!(vectorcraft_render::proof::view(), Default::default(), "saving leaves the proof view alone");
+ let text = std::fs::read_to_string(&path).unwrap();
+ assert!(text.contains("\"format\": \"vectorcraft-proof-setup\"") && text.contains("\"version\": 1"), "{text}");
+ let r = s.execute("view.proofSetup.read", &json!({"path": path})).unwrap();
+ assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(device.as_str()), Some(true), Some(true)));
+ assert_eq!(vectorcraft_render::proof::view(), Default::default(), "reading changes nothing");
+ assert!(!crate::waits_for_tool_edit("view.proofSetup.read"), "reading does not finish a tool's edit");
+ let rev = s.doc().unwrap().revision;
+ let r = s.execute("view.proofSetup.load", &json!({"path": path})).unwrap();
+ assert_eq!((r["proofColors"].as_bool(), r["path"].as_str()), (Some(true), Some(path.as_str())));
+ let v = vectorcraft_render::proof::view();
+ assert!(v.proof_colors);
+ let want = ProofSetup {
+ target: ProofTarget::Cmyk(cms::GENERIC_CMYK.into()),
+ intent: Intent::Perceptual,
+ simulate_paper: false,
+ preserve_numbers: true,
+ simulate_black: true,
+ ..Default::default()
+ };
+ assert_eq!(v.setup, want);
+ assert!(s.doc().unwrap().revision > rev, "the canvas redraws");
+ // Saved from the current setup, the file holds that setup: the round trip keeps every field.
+ let again = dir.join("again.vcproof").to_string_lossy().to_string();
+ s.execute("view.proofSetup.save", &json!({"path": again, "simulatePaper": true})).unwrap();
+ s.execute("view.proofSetup", &json!({"target": "workingCmyk"})).unwrap();
+ s.execute("view.proofSetup.load", &json!({"path": again})).unwrap();
+ assert_eq!(vectorcraft_render::proof::view().setup, ProofSetup { simulate_paper: true, ..want });
+}
+
+/// Saving refuses a target that is not a device, bad params, a bad name and a file larger than
+/// loading reads; loading refuses a file
+/// that is too large, not a proof setup, newer, or whose device is a profile that is not loaded,
+/// and the proof view stays as it was.
+#[test]
+fn proof_setup_files_refuse_what_they_cannot_use() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let _v = DefaultView::new();
+ let dir = vectorcraft_testkit::TempDir::new("proof-setup-refused");
+ let file = |n: &str| dir.join(n).to_string_lossy().to_string();
+ let mut s = session();
+ let path = file("a.vcproof");
+ refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "protanopia"}), "`protanopia` is not a device to simulate");
+ refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "rgb:Nope"}), "unknown RGB profile `Nope`");
+ refused(&mut s, "view.proofSetup.save", json!({"path": path, "simulateBlack": "yes"}), "`simulateBlack` must be true or false");
+ refused(&mut s, "view.proofSetup.save", json!({}), "missing `path` or `name`");
+ refused(&mut s, "view.proofSetup.save", json!({"path": path, "name": "x"}), "not both");
+ refused(&mut s, "view.proofSetup.save", json!({"path": " "}), "`path` is empty");
+ refused(&mut s, "view.proofSetup.save", json!({"name": "x"}), "need the preferences folder");
+ assert!(!std::path::Path::new(&path).exists(), "nothing is written");
+ s.attach_proof_setups(dir.join("Proof Setups"));
+ for bad_name in ["", " ", "../up", "a/b", "a\\b", ".hidden", "c:d"] {
+ refused(&mut s, "view.proofSetup.save", json!({"name": bad_name}), "`name`");
+ }
+ refused(&mut s, "view.proofSetup.save", json!({"name": "x".repeat(101)}), "longer than 100 characters");
+ // A device whose name makes the file larger than load reads is refused, and nothing is written.
+ let long = "Long Profile Name ".repeat(4000);
+ cms::register_icc(&cms::icc_bytes(cms::DISPLAY_P3).unwrap(), Some(long.clone())).unwrap();
+ let refusal = s.execute("view.proofSetup.save", &json!({"path": path, "target": format!("rgb:{long}")}));
+ cms::unregister_icc(&long);
+ assert!(refusal.unwrap_err().to_string().contains("larger than 65536 bytes"), "a setup load can't read is refused");
+ assert!(!std::path::Path::new(&path).exists(), "nothing is written");
+ let before = vectorcraft_render::proof::view();
+ let write = |n: &str, text: &str| {
+ let p = file(n);
+ std::fs::write(&p, text).unwrap();
+ p
+ };
+ let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#;
+ let cases = [
+ (write("big.vcproof", &format!("{ok}{}", " ".repeat(64 << 10))), "larger than 65536 bytes"),
+ (write("junk.vcproof", "not json"), "not a proof setup file"),
+ (write("other.vcproof", r#"{"format": "other", "version": 1}"#), "not a VectorCraft proof setup file"),
+ (write("newer.vcproof", &ok.replace("\"version\": 1", "\"version\": 2")), "made by a newer VectorCraft"),
+ (write("missing.vcproof", &ok.replace("workingCmyk", "cmyk:Not Loaded")), "the CMYK profile `Not Loaded`, which is not loaded"),
+ (write("blind.vcproof", &ok.replace("workingCmyk", "deuteranopia")), "not a device to simulate"),
+ (write("intent.vcproof", &ok.replace("relative", "vivid")), "unknown intent `vivid`"),
+ (write("flag.vcproof", &ok.replace("}", r#", "simulatePaper": 1}"#)), "`simulatePaper` must be true or false"),
+ ];
+ for (p, msg) in cases {
+ for cmd in ["view.proofSetup.load", "view.proofSetup.read"] {
+ refused(&mut s, cmd, json!({"path": p}), msg);
+ }
+ }
+ refused(&mut s, "view.proofSetup.load", json!({"path": file("gone.vcproof")}), "gone.vcproof");
+ assert_eq!(vectorcraft_render::proof::view(), before, "the proof view is unchanged");
+ // A file of the limit's size is read.
+ let padded = format!("{ok}{}", " ".repeat((64 << 10) - ok.len()));
+ s.execute("view.proofSetup.load", &json!({"path": write("limit.vcproof", &padded)})).unwrap();
+}
+
+/// Setups saved by name go in the Proof Setups folder, made on the first save, and are listed by
+/// name; other files there are left out, and a run without the folder lists none.
+#[test]
+fn proof_setups_saved_by_name_are_listed() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let _v = DefaultView::new();
+ let mut s = session();
+ assert_eq!(s.execute("view.proofSetup.list", &json!({})).unwrap(), json!({"folder": null, "setups": [], "truncated": false}));
+ let dir = vectorcraft_testkit::TempDir::new("proof-setup-list");
+ let folder = dir.join("Proof Setups");
+ s.attach_proof_setups(folder.clone());
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ assert_eq!(r["setups"], json!([]), "no folder yet: none saved");
+ let r = s.execute("view.proofSetup.save", &json!({"name": " Coated Press ", "target": format!("rgb:{}", cms::DISPLAY_P3)})).unwrap();
+ let saved = folder.join("Coated Press.vcproof");
+ assert_eq!(r["path"].as_str(), Some(saved.to_string_lossy().as_ref()));
+ s.execute("view.proofSetup.save", &json!({"name": "Bright"})).unwrap();
+ std::fs::write(folder.join("notes.txt"), "x").unwrap();
+ std::fs::create_dir(folder.join("Sub.vcproof")).unwrap();
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ let names: Vec<&str> = r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str()).collect();
+ assert_eq!(names, ["Bright", "Coated Press"]);
+ assert_eq!(r["truncated"], false);
+ s.execute("view.proofSetup.load", &json!({"name": "Coated Press"})).unwrap();
+ assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()));
+ for i in 0..101 {
+ std::fs::write(folder.join(format!("z{i:03}.vcproof")), "x").unwrap();
+ }
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (100, Some(true)));
+ assert_eq!((r["setups"][0]["name"].as_str(), r["setups"][99]["name"].as_str()), (Some("Bright"), Some("z097")), "the first 100 by name");
+}
+
+/// Other files in the Proof Setups folder, however many, do not keep its setups from the listing.
+#[test]
+fn proof_setups_are_listed_among_many_other_files() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let _v = DefaultView::new();
+ let mut s = session();
+ let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-crowded");
+ let folder = dir.join("Proof Setups");
+ std::fs::create_dir_all(&folder).unwrap();
+ for i in 0..5000 {
+ std::fs::write(folder.join(format!("a{i:04}.txt")), "").unwrap();
+ }
+ s.attach_proof_setups(folder.clone());
+ s.execute("view.proofSetup.save", &json!({"name": "Press"})).unwrap();
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (1, Some(false)));
+ assert_eq!(r["setups"][0]["name"], "Press");
+}
+
+/// The listing names only files that `name` loads (`.vcproof`, a name `save` can give), in
+/// the order of those names, and the limit keeps the first by name; a folder that can't be read is
+/// an error, not an empty listing.
+#[test]
+fn proof_setups_are_listed_by_names_that_load_them() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let _v = DefaultView::new();
+ let mut s = session();
+ let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-names");
+ let folder = dir.join("Proof Setups");
+ std::fs::create_dir_all(&folder).unwrap();
+ s.attach_proof_setups(folder.clone());
+ let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#;
+ for file in ["Press.vcproof", "Press Matte.vcproof", "Loud.VCPROOF", " Lead.vcproof"] {
+ std::fs::write(folder.join(file), ok).unwrap();
+ }
+ let names = |r: &Value| r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str().map(str::to_string)).collect::>();
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ assert_eq!((names(&r), r["truncated"].as_bool()), (vec!["Press".to_string(), "Press Matte".to_string()], Some(false)));
+ for name in names(&r) {
+ s.execute("view.proofSetup.read", &json!({ "name": name })).unwrap();
+ }
+ // `Press` and `Press Matte` compete for the last place: the first by name keeps it.
+ for i in 0..99 {
+ std::fs::write(folder.join(format!("A{i:02}.vcproof")), "x").unwrap();
+ }
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ let listed = names(&r);
+ assert_eq!((listed.len(), listed.last().map(String::as_str), r["truncated"].as_bool()), (100, Some("Press"), Some(true)));
+ // A folder that is not one can't be listed.
+ let file = dir.join("not a folder");
+ std::fs::write(&file, "x").unwrap();
+ s.attach_proof_setups(file);
+ refused(&mut s, "view.proofSetup.list", json!({}), "not a folder");
+}
+
+/// A file name that is not valid Unicode is left out of the listing, which then says it is
+/// incomplete: a path made from a lossy copy of the name would name another file.
+#[test]
+fn proof_setup_names_that_are_not_unicode_are_left_out() {
+ let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let _v = DefaultView::new();
+ let mut s = session();
+ let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-bytes");
+ let folder = dir.join("Proof Setups");
+ std::fs::create_dir_all(&folder).unwrap();
+ #[cfg(unix)]
+ let odd = {
+ use std::os::unix::ffi::OsStringExt;
+ std::ffi::OsString::from_vec(b"Odd\xff.vcproof".to_vec())
+ };
+ #[cfg(windows)]
+ let odd = {
+ use std::os::windows::ffi::OsStringExt;
+ std::ffi::OsString::from_wide(&"Odd?.vcproof".encode_utf16().map(|u| if u == u16::from(b'?') { 0xD800 } else { u }).collect::>())
+ };
+ // A file system that refuses such a name has nothing to leave out.
+ if std::fs::write(folder.join(odd), "x").is_err() {
+ return;
+ }
+ std::fs::write(folder.join("Press.vcproof"), "x").unwrap();
+ s.attach_proof_setups(folder);
+ let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
+ assert_eq!(
+ (r["setups"].as_array().map(Vec::len), r["setups"][0]["name"].as_str(), r["truncated"].as_bool()),
+ (Some(1), Some("Press"), Some(true))
+ );
+}
+
/// Whether the content has a DeviceCMYK fill/stroke operator (`c m y k k` / `K`).
fn has_cmyk_op(pdf: &str) -> bool {
let toks: Vec<&str> = pdf.split_ascii_whitespace().collect();
diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs
index 43bdf180a7..6e385cbb7e 100644
--- a/crates/engine/src/tests/dcs.rs
+++ b/crates/engine/src/tests/dcs.rs
@@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() {
assert!(marked(b), "the opaque image it overlaps");
}
+/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a
+/// distorted plate image does not stop an image replacing the group.
+#[test]
+fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() {
+ let dir = temp_dir("replace-distorted");
+ let path = write(&dir, "pic.eps", &two_plates());
+ let mut s = session();
+ let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
+ let group = r["ids"][0].clone();
+ let image = image_of(&s, &group).id;
+ let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap();
+ let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1);
+ let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]);
+ s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap();
+ assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
+ s.execute("select.set", &json!({ "ids": [group] })).unwrap();
+ let png = crate::tests_links::png(2, 2, [0, 0, 255]);
+ let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
+ assert!(out.is_ok(), "{out:?}");
+}
+
#[test]
fn dcs_transparency_counts_characters_with_a_transparent_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs
index 313d573206..5dd3357641 100644
--- a/crates/engine/src/tests/links.rs
+++ b/crates/engine/src/tests/links.rs
@@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
}
+/// Update Links gives a distorted image its file's new pixels between the same corners: its
+/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size,
+/// and Link Info measures its scale at its middle.
+#[test]
+fn update_links_keeps_a_distorted_images_corners() {
+ let dir = Folder::new("distorted-update");
+ let photo = dir.file("photo.png");
+ write(&photo, &png(20, 10, RED));
+ let mut s = session();
+ let id = place(&mut s, &photo);
+ s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
+ let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
+ let before = corners(&s);
+ assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
+ // The far corner of the pixels as the transform alone places them.
+ let far = |s: &Session| {
+ let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
+ im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
+ };
+ let far_before = far(&s);
+ // Link Info measures the scale where the effective resolution is measured: at the middle.
+ let scale_matches_ppi = |s: &mut Session| {
+ let info = s.execute("links.info", &json!({"id": id.0})).unwrap();
+ for i in 0..2 {
+ let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap());
+ assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}");
+ }
+ };
+ scale_matches_ppi(&mut s);
+ // A copy in a symbol, distorted the same way, shows the same file.
+ let copy = place(&mut s, &photo);
+ s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap();
+ s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
+ s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
+ s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
+ let in_symbol = |s: &Session| {
+ let mut out = vec![];
+ s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
+ if let NodeKind::Image(im) = &n.kind {
+ out.push((n.is_distorted_image(), (im.width, im.height)));
+ }
+ });
+ out
+ };
+ let symbol_corners = |s: &Session| {
+ let mut out = vec![];
+ s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners()));
+ out
+ };
+ assert_eq!(in_symbol(&s), [(true, (20, 10))]);
+ let symbol_before = symbol_corners(&s);
+ assert_eq!(symbol_before.len(), 1);
+ write(&photo, &png(60, 20, BLUE));
+ let u = s.execute("links.update", &json!({})).unwrap();
+ assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}");
+ let d = &s.doc().unwrap().doc;
+ let n = d.node(id).unwrap();
+ assert!(n.is_distorted_image());
+ assert_eq!(corners(&s), before);
+ let NodeKind::Image(im) = &n.kind else { panic!("an image") };
+ assert_eq!((im.width, im.height), (60, 20));
+ // The transform takes the new pixel size, so a placement by the transform keeps the old size.
+ assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
+ let d = &s.doc().unwrap().doc;
+ assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped");
+ let mut clipped = false;
+ d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. }));
+ assert!(!clipped, "the symbol's image is not clipped");
+ assert_eq!(in_symbol(&s), [(true, (60, 20))]);
+ assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners");
+ scale_matches_ppi(&mut s);
+}
+
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs
index dff77c1ce4..feb71e40ad 100644
--- a/crates/engine/src/tests/pathops.rs
+++ b/crates/engine/src/tests/pathops.rs
@@ -1907,6 +1907,166 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() {
assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err());
}
+/// The leaf objects of `n`, in paint order.
+fn leaves_of(n: &vectorcraft_doc::Node, out: &mut Vec) {
+ match n.children() {
+ Some(children) => children.iter().for_each(|c| leaves_of(c, out)),
+ None => out.push(n.clone()),
+ }
+}
+
+/// Apply the live Pathfinder effect `effect` with `params` to the selection, then expand its
+/// appearance: the objects it draws.
+fn live_pieces(s: &mut Session, effect: &str, params: Value) -> Vec {
+ let g = ids(&s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap())[0];
+ s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
+ let mut out = vec![];
+ leaves_of(&node(s, g), &mut out);
+ out
+}
+
+/// The parameters of the first effect of the selected object.
+fn first_effect_params(s: &Session) -> Value {
+ let st = s.doc().unwrap();
+ st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[0].params.clone()
+}
+
+/// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those its params
+/// give aside, and its journal entry carries them.
+#[test]
+fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() {
+ let mut s = session();
+ let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
+ s.execute("object.pathfinder.options", &json!({"precision": 1, "removeRedundantPoints": true, "removeUnpainted": true})).unwrap();
+ s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
+ s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap();
+ let all = json!({"precision": 1.0, "removeRedundantPoints": true, "removeUnpainted": true});
+ assert_eq!(first_effect_params(&s), all);
+ assert_eq!(s.journal.last().unwrap().1["params"], all, "the journal entry gives the options it used");
+ s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"precision": 0.5}})).unwrap();
+ let st = s.doc().unwrap();
+ let mix = &st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[1].params;
+ assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true}));
+}
+
+/// A live Pathfinder effect evaluates with its own options as the panel's operations do with
+/// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled
+/// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing.
+#[test]
+fn a_pathfinder_effect_evaluates_with_its_own_options() {
+ for (precision, faces) in [(0.01, 3), (1.0, 2)] {
+ let mut s = session();
+ let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0);
+ s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
+ assert_eq!(live_pieces(&mut s, "pathfinder.divide", json!({"precision": precision})).len(), faces, "precision {precision}");
+ }
+ for on in [false, true] {
+ let mut s = session();
+ filled_and_unfilled(&mut s);
+ let divided = live_pieces(&mut s, "pathfinder.divide", json!({"removeUnpainted": on}));
+ let unfilled = divided.iter().filter(|n| n.appearance.fill_paint().is_none()).count();
+ assert_eq!((unfilled, divided.len() - unfilled), (if on { 0 } else { 2 }, 1), "removeUnpainted {on}");
+ }
+ for on in [false, true] {
+ let mut s = session();
+ let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
+ let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
+ let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
+ let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
+ s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
+ let united = live_pieces(&mut s, "pathfinder.add", json!({"removeRedundantPoints": on}));
+ let count = united[0].path_data().unwrap().anchor_count();
+ assert!(if on { count == 4 } else { count > 4 }, "removeRedundantPoints {on}: {count} anchors");
+ }
+}
+
+/// An effect saved before Pathfinder effects kept their own options draws as one given their
+/// defaults, so older documents look as they did.
+#[test]
+fn a_pathfinder_effect_saved_without_options_draws_as_before() {
+ let draw = |params: Value| {
+ let mut s = session();
+ filled_and_unfilled(&mut s);
+ let g = ids(&s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap())[0];
+ s.edit("t", |d, _| {
+ d.node_mut(g).unwrap().appearance.effects[0].params = params;
+ Ok(())
+ })
+ .unwrap();
+ s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
+ serde_json::to_value(node(&s, g)).unwrap()
+ };
+ assert_eq!(draw(json!({})), draw(json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false})));
+}
+
+/// `effect.setParams` edits a Pathfinder effect's options as one undo step, records none for the
+/// values it already evaluates with, and refuses values out of range or of the wrong type.
+#[test]
+fn pathfinder_effect_options_edit_as_one_step_and_refuse_bad_values() {
+ let mut s = session();
+ let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
+ s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
+ s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
+ let steps = |s: &Session| s.doc().unwrap().history.undo.len();
+ let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
+ let before = steps(&s);
+ let same = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 0.01, "removeUnpainted": false}})).unwrap();
+ assert_eq!((same, steps(&s)), (json!({"ids": []}), before), "the values it has: no step");
+ // An effect saved without options evaluates with the defaults: given them, it is unchanged.
+ let g = s.doc().unwrap().selection.objects[0];
+ s.edit("t", |d, _| {
+ d.node_mut(g).unwrap().appearance.effects[0].params = json!({});
+ Ok(())
+ })
+ .unwrap();
+ let before = steps(&s);
+ let defaults = json!({"index": 0, "params": {"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}});
+ assert_eq!(s.execute("effect.setParams", &defaults).unwrap(), json!({"ids": []}));
+ assert_eq!(steps(&s), before);
+ s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 2, "removeRedundantPoints": true}})).unwrap();
+ assert_eq!(steps(&s), before + 1, "one step");
+ assert_eq!(first_effect_params(&s), json!({"precision": 2, "removeRedundantPoints": true}));
+ let kept = doc(&s);
+ for bad in [
+ json!({"precision": 0}),
+ json!({"precision": 11}),
+ json!({"precision": "1 pt"}),
+ json!({"precision": null}),
+ json!({"removeRedundantPoints": "yes"}),
+ json!({"removeUnpainted": 1}),
+ ] {
+ assert!(s.execute("effect.setParams", &json!({"index": 0, "params": bad})).is_err(), "setParams {bad}");
+ assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.trim", "params": bad})).is_err(), "apply {bad}");
+ assert_eq!(doc(&s), kept, "{bad} changes nothing");
+ }
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(first_effect_params(&s), json!({}), "undo restores the options");
+}
+
+/// A precision that Scale Strokes & Effects took past the range evaluates at its bound, and setting
+/// the bound is still an edit: a later scale then starts from the value set.
+#[test]
+fn a_precision_set_after_a_scale_past_its_range_is_kept() {
+ let mut s = session();
+ let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
+ s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
+ s.execute("effect.apply", &json!({"effect": "pathfinder.add", "params": {"precision": 8}})).unwrap();
+ let precision = |s: &Session| first_effect_params(s)["precision"].as_f64();
+ s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap();
+ assert_eq!(precision(&s), Some(16.0));
+ let steps = s.doc().unwrap().history.undo.len();
+ let out = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 10}})).unwrap();
+ assert_ne!(out, json!({"ids": []}), "an edit");
+ assert_eq!((precision(&s), s.doc().unwrap().history.undo.len()), (Some(10.0), steps + 1));
+ s.execute("object.scale", &json!({"sx": 50, "strokes": true})).unwrap();
+ assert_eq!(precision(&s), Some(5.0));
+ // The value it stores is still no edit.
+ let steps = s.doc().unwrap().history.undo.len();
+ assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 5}})).unwrap(), json!({"ids": []}));
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps);
+}
+
/// A single group containing multiple overlapping paths is accepted by Crop.
#[test]
fn crop_operates_on_a_single_selected_group_of_paths() {
diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs
index b2664a9682..9767aaec3e 100644
--- a/crates/engine/src/tests/recolor.rs
+++ b/crates/engine/src/tests/recolor.rs
@@ -1422,6 +1422,26 @@ fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
}
+/// A distorted image is read where its pixels are drawn, between its corners.
+#[test]
+fn theme_picker_reads_a_distorted_image_where_it_is_drawn() {
+ let mut s = session();
+ let (id, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
+ let (x, y0, y1) = (b.x1 + 20.0, b.y0, b.y1);
+ run(&mut s, "select.set", json!({"ids": [id.0]}));
+ run(&mut s, "object.distort", json!({"corners": [[x + 40.0, y0], [x + 60.0, y0], [x + 100.0, y1], [x, y1]]}));
+ // The lower left of the trapezoid, outside the rectangle the image was placed in: red.
+ assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [x + 2.0, y1 - 4.0, x + 20.0, y1 - 1.0]}]})), ["rgb 255 0 0"]);
+ // Where the image was: nothing.
+ assert!(pick_theme(&mut s, json!({"picks": [{"rect": [b.x0 + 1.0, b.y0 + 1.0, b.x1 - 1.0, b.y1 - 1.0]}]})).is_empty());
+ // A marquee reaching past the horizon its sides meet at (a quarter of its height above its
+ // top) still reads every pixel it covers.
+ let h = y1 - y0;
+ let mut both = pick_theme(&mut s, json!({"picks": [{"rect": [x - 10.0, y0 - h, x + 110.0, y1 + 1.0]}]}));
+ both.sort();
+ assert_eq!(both, ["rgb 0 0 255", "rgb 255 0 0"]);
+}
+
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
#[test]
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs
index 1b87639ef9..ff02889253 100644
--- a/crates/engine/src/tests/swatchcmds.rs
+++ b/crates/engine/src/tests/swatchcmds.rs
@@ -125,6 +125,69 @@ fn add_used_colors_skips_colours_that_have_swatches() {
assert!(doc(&s).swatch("R=171 G=205 B=239").unwrap().global);
}
+/// A run that finds no new color, over all the art or the selection, records no undo step.
+#[test]
+fn add_used_colors_with_no_new_color_records_no_undo_step() {
+ let mut s = session();
+ let a = rect_filled(&mut s, json!({"color": "#123456"}));
+ run(&mut s, "swatch.addUsedColors", json!({}));
+ run(&mut s, "select.set", json!({"ids": [a.0]}));
+ let before = doc(&s).clone();
+ let undo = undo_len(&s);
+ for p in [json!({}), json!({"selection": true, "global": true})] {
+ assert_eq!(run(&mut s, "swatch.addUsedColors", p), json!({"added": [], "linked": 0}));
+ assert_eq!(undo_len(&s), undo);
+ assert_eq!(*doc(&s), before);
+ }
+ // An empty selection is still an error, with nothing changed.
+ run(&mut s, "select.set", json!({"ids": []}));
+ let undo = undo_len(&s);
+ assert!(s.execute("swatch.addUsedColors", &json!({"selection": true})).is_err());
+ assert_eq!(undo_len(&s), undo);
+}
+
+/// A run that finds no new color, while the Type tool is typing, still ends the typing session: the
+/// typing is its own undo step.
+#[test]
+fn add_used_colors_with_no_new_color_ends_the_typing() {
+ use vectorcraft_tools::{PointerEvent, PointerKind};
+ let mut s = session();
+ let v = ViewInfo::default();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 10, "text": "Hello"}))["id"].as_u64().unwrap());
+ run(&mut s, "swatch.addUsedColors", json!({}));
+ s.select_tool("type", v).unwrap();
+ let b = doc(&s).bounds_of(&[t], false).unwrap();
+ for kind in [PointerKind::Down, PointerKind::Up] {
+ s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap();
+ }
+ s.tool_text("!", v).unwrap();
+ assert!(crate::cmd::typing_in_progress(&s));
+ let steps = undo_len(&s);
+ assert_eq!(run(&mut s, "swatch.addUsedColors", json!({})), json!({"added": [], "linked": 0}));
+ assert!(!crate::cmd::typing_in_progress(&s));
+ let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect();
+ assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing")));
+}
+
+/// Add Selected Colors while Global Edit is on links only the selected art: a member of the same
+/// shape with another color keeps its color and stays unlinked, and Global Edit stays on.
+#[test]
+fn add_selected_colors_in_global_edit_keeps_the_other_members_colors() {
+ let mut s = session();
+ let a = rect_filled(&mut s, json!({"color": "#123456"}));
+ let b = rect_filled(&mut s, json!({"color": "#654321"}));
+ run(&mut s, "select.set", json!({"ids": [a.0]}));
+ let r = run(&mut s, "select.globalEdit", json!({}));
+ assert_eq!((r["active"].clone(), r["ids"].clone()), (json!(true), json!([a.0, b.0])), "the other rectangle is a member");
+ let other = fill(&s, b);
+ let undo = undo_len(&s);
+ run(&mut s, "swatch.addUsedColors", json!({"selection": true, "global": true}));
+ assert!(matches!(fill(&s, a), Paint::Solid { swatch: Some(_), .. }), "{:?}", fill(&s, a));
+ assert_eq!(fill(&s, b), other, "the unselected member keeps its color");
+ assert_eq!(undo_len(&s), undo + 1);
+ assert!(s.doc().unwrap().global_edit.is_some(), "Global Edit stays on");
+}
+
/// Give `id` the fill `p` exactly as written (a command would round or convert some colors).
fn set_fill(s: &mut Session, id: NodeId, p: Paint) {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p);
diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs
index b8cb29f213..4a75c170c7 100644
--- a/crates/engine/src/tests/symbolism_options.rs
+++ b/crates/engine/src/tests/symbolism_options.rs
@@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() {
assert!(state(&s) == before);
}
+/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque
+/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke
+/// that changes no instance adds no undo step.
+#[test]
+fn an_instance_left_as_it_is_is_not_counted() {
+ let mut s = session();
+ let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
+ s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap();
+ let before = state(&s);
+ let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true}));
+ assert_eq!(r["count"], 0, "Alt on an opaque instance");
+ let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10}));
+ assert_eq!(r["count"], 0, "an instance at 5%");
+ assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history");
+ // A stroke over both counts only the instance it changes.
+ let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10}));
+ assert_eq!(r["count"], 1);
+ assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05);
+}
+
+/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and
+/// the Symbol Screener's instances take the mean of the instances under the brush.
+#[test]
+fn average_keeps_a_mean_opacity_below_five_percent() {
+ let mut s = session();
+ let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
+ let first = members(&s, set)[0];
+ s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap();
+ s.select(|_, sel| sel.set([set])).unwrap();
+ s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap();
+ let sprayed = *members(&s, set).last().unwrap();
+ assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity);
+ // Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it.
+ let mut s = session();
+ let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0));
+ s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap();
+ s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap();
+ adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"}));
+ let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity);
+ assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}");
+}
+
/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing.
#[test]
fn average_evens_out_the_stain_and_the_spacing() {
@@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() {
assert_eq!(center(&s, a), Point::new(200.0, 150.0));
}
+/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the
+/// tool's options stay as they were.
+#[test]
+fn tool_set_option_refuses_bad_symbolism_options() {
+ let mut s = session();
+ let before = s.tool_options_of("symbolSizer");
+ for (key, bad, want) in [
+ ("method", json!("smooth"), "`method` must be one of userDefined, average, random"),
+ ("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"),
+ ("usePressure", json!("yes"), "`usePressure` must be true or false"),
+ ("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"),
+ ("style", json!(3), "`style` must be a string or null"),
+ ("diameter", json!(1), "`diameter` must be a number from 2 to 2000"),
+ ] {
+ let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}}));
+ assert_eq!(r, Err(want.to_string()), "{key}");
+ assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}");
+ }
+ let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap();
+ assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined")));
+ // Every option the options dialog sends is taken, together.
+ let all = json!({
+ "diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false,
+ "sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined",
+ "sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true,
+ });
+ let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap();
+ for (key, v) in all.as_object().unwrap() {
+ assert_eq!(&r[key], v, "{key}");
+ }
+}
+
/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is
/// not used. A pressure that isn't a number is an error.
#[test]
@@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() {
json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}),
"a point's pressure must be a number, not \"hard\"",
);
+ // Also on a point without coordinates, beside one that has them.
+ refused(
+ &mut s,
+ "symbol.adjust",
+ json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}),
+ "a point's pressure must be a number, not \"bad\"",
+ );
}
for key in ["usePressure", "proportional", "affectsDensity"] {
let mut p = json!({"tool": "size", "points": [[200, 150]]});
@@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() {
assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a));
}
+/// A set duplicated packs from the density recorded for its source, and a pasted set from the
+/// density its source had at Copy: after Cut, after the source is given another density, and in
+/// another document.
+#[test]
+fn a_copied_set_packs_from_the_density_of_its_source() {
+ for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] {
+ let mut s = session();
+ let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect();
+ let set =
+ NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap());
+ s.select(|_, sel| sel.set([set])).unwrap();
+ let first = match copy {
+ "duplicate" => "edit.duplicate",
+ "cut" => "edit.cut",
+ _ => "edit.copy",
+ };
+ s.execute(first, &json!({})).unwrap();
+ if copy == "changed after copy" {
+ s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap();
+ }
+ if copy == "other document" {
+ s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
+ }
+ if copy != "duplicate" {
+ s.execute("edit.paste", &json!({})).unwrap();
+ }
+ let copied = s.doc().unwrap().selection.objects.clone();
+ assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}");
+ let ids = members(&s, copied[0]);
+ let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>();
+ let was = xs(&s);
+ let middle = was.iter().sum::() / 4.0;
+ s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap();
+ for (before, after) in was.iter().zip(xs(&s)) {
+ assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}");
+ }
+ }
+}
+
/// A set of one instance takes the new density without moving, as one undo step, so a later change
/// packs it from that density; setting the density it already has adds no undo step.
#[test]
@@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() {
assert!(state(&s) == before);
}
+/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen
+/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives
+/// each instance a share of that amount.
+#[test]
+fn the_styler_applies_the_style_by_the_brushs_strength() {
+ let styled = |extra: Value, x: f64| {
+ let mut s = session();
+ let a = dot(&mut s, 100.0, 150.0);
+ let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
+ s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
+ s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
+ s.select(|_, sel| sel.clear()).unwrap();
+ let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"});
+ p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ adjust(&mut s, p);
+ node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity)
+ };
+ let near = |a: f32, b: f32| (a - b).abs() < 1e-6;
+ assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center");
+ assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5));
+ assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge");
+ assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25));
+ assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0));
+ assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style");
+ // Random: instances the same distance from the point take different amounts, each from none to
+ // the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge).
+ let mut s = session();
+ let ring: Vec = (0..6)
+ .map(|i| {
+ let a = f64::from(i) * std::f64::consts::TAU / 6.0;
+ dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin())
+ })
+ .collect();
+ let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
+ s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
+ s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
+ s.select(|_, sel| sel.clear()).unwrap();
+ adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"}));
+ let amounts: Vec = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect();
+ assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}");
+ assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}");
+ assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}");
+}
+
+/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one
+/// at no opacity is passed over and counts as no stain in the mean amount.
+#[test]
+fn average_spray_passes_over_a_stain_at_no_opacity() {
+ use vectorcraft_color::{Color, Paint};
+ let mut s = session();
+ let set =
+ NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
+ let ids = members(&s, set);
+ assert_eq!(ids.len(), 2);
+ s.edit("Stains", |d, _| {
+ for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] {
+ let n = d.node_mut(id).unwrap();
+ n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_)));
+ let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
+ f.opacity = amount;
+ n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
+ }
+ Ok(())
+ })
+ .unwrap();
+ s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap();
+ let new: Vec = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect();
+ assert_eq!(new.len(), 1);
+ let f = node(&s, new[0]).appearance.fill().cloned().unwrap();
+ assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity);
+}
+
+/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves
+/// any other, and counts it.
+#[test]
+fn the_shifter_moves_an_instance_without_a_size() {
+ let mut s = session();
+ let a = dot(&mut s, 200.0, 150.0);
+ s.edit("Flatten", |d, _| {
+ if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
+ *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10}));
+ assert_eq!(r["count"], 1);
+ assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a));
+ // Average has no mean of such instances to move toward: it leaves them as they are.
+ let (before, x) = (state(&s), center(&s, a).x);
+ let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10}));
+ assert_eq!(r["count"], 0);
+ assert!(state(&s) == before);
+}
+
/// An instance with no size is shifted and screened as before; only Average, which needs its size,
/// leaves it as it is.
#[test]
@@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() {
assert!(state(&s) == before);
}
+/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes
+/// the stain the mean picks, not its hidden paint.
+#[test]
+fn average_stain_replaces_a_stain_at_no_opacity() {
+ use vectorcraft_color::{Color, Paint};
+ let mut s = session();
+ let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0));
+ s.edit("Stains", |d, _| {
+ for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] {
+ let n = d.node_mut(id).unwrap();
+ let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
+ f.opacity = amount;
+ n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
+ }
+ Ok(())
+ })
+ .unwrap();
+ adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10}));
+ let f = node(&s, a).appearance.fill().cloned().unwrap();
+ assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ assert!(f.opacity > 0.0, "{}", f.opacity);
+}
+
/// A stroke that leaves every instance under the brush as it is (each already at full stain, or
/// at the least opacity) counts none and adds no undo step.
#[test]
diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs
new file mode 100644
index 0000000000..ca08dc2069
--- /dev/null
+++ b/crates/engine/src/tests/symbolism_shift.rs
@@ -0,0 +1,272 @@
+//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking
+//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler
+//! keeping their amount while the color or style changes.
+
+use serde_json::{Value, json};
+use vectorcraft_doc::{Document, Node, NodeKind};
+use vectorcraft_geom::Point;
+
+use crate::*;
+
+/// A document with the 20 pt square symbol "Dot" and nothing selected.
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
+ s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
+ s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
+ s.select(|_, sel| sel.clear()).unwrap();
+ s
+}
+
+/// An instance of Dot centered on (`x`, `y`), not selected.
+fn dot(s: &mut Session, x: f64, y: f64) -> NodeId {
+ let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap());
+ s.select(|_, sel| sel.clear()).unwrap();
+ id
+}
+
+fn node(s: &Session, id: NodeId) -> Node {
+ s.doc().unwrap().doc.node(id).cloned().unwrap()
+}
+
+fn center(s: &Session, id: NodeId) -> Point {
+ match node(s, id).kind {
+ NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO,
+ other => panic!("not an instance: {other:?}"),
+ }
+}
+
+fn width(s: &Session, id: NodeId) -> f64 {
+ node(s, id).geometric_bounds().unwrap().width()
+}
+
+fn undo_len(s: &Session) -> usize {
+ s.doc().unwrap().history.undo.len()
+}
+
+fn state(s: &Session) -> (Document, usize) {
+ ((*s.doc().unwrap().doc).clone(), undo_len(s))
+}
+
+fn adjust(s: &mut Session, p: Value) -> Value {
+ s.execute("symbol.adjust", &p).unwrap()
+}
+
+/// The children of symbol set `set`, in stacking order (the first is at the back).
+fn members(s: &Session, set: NodeId) -> Vec {
+ node(s, set).children().unwrap().iter().map(|c| c.id).collect()
+}
+
+/// The instance's fill: its color as RGB and its amount.
+fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> {
+ node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity))
+}
+
+/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected.
+fn row(s: &mut Session) -> (NodeId, Vec) {
+ let pts: Vec = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect();
+ let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap());
+ let ids = members(s, set);
+ assert_eq!(ids.len(), 4);
+ (set, ids)
+}
+
+/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in
+/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas.
+#[test]
+fn shift_click_with_the_shifter_changes_the_stacking_order() {
+ let mut s = session();
+ let (set, ids) = row(&mut s);
+ let centers: Vec = ids.iter().map(|id| center(&s, *id)).collect();
+ let click = |s: &mut Session, x: f64, alt: bool| {
+ adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone()
+ };
+ let steps = undo_len(&s);
+ assert_eq!(click(&mut s, 120.0, false), 1);
+ assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
+ assert_eq!(undo_len(&s), steps + 1, "one undo step");
+ assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::>(), centers, "nothing moves on the canvas");
+ assert_eq!(click(&mut s, 120.0, false), 1);
+ assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]);
+ // Already in front of the others: nothing changes and no undo step is added.
+ let before = state(&s);
+ assert_eq!(click(&mut s, 120.0, false), 0);
+ assert!(state(&s) == before);
+ // Alt sends it back one place at a time; at the back it stays.
+ assert_eq!(click(&mut s, 120.0, true), 1);
+ assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
+ click(&mut s, 120.0, true);
+ click(&mut s, 120.0, true);
+ assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]);
+ assert_eq!(click(&mut s, 120.0, true), 0);
+ // Two instances under the brush move together past the next one.
+ s.execute("edit.undo", &json!({})).unwrap();
+ let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true}));
+ assert_eq!(both["count"], 2);
+ assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]);
+ // Without Shift a drag moves the instances, as before.
+ adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10}));
+ assert!(center(&s, ids[3]).x > centers[3].x);
+}
+
+/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even
+/// with Resizing Affects Density.
+#[test]
+fn shift_with_the_sizer_keeps_the_density() {
+ let at = |affects: bool, shift: bool| {
+ let mut s = session();
+ let a = dot(&mut s, 220.0, 150.0);
+ adjust(
+ &mut s,
+ json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}),
+ );
+ (center(&s, a), width(&s, a))
+ };
+ let (moved, _) = at(true, false);
+ assert!(moved.x > 220.5, "{moved:?}");
+ let (kept, grown) = at(true, true);
+ assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}");
+ // It resizes as the Sizer does with Resizing Affects Density off.
+ assert_eq!(at(false, false), (kept, grown));
+ assert_eq!(at(false, true), (kept, grown));
+}
+
+/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill
+/// color; an instance without a stain is left as it is.
+#[test]
+fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() {
+ let mut s = session();
+ let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
+ adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
+ let (red, amount) = fill(&s, a).unwrap();
+ assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}");
+ // A second fill below the stain, which Shift leaves as it is.
+ s.edit("Add fill", |d, _| {
+ let n = d.node_mut(a).unwrap();
+ let lower = n.appearance.fill().unwrap().clone();
+ n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower }));
+ Ok(())
+ })
+ .unwrap();
+ let lower = node(&s, a).appearance.items[0].clone();
+ let stain = |s: &mut Session, x: f64| {
+ adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true}))
+ };
+ assert_eq!(stain(&mut s, 100.0)["count"], 1);
+ let (color, kept) = fill(&s, a).unwrap();
+ assert_eq!(kept, amount, "the amount stays");
+ assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}");
+ assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays");
+ // More strokes go on toward blue, with the amount still the same.
+ for _ in 0..30 {
+ stain(&mut s, 100.0);
+ }
+ let (bluer, kept) = fill(&s, a).unwrap();
+ assert_eq!(kept, amount);
+ assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}");
+ // Alt has no effect with Shift.
+ let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true});
+ adjust(&mut s, green.clone());
+ let plain = fill(&s, a);
+ s.execute("edit.undo", &json!({})).unwrap();
+ let mut with_alt = green;
+ with_alt["alt"] = json!(true);
+ adjust(&mut s, with_alt);
+ assert_eq!(fill(&s, a), plain);
+ // No stain on b: nothing changes and no undo step is added.
+ let before = state(&s);
+ assert_eq!(stain(&mut s, 300.0)["count"], 0);
+ assert!(state(&s) == before && fill(&s, b).is_none());
+}
+
+/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its
+/// fill toward the selected style's fill.
+#[test]
+fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() {
+ let mut s = session();
+ let a = dot(&mut s, 100.0, 150.0);
+ let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
+ s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
+ s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
+ s.select(|_, sel| sel.clear()).unwrap();
+ // A red stain at part strength.
+ adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
+ let (red, amount) = fill(&s, a).unwrap();
+ assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}");
+ // Half the brush's strength at a point 2.5 pt from the instance: half way to blue.
+ adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
+ let (mixed, kept) = fill(&s, a).unwrap();
+ assert_eq!(kept, amount);
+ assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}");
+ // At the brush's center with full intensity it takes the style's fill.
+ adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
+ let (blue, kept) = fill(&s, a).unwrap();
+ assert_eq!(kept, amount);
+ assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}");
+}
+
+/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes
+/// the new paint at once, at any strength, and keeps its amount.
+#[test]
+fn shift_changes_a_paint_that_has_no_form_in_between() {
+ use vectorcraft_color::Paint;
+ let mut s = session();
+ let a = dot(&mut s, 100.0, 150.0);
+ s.edit("Pattern fill", |d, _| {
+ let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() });
+ f.opacity = 0.4;
+ d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
+ Ok(())
+ })
+ .unwrap();
+ // Low intensity, near the brush's edge: far below half strength.
+ let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true}));
+ assert_eq!(r["count"], 1);
+ let f = node(&s, a).appearance.fill().cloned().unwrap();
+ assert_eq!(f.opacity, 0.4, "the amount stays");
+ assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint);
+}
+
+/// A style name the document has no style for (the Styler's style from another document, or one
+/// since renamed or deleted) moves the fill toward the document's first style after the default
+/// one, as no name does, and the stain's amount stays.
+#[test]
+fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() {
+ use vectorcraft_color::{Color, Paint};
+ let styled = |style: Option<&str>| {
+ let mut s = session();
+ let a = dot(&mut s, 100.0, 150.0);
+ s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
+ s.select(|_, sel| sel.clear()).unwrap();
+ adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
+ let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true});
+ if let Some(n) = style {
+ p["style"] = json!(n);
+ }
+ let stained = node(&s, a).appearance.fill().map(|f| f.opacity);
+ adjust(&mut s, p);
+ let f = node(&s, a).appearance.fill().cloned().unwrap();
+ assert_eq!(Some(f.opacity), stained, "the amount stays");
+ let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint();
+ (f.paint, first)
+ };
+ let (missing, first) = styled(Some("No Such Style"));
+ let (none, _) = styled(None);
+ assert_eq!(missing, none);
+ // The paint is the first style's, not the active fill color.
+ assert_eq!(none, first);
+ assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
+}
+
+/// A `shift` that is not true, false or null is refused and changes nothing.
+#[test]
+fn a_bad_shift_is_refused() {
+ let mut s = session();
+ dot(&mut s, 100.0, 150.0);
+ for tool in ["shift", "size", "stain", "style"] {
+ let before = state(&s);
+ let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"}));
+ assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}");
+ assert!(state(&s) == before);
+ }
+}
diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs
new file mode 100644
index 0000000000..ebd755dda7
--- /dev/null
+++ b/crates/engine/src/tests/three_point_arc.rs
@@ -0,0 +1,220 @@
+//! `shape.threePointArc`: an open circular arc between two ends, through a third point or
+//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it.
+
+use serde_json::{Value, json};
+use vectorcraft_doc::{Node, NodeKind};
+use vectorcraft_geom::Point;
+use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
+
+use crate::*;
+
+const C: &str = "shape.threePointArc";
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ s
+}
+
+fn node(s: &Session, id: NodeId) -> Node {
+ s.doc().unwrap().doc.node(id).unwrap().clone()
+}
+
+fn undo_len(s: &Session) -> usize {
+ s.doc().unwrap().history.undo.len()
+}
+
+fn object_count(s: &Session) -> usize {
+ let mut n = 0;
+ s.doc().unwrap().doc.walk(|_| n += 1);
+ n
+}
+
+fn id_of(v: &Value) -> NodeId {
+ NodeId(v["id"].as_u64().unwrap())
+}
+
+/// The largest distance of `points` from the path of `id`.
+fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
+ let n = node(s, id);
+ let path = n.path_data().unwrap();
+ points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
+}
+
+/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about
+/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with
+/// no fill and a stroke, selected, and one undo step.
+#[test]
+fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() {
+ let mut s = session();
+ let undo = undo_len(&s);
+ let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap();
+ assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
+ // From (0, 0) over the top to (80, 0): clockwise on the page.
+ assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}");
+ let id = id_of(&out);
+ let n = node(&s, id);
+ let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) };
+ let sp = &path.subpaths[0];
+ assert!(!sp.closed && path.subpaths.len() == 1);
+ assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0))));
+ assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9);
+ assert!(n.appearance.fill_paint().is_none(), "no fill");
+ assert!(!n.appearance.stroke_paint().is_none(), "a stroke");
+ assert_eq!(s.doc().unwrap().selection.objects, [id]);
+ assert_eq!(undo_len(&s), undo + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(s.doc().unwrap().doc.node(id).is_none());
+ // A third point between the quarter turns is an anchor too, so the path meets it exactly.
+ let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin());
+ let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap();
+ let id = id_of(&out);
+ assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via));
+ assert!(farthest_from_path(&s, id, &[via]) < 1e-9);
+}
+
+/// With `toward`, the arc leaves `start` heading at the point (its first handle points there),
+/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the
+/// arc leaves `end` heading at the point).
+#[test]
+fn the_arc_toward_a_point_has_that_tangent_at_its_end() {
+ let mut s = session();
+ let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap();
+ let n = node(&s, id_of(&out));
+ let first = n.path_data().unwrap().subpaths[0].anchors[0];
+ let d = (first.h_out - first.p).normalize();
+ assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
+ // A quarter turn's tangent: the center is at (40, 40) and the radius √3200.
+ assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}");
+ let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap();
+ let n = node(&s, id_of(&out));
+ let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap();
+ let d = (last.p - last.h_in).normalize();
+ assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
+ // The direction from the start and from the end mirror each other.
+ assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}");
+}
+
+/// Points that are the same, a third point on the line through the ends, and an arc reaching past
+/// the canvas are refused with a message; nothing is drawn and no undo step is added.
+#[test]
+fn points_with_no_arc_are_refused() {
+ let mut s = session();
+ let (undo, count) = (undo_len(&s), object_count(&s));
+ for p in [
+ json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}),
+ json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}),
+ json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}),
+ json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}),
+ json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}),
+ json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}),
+ json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}),
+ json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}),
+ ] {
+ let e = s.execute(C, &p).unwrap_err().to_string();
+ assert!(e.contains("no arc fits these points"), "{p}: {e}");
+ }
+ // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the
+ // arc goes round the far side of it.
+ let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]});
+ let e = s.execute(C, &far).unwrap_err().to_string();
+ assert!(e.contains("result would exceed the canvas"), "{e}");
+ assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
+}
+
+/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not
+/// "start" or "end", and an `at` with `through` are errors; nothing is drawn.
+#[test]
+fn malformed_params_are_refused() {
+ let mut s = session();
+ let count = object_count(&s);
+ for (p, want) in [
+ (json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"),
+ (json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"),
+ (json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"),
+ (json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"),
+ (json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"),
+ (json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"),
+ (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"),
+ (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""),
+ (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""),
+ (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"),
+ (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"),
+ ] {
+ let e = s.execute(C, &p).unwrap_err().to_string();
+ assert!(e.contains(want), "{p}: {e}");
+ }
+ assert_eq!(object_count(&s), count);
+}
+
+/// With Align New Objects to Pixel Grid on, the ends stay on the given points.
+#[test]
+fn the_arc_is_not_moved_onto_the_pixel_grid() {
+ let mut s = session();
+ s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
+ let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap());
+ let n = node(&s, id);
+ let sp = &n.path_data().unwrap().subpaths[0];
+ assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2)));
+ assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1)));
+ assert!(!n.extras().pixel_aligned);
+}
+
+fn view() -> ViewInfo {
+ ViewInfo { smart_guides: false, ..ViewInfo::default() }
+}
+
+fn click(s: &mut Session, x: f64, y: f64) {
+ for k in [PointerKind::Down, PointerKind::Up] {
+ s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap();
+ }
+}
+
+/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third
+/// click makes the third point give the direction instead. Escape drops the ends.
+#[test]
+fn three_clicks_with_the_tool_draw_the_arc() {
+ let mut s = session();
+ s.select_tool("threePointArc", view()).unwrap();
+ let (undo, count) = (undo_len(&s), object_count(&s));
+ click(&mut s, 100.0, 200.0);
+ click(&mut s, 180.0, 200.0);
+ assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet");
+ click(&mut s, 140.0, 160.0);
+ assert_eq!(undo_len(&s), undo + 1);
+ let id = *s.doc().unwrap().selection.objects.first().unwrap();
+ assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9);
+ // Escape after the ends: the next clicks start afresh.
+ click(&mut s, 0.0, 0.0);
+ click(&mut s, 10.0, 300.0);
+ s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
+ click(&mut s, 100.0, 300.0);
+ click(&mut s, 180.0, 300.0);
+ s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap();
+ let undo = undo_len(&s);
+ // Straight up from the first end: the upper half circle about (140, 300).
+ click(&mut s, 100.0, 250.0);
+ assert_eq!(undo_len(&s), undo + 1);
+ let id = *s.doc().unwrap().selection.objects.first().unwrap();
+ assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9);
+}
+
+/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and
+/// refuses a value that is not true or false, or an option the tool doesn't have.
+#[test]
+fn set_option_sets_the_direction_and_refuses_bad_values() {
+ let mut s = session();
+ for on in [true, false] {
+ let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap();
+ assert_eq!(set["direction"], json!(on));
+ assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on));
+ }
+ let cases = [
+ (json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"),
+ (json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"),
+ ];
+ for (p, want) in cases {
+ assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
+ }
+ assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
+}
diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs
index fbde9edca7..69d382f2dc 100644
--- a/crates/engine/src/tests/toolsettings.rs
+++ b/crates/engine/src/tests/toolsettings.rs
@@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() {
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides");
}
+/// An option set with `tool.setOption` while a press is held survives the dropped press, in the
+/// tool and in the stored options, while what the drag itself changed is put back in both.
+#[test]
+fn an_option_set_during_a_dropped_press_is_kept() {
+ let mut s = session();
+ select(&mut s, "rectangularGrid");
+ let v = ViewInfo { smart_guides: false, ..Default::default() };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
+ s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
+ s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
+ assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6)));
+ s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap();
+ s.drop_tool_press(v).unwrap();
+ let o = s.tool_options();
+ assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay");
+ let saved = &s.prefs.tool_settings["rectangularGrid"];
+ assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are");
+ select(&mut s, "selection");
+ select(&mut s, "rectangularGrid");
+ let o = s.tool_options();
+ assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns");
+ // The same through the desktop app's setter.
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
+ s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
+ s.set_tool_option("columns", &json!(3));
+ s.drop_tool_press(v).unwrap();
+ let o = s.tool_options();
+ assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3)));
+ let saved = &s.prefs.tool_settings["rectangularGrid"];
+ assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3)));
+}
+
+/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped
+/// press, in the tool and in the preference.
+#[test]
+fn a_corner_radius_set_during_a_dropped_press_is_kept() {
+ let mut s = session();
+ select(&mut s, "roundedRectangle");
+ let v = ViewInfo { smart_guides: false, ..Default::default() };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
+ let mut p = s.prefs.clone();
+ p.corner_radius = 30.0;
+ s.apply_prefs(p);
+ s.drop_tool_press(v).unwrap();
+ assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
+ assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
+}
+
+/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag
+/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius
+/// preference set while the Rounded Rectangle lends one.
+#[test]
+fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
+ let mut s = session();
+ select(&mut s, "rectangularGrid");
+ let v = ViewInfo { smart_guides: false, ..Default::default() };
+ let cmd = Mods { cmd: true, ..Default::default() };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
+ assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool");
+ s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap();
+ s.drop_tool_press(v).unwrap();
+ assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back");
+ assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns");
+ assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them");
+ select(&mut s, "roundedRectangle");
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
+ assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool");
+ let mut p = s.prefs.clone();
+ p.corner_radius = 30.0;
+ s.apply_prefs(p);
+ s.drop_tool_press(v).unwrap();
+ assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
+ assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
+}
+
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
/// the next click.
#[test]
diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs
index 3aea7f3041..89c3b28b13 100644
--- a/crates/engine/src/tests/xform.rs
+++ b/crates/engine/src/tests/xform.rs
@@ -754,6 +754,406 @@ fn distort_perspective_midpoint_is_projective() {
assert!((c.y - 100.0 / 6.0).abs() < 1e-3, "{c:?}");
}
+/// A 2 × 2 px image placed at (0, 0)–(100, 100), selected.
+fn placed_image(s: &mut Session) -> NodeId {
+ s.edit("Place", |d, sel| {
+ d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![]));
+ let id = d.alloc_id();
+ let im = vectorcraft_doc::ImageObject {
+ key: "pic".into(),
+ width: 2,
+ height: 2,
+ xf: vectorcraft_geom::Affine::scale(50.0),
+ link: None,
+ placement: Default::default(),
+ pixels: None,
+ };
+ d.insert(d.default_layer(), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?;
+ sel.set([id]);
+ Ok(id)
+ })
+ .unwrap()
+}
+
+fn corners(s: &Session, id: NodeId) -> [Point; 4] {
+ s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap()
+}
+
+fn assert_corners(got: [Point; 4], want: [(f64, f64); 4]) {
+ for (g, (x, y)) in got.iter().zip(want) {
+ assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?} against {want:?}");
+ }
+}
+
+/// Perspective Distort and Free Distort put an image's corners exactly on the handles, in one
+/// undo step; the image is bounded and clicked by its corners, and a move takes them along.
+#[test]
+fn distort_puts_an_images_corners_on_the_handles() {
+ for want in [[(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)], [(10.0, 5.0), (90.0, 0.0), (120.0, 110.0), (0.0, 100.0)]] {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let undo = undo_len(&s);
+ let corners_json: Vec<[f64; 2]> = want.iter().map(|(x, y)| [*x, *y]).collect();
+ s.execute("object.distort", &json!({ "corners": corners_json })).unwrap();
+ assert_eq!(undo_len(&s), undo + 1);
+ assert_corners(corners(&s, img), want);
+ assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+ let b = bounds(&s, img);
+ let xs = want.map(|c| c.0);
+ let ys = want.map(|c| c.1);
+ let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
+ assert!(near(b.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(b.x1, xs.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
+ assert!(near(b.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(b.y1, ys.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
+ s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
+ assert_corners(corners(&s, img), want.map(|(x, y)| (x + 10.0, y + 20.0)));
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+ assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+ }
+ // Clicks: inside the trapezoid hits the image; inside its old square but outside the
+ // trapezoid does not.
+ let mut s = session();
+ let img = placed_image(&mut s);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ let doc = &s.doc().unwrap().doc;
+ let opt = vectorcraft_doc::hit::HitOptions::default();
+ assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(50.0, 50.0), opt).map(|h| h.leaf), Some(img));
+ assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(5.0, 10.0), opt).map(|h| h.leaf), None);
+}
+
+/// Distorted together with a path, the image's corners and the path's anchors follow one warp.
+#[test]
+fn distort_moves_an_image_and_a_path_as_one() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let path = rect(&mut s, 100.0, 0.0, 100.0, 100.0);
+ s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
+ s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [200, 100], [50, 100]]})).unwrap();
+ let d = &s.doc().unwrap().doc;
+ let anchors: Vec = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
+ let q = corners(&s, img);
+ // The image's right edge and the path's left edge were one line, and stay one where the warp
+ // moves it.
+ assert!(q[2].distance(Point::new(100.0, 100.0)) > 1.0, "{q:?}");
+ for p in [q[1], q[2]] {
+ assert!(anchors.iter().any(|a| a.distance(p) < 1e-9), "{p:?} not in {anchors:?}");
+ }
+}
+
+/// Corners that would fold an image over are refused: nothing changes and no undo step is kept.
+/// A distorted image keeps its distortion where commands that cannot keep it are asked to work.
+#[test]
+fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
+ let e = s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [0, 100], [100, 100]]})).unwrap_err().to_string();
+ assert!(e.contains("convex"), "{e}");
+ assert_eq!(undo_len(&s), undo);
+ assert_eq!(s.doc().unwrap().doc, before);
+ // Three corners on one line give no perspective map at all.
+ let e = s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [100, 50], [0, 100]]})).unwrap_err().to_string();
+ assert!(e.contains("convex"), "{e}");
+ assert_eq!(s.doc().unwrap().doc, before);
+ // A convex shape too small for a perspective map: the corners could not reach the handles.
+ let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1e-7, 0], [8e-8, 1e-7], [0, 1e-7]]})).unwrap_err().to_string();
+ assert!(e.contains("too close together"), "{e}");
+ // The same shape far from the origin: its distance from it does not hide the missed corner.
+ let x = 1_000_000.0;
+ let e = s.execute("object.distort", &json!({"corners": [[x, 0], [x + 1e-7, 0], [x + 8e-8, 1e-7], [x, 1e-7]]})).unwrap_err().to_string();
+ assert!(e.contains("too close together"), "{e}");
+ // A long, thin shape with one side all but gone.
+ let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1_000_000, 0], [1_000_000, 1e-19], [0, 1]]})).unwrap_err().to_string();
+ assert!(e.contains("too close together"), "{e}");
+ assert_eq!(s.doc().unwrap().doc, before);
+ assert_eq!(undo_len(&s), undo);
+ // A small shape near the edge of the canvas is still distorted.
+ let o = vectorcraft_doc::MAX_COORD - 2.0;
+ let far = [[o, o], [o + 1.0, o], [o + 0.2130712, o + 1.0], [o, o + 1.0]];
+ s.execute("object.distort", &json!({ "from": [0, 0, 100, 100], "corners": far })).unwrap();
+ assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(undo_len(&s), undo);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ for (cmd, params) in [
+ ("object.cropImage", json!({})),
+ ("imageTrace.make", json!({})),
+ ("links.relink", json!({"path": "/nowhere/pic.png"})),
+ // Refused before the folder is searched, so a file missing there does not hide it.
+ ("links.relink", json!({"folder": "/nowhere"})),
+ ("links.embed", json!({"ids": [img.0]})),
+ ("links.unembed", json!({})),
+ // Refused before any file is written.
+ ("links.unembed", json!({"folder": "/nowhere"})),
+ ("object.createObjectMosaic", json!({})),
+ ("object.mesh.create", json!({})),
+ (
+ "file.place",
+ json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
+ ),
+ ] {
+ let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
+ // Every command gives the one shared refusal, which the complete-message catalogs translate.
+ assert!(e.contains("is an image changed by Perspective Distort or Free Distort, which this command does not work on"), "{cmd}: {e}");
+ }
+ assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+ assert_eq!(undo_len(&s), undo + 1);
+ // Type replaces a distorted image by its bounds, which the corners give: not refused.
+ let text = json!({"replace": true, "name": "note.txt", "dataBase64": vectorcraft_format::base64_encode(b"Hello")});
+ let out = s.execute("file.place", &text).unwrap();
+ let id = NodeId(out["ids"][0].as_u64().unwrap());
+ assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Text(_)));
+}
+
+/// Create Gradient Mesh on a path and a distorted image converts the path and names the image it
+/// left as it is, with the shared refusal.
+#[test]
+fn mesh_create_reports_the_distorted_image_it_skips() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ let path = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
+ s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
+ let out = s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
+ assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}");
+ let skipped = out["skipped"].as_array().expect("the skipped image");
+ assert_eq!(skipped.len(), 1, "{out}");
+ assert_eq!(skipped[0]["id"], json!(img.0));
+ assert!(skipped[0]["reason"].as_str().unwrap().contains("Perspective Distort or Free Distort"), "{out}");
+ assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+ // Without a distorted image, no `skipped`.
+ let other = rect(&mut s, 400.0, 0.0, 100.0, 100.0);
+ let out = s.execute("object.mesh.create", &json!({"ids": [other.0], "rows": 1, "cols": 1})).unwrap();
+ assert!(out.get("skipped").is_none(), "{out}");
+}
+
+/// A blend takes the warp's affine approximation whole, so an image inside it does not stop a
+/// distort whose corners an image could not follow.
+#[test]
+fn distort_of_a_blend_holding_an_image_is_not_refused() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let r = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
+ let out = s.execute("object.blend.make", &json!({"ids": [img.0, r.0]})).unwrap();
+ let blend = NodeId(out["id"].as_u64().unwrap());
+ let undo = undo_len(&s);
+ s.execute("object.distort", &json!({"ids": [blend.0], "corners": [[0, 0], [300, 0], [100, 50], [0, 100]]})).unwrap();
+ assert_eq!(undo_len(&s), undo + 1);
+ assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+}
+
+/// The Control bar's Mask clips a distorted image to the shape between its corners.
+#[test]
+fn mask_on_a_distorted_image_follows_its_corners() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let want = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ let out = s.execute("object.maskImage", &json!({})).unwrap();
+ let path = NodeId(out["path"].as_u64().unwrap());
+ let d = &s.doc().unwrap().doc;
+ let anchors: Vec = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
+ assert_eq!(anchors.len(), 4, "{anchors:?}");
+ for (x, y) in want {
+ assert!(anchors.iter().any(|a| a.distance(Point::new(x, y)) < 1e-9), "{x},{y} not in {anchors:?}");
+ }
+ assert!(d.node(img).unwrap().is_distorted_image());
+}
+
+/// A Transform effect moves a distorted image's corners with it: expanded, the image stands
+/// where the effect drew it.
+#[test]
+fn a_transform_effect_moves_a_distorted_images_corners() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
+ s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
+ s.execute("effect.expandAppearance", &json!({})).unwrap();
+ let mut found = vec![];
+ for layer in &s.doc().unwrap().doc.layers {
+ layer.walk(&mut |n| {
+ if let Some(q) = n.image_corners() {
+ found.push(q);
+ }
+ });
+ }
+ let want = [(240.0, 0.0), (260.0, 0.0), (300.0, 100.0), (200.0, 100.0)];
+ assert!(found.iter().any(|q| q.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-6)), "{found:?}");
+}
+
+/// A Transform effect after a Warp effect moves a distorted image's warped pixels once: the art
+/// stands where the Warp alone draws it, moved by the Transform.
+#[test]
+fn a_transform_after_a_warp_moves_a_distorted_image_once() {
+ let expanded_bounds = |transform: bool| {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ s.execute("effect.apply", &json!({"ids": [img.0], "effect": "warp.bulge", "params": {"bend": 50}})).unwrap();
+ if transform {
+ s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
+ }
+ s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
+ s.execute("effect.expandAppearance", &json!({})).unwrap();
+ let mut images = None;
+ for layer in &s.doc().unwrap().doc.layers {
+ layer.walk(&mut |n| {
+ if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
+ let r = im.xf.transform_rect_bbox(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)));
+ images = Some(images.map_or(r, |b: vectorcraft_geom::Rect| b.union(r)));
+ }
+ });
+ }
+ images.expect("the warped pieces")
+ };
+ let (alone, moved) = (expanded_bounds(false), expanded_bounds(true));
+ assert!((moved.x0 - alone.x0 - 200.0).abs() < 1e-6 && (moved.x1 - alone.x1 - 200.0).abs() < 1e-6, "{alone:?} {moved:?}");
+ assert!((moved.y0 - alone.y0).abs() < 1e-6 && (moved.y1 - alone.y1).abs() < 1e-6, "{alone:?} {moved:?}");
+}
+
+/// A raster effect's baked pixels already show the distortion: the image that replaces a
+/// distorted one is placed by its own transform.
+#[test]
+fn baked_raster_effect_pixels_replace_a_distortion() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ let v = s.doc().unwrap().doc.node(img).unwrap().clone();
+ let baked = Node::new(NodeId(99), v.kind.clone());
+ let out = crate::cmd::rasterfx::replace_with_image(v, baked);
+ assert!(!out.is_distorted_image());
+ assert!(out.extras().image_quad.is_none());
+}
+
+/// A distorted image is saved with its corners and reads back the same.
+#[test]
+fn a_distorted_image_saves_and_reads_back() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ let doc = &s.doc().unwrap().doc;
+ let bytes = vectorcraft_format::save(doc, false);
+ let back = vectorcraft_format::load(&bytes).unwrap();
+ assert_eq!(back.node(img).unwrap().image_corners(), doc.node(img).unwrap().image_corners());
+ assert!(back.node(img).unwrap().is_distorted_image());
+ assert!(String::from_utf8_lossy(&bytes).contains("image_quad"));
+ // An image without a distortion is saved without the field, and opens as it was.
+ let mut plain = session();
+ let img = placed_image(&mut plain);
+ let doc = &plain.doc().unwrap().doc;
+ let bytes = vectorcraft_format::save(doc, false);
+ assert!(!String::from_utf8_lossy(&bytes).contains("image_quad"));
+ let back = vectorcraft_format::load(&bytes).unwrap();
+ assert_eq!(back.node(img), doc.node(img));
+ // Corners in a file that fold the image over leave it placed by its transform.
+ let mut bad = (**doc).clone();
+ bad.node_mut(img).unwrap().extras_mut().image_quad =
+ Some(Box::new([(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)].map(|(x, y)| Point::new(x, y))));
+ let back = vectorcraft_format::load(&vectorcraft_format::save(&bad, false)).unwrap();
+ assert!(!back.node(img).unwrap().is_distorted_image());
+ assert_corners(back.node(img).unwrap().image_corners().unwrap(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
+}
+
+/// A distort whose corners cross the warp's horizon at the image is refused with that reason, and
+/// a distort that leaves a distorted image where it is records nothing.
+#[test]
+fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
+ // The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
+ // y = 15, inside the image.
+ let e = s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
+ assert!(e.contains("horizon"), "{e}");
+ assert_eq!(s.doc().unwrap().doc, before);
+ assert_eq!(undo_len(&s), undo);
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
+ let b = bounds(&s, img);
+ let at = [[b.x0, b.y0], [b.x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]];
+ s.execute("object.distort", &json!({ "from": [b.x0, b.y0, b.x1, b.y1], "corners": at })).unwrap();
+ assert_eq!(s.doc().unwrap().doc, before);
+ assert_eq!(undo_len(&s), undo);
+}
+
+/// Image info gives a distorted image's resolution at its middle, not the resolution it had
+/// before the distort.
+#[test]
+fn image_info_measures_a_distorted_image_at_its_middle() {
+ let mut s = session();
+ placed_image(&mut s);
+ // 2 pixels across 100 pt: 1.44 ppi.
+ let ppi = |s: &mut Session| {
+ let out = s.execute("image.info", &json!({})).unwrap();
+ [out["ppi"][0].as_f64().unwrap(), out["ppi"][1].as_f64().unwrap()]
+ };
+ assert!((ppi(&mut s)[0] - 1.44).abs() < 1e-9);
+ // The top squeezed to half the width: the middle of the pixels spans less than 100 pt across,
+ // so the resolution across there is higher.
+ s.execute("object.distort", &json!({ "corners": [[25, 0], [75, 0], [100, 100], [0, 100]] })).unwrap();
+ let [x, _] = ppi(&mut s);
+ assert!(x > 1.44 * 1.1, "{x}");
+}
+
+/// Rasterize draws a distorted image's pixels between its corners, and the image it makes is a
+/// plain one.
+#[test]
+fn rasterize_draws_a_distorted_image_between_its_corners() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let mut png = std::io::Cursor::new(vec![]);
+ image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();
+ s.edit("Pixels", |d, _| {
+ d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png.into_inner()));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
+ s.execute("select.set", &json!({ "ids": [img.0] })).unwrap();
+ let out = s.execute("object.rasterize", &json!({ "ppi": 72, "background": "transparent", "addAround": 0 })).unwrap();
+ let d = &s.doc().unwrap().doc;
+ let id = NodeId(out["id"].as_u64().unwrap());
+ let n = d.node(id).unwrap();
+ assert!(!n.is_distorted_image());
+ let vectorcraft_doc::NodeKind::Image(im) = &n.kind else { panic!("an image") };
+ // The raster covers the corners' bounds.
+ let b = n.geometric_bounds().unwrap();
+ assert!([b.x0, b.y0, b.x1 - 100.0, b.y1 - 100.0].iter().all(|v| v.abs() <= 1.0), "{b:?}");
+ let px = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
+ let (w, h) = px.dimensions();
+ let rgba = px.to_rgba8();
+ let alpha = |x: f64, y: f64| {
+ let p = im.xf.inverse() * Point::new(x, y);
+ assert!(p.x >= 0.0 && p.y >= 0.0 && p.x < f64::from(w) && p.y < f64::from(h), "({x}, {y}) is outside the raster: {p:?}");
+ let (i, j) = (p.x as u32, p.y as u32);
+ rgba[((j * w + i) * 4 + 3) as usize]
+ };
+ assert_eq!(alpha(50.0, 90.0), 255, "inside the corners");
+ assert_eq!(alpha(10.0, 10.0), 0, "inside the old rectangle, outside the corners");
+}
+
+/// A Free Transform drag in Free Distort mode on an image puts the dragged corner where the drag
+/// ends, in one undo step, also when a position on the way would have folded the image.
+#[test]
+fn free_transform_distort_drag_on_an_image_is_one_undo_step() {
+ let mut s = session();
+ let img = placed_image(&mut s);
+ let undo = undo_len(&s);
+ let v = ViewInfo::default();
+ s.select_tool("freeTransform", v).unwrap();
+ s.set_tool_option("mode", &json!("distort"));
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
+ // Past the top left corner: the image would fold over.
+ s.pointer(&PointerEvent::new(PointerKind::Drag, -50.0, -50.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 120.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 120.0), v).unwrap();
+ assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (130.0, 120.0), (0.0, 100.0)]);
+ assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
+ assert_eq!(undo_len(&s), undo + 1);
+}
+
#[test]
fn free_transform_distort_mode_via_pointer() {
let mut s = session();
diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs
index 5f36c5a98e..fe38a92a49 100644
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@ -298,6 +298,10 @@ impl Session {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
+ // The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842).
+ if id == "directSelection" {
+ lent.set_option("lentByCmd", &Value::Bool(true));
+ }
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
@@ -611,13 +615,18 @@ impl Session {
/// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what
/// the tool asks for along the way, only a cancel and a notify run, so a marquee selects
/// nothing and a click opens no size dialog. The tool gets back the persistent options it had
- /// when the press began, and none of the press's changes to them are stored. A dropped Type
- /// press restores the prior selection. The freeform gradient point selected once the tool
- /// took the press is selected again. A press held while the tool computes an edit on another
- /// thread has not reached the tool: it is removed from the held input with the pointer events
- /// and tool keys held after it, and the tool is left as it is. A perspective plane key held
- /// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held
- /// after the last held release belong to the press the tool has, and are removed with it.
+ /// when the press began, and none of the press's changes to them are stored. An option set
+ /// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General ›
+ /// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the
+ /// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the
+ /// tool's options, the press's changes included, so the dropped press then stores the options
+ /// it puts back. A dropped Type press restores the prior selection. The freeform gradient
+ /// point selected once the tool took the press is selected again. A press held while the tool
+ /// computes an edit on another thread has not reached the tool: it is removed from the held
+ /// input with the pointer events and tool keys held after it, and the tool is left as it is.
+ /// A perspective plane key held after it stays held, since the plane it picks outlasts a
+ /// dropped press. Pointer events held after the last held release belong to the press the tool
+ /// has, and are removed with it.
pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> {
let (from, held) = self.held_press();
let keep: Vec = (self.held_input.iter().enumerate())
@@ -635,6 +644,7 @@ impl Session {
// Nothing to roll back without a document; the tool still drops the press and gets the release.
let _ = self.cancel_interaction();
let before = self.press_options.take();
+ let stored = std::mem::take(&mut self.press_options_stored);
let type_selection = self.press_type_selection.take();
let point = self.press_point.take();
let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx));
@@ -669,6 +679,11 @@ impl Session {
self.tool.set_option(k, v);
}
}
+ // An option set during the press stored every option the tool had then, the press's
+ // changes included: those stored values are put back too.
+ if stored {
+ self.keep_tool_settings();
+ }
}
r.map(drop)
}
@@ -706,6 +721,7 @@ impl Session {
match ev.kind {
PointerKind::Down => {
self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref())));
+ self.press_options_stored = false;
self.press_type_selection =
if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") {
self.active().map(|st| (st.selection.clone(), st.active_layer))
@@ -715,6 +731,7 @@ impl Session {
}
PointerKind::Up => {
self.press_options = None;
+ self.press_options_stored = false;
self.press_type_selection = None;
}
_ => {}
@@ -1309,9 +1326,12 @@ impl Session {
if key == "queue" && self.tool.id() == "place" {
self.note_place_queue_roots();
}
+ let before_press = self.options_before_press_set();
+ let sets_pressed = self.press_taken_by(self.tool.id());
self.tool.set_option(key, v);
self.tool_set_since_reset = true;
self.keep_tool_settings();
+ self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed);
}
/// Keep the automation roots in force now as those the place cursor's queue, being loaded,
@@ -1356,6 +1376,8 @@ impl Session {
self.note_place_queue_roots();
}
let active = id.is_none_or(|id| id == self.tool.id());
+ let before_press = self.options_before_press_set();
+ let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id()));
// The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again
// when the drag ends.
let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id));
@@ -1393,9 +1415,46 @@ impl Session {
let set = other.id();
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
}
+ self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed);
out
}
+ /// The tool that took the press under way: the active tool, or the tool that lent a selection
+ /// tool for it (a Cmd-drag), which the dropped press gives its options back to.
+ fn pressed_tool(&self) -> Option<&dyn Tool> {
+ let (pressed, _) = self.press_options.as_ref()?;
+ std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed)
+ }
+
+ /// Tool `id` took the press under way ([`Self::pressed_tool`]).
+ pub(crate) fn press_taken_by(&self, id: &str) -> bool {
+ self.pressed_tool().is_some_and(|t| t.id() == id)
+ }
+
+ /// The persistent options of the tool that took the press under way ([`Self::pressed_tool`])
+ /// before an option is set: a dropped press puts back the options it began with, except those
+ /// the set changes ([`Self::keep_press_set`]).
+ fn options_before_press_set(&self) -> Option> {
+ self.pressed_tool().map(Self::persistent_options)
+ }
+
+ /// After an option is set during a held press, the press's saved options take the options of
+ /// the tool that took the press that the set changed from `before` or named (`named`), so a
+ /// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes
+ /// included, so a dropped press stores the options it puts back.
+ fn keep_press_set(&mut self, before: Option>, named: impl Fn(&str) -> bool, stored: bool) {
+ let Some(before) = before else { return };
+ let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return };
+ self.press_options_stored |= stored;
+ if let Some((_, saved)) = self.press_options.as_mut() {
+ for (k, v) in now {
+ if before.get(&k) != Some(&v) || named(&k) {
+ saved.insert(k, v);
+ }
+ }
+ }
+ }
+
/// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the
/// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default:
/// the tool active when the call arrives, named before the edit in progress is finished) → its
@@ -1519,6 +1578,10 @@ impl Session {
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
pub fn apply_actions(&mut self, acts: Vec) -> Result> {
let outer = std::mem::replace(&mut self.in_tool_actions, true);
+ let outer_bucket = self.back_to_bucket;
+ // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket.
+ self.back_to_bucket |=
+ self.tool.id() == "eyedropper" && acts.iter().any(|a| matches!(a, Action::SwitchTool(t) if t == crate::cmd::LIVE_PAINT_BUCKET));
// A preview that settling applied (typing kept as its own step before a drag begins) shows
// its warning in the status bar, as the tool's own commit shows its preview's.
let r = if !outer && self.depth == 0 {
@@ -1528,6 +1591,7 @@ impl Session {
self.apply_tool_actions(acts)
};
self.in_tool_actions = outer;
+ self.back_to_bucket = outer_bucket;
if !outer && self.depth == 0 {
self.trim_histories();
}
diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs
new file mode 100644
index 0000000000..30326d8e74
--- /dev/null
+++ b/crates/engine/tests/direct_handle_mirror.rs
@@ -0,0 +1,630 @@
+//! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle.
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use serde_json::{Value, json};
+use vectorcraft_doc::{Node, NodeId};
+use vectorcraft_engine::{Session, ViewInfo};
+use vectorcraft_geom::{Anchor, AnchorKind, Point};
+use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
+
+fn run(s: &mut Session, command: &str, params: Value) -> Value {
+ s.execute(command, ¶ms).unwrap()
+}
+
+fn view() -> ViewInfo {
+ ViewInfo {
+ smart_guides: false,
+ guides: false,
+ snap_to_point: false,
+ snap_to_grid: false,
+ snap_to_pixel: false,
+ snap_to_glyph: false,
+ corner_widgets: false,
+ show_bbox: false,
+ ..ViewInfo::default()
+ }
+}
+
+fn session() -> Session {
+ let mut s = Session::new();
+ run(&mut s, "file.new", json!({"width": 900, "height": 700}));
+ for (key, value) in [("constrainAngle", json!(0)), ("showHandlesMultipleAnchors", json!(true)), ("realTimeDrawing", json!(true))] {
+ run(&mut s, "prefs.set", json!({"key": key, "value": value}));
+ }
+ s
+}
+
+fn node(s: &Session, id: NodeId) -> Node {
+ s.doc().unwrap().doc.node(id).unwrap().clone()
+}
+
+fn curve(s: &mut Session, incoming: Point) -> NodeId {
+ let id = run(
+ s,
+ "path.create",
+ json!({"anchors": [
+ {"x": 20, "y": 220},
+ {"x": 100, "y": 100, "in": [incoming.x, incoming.y], "out": [180, 100]},
+ {"x": 320, "y": 220}
+ ]}),
+ );
+ let id = NodeId(id["id"].as_u64().unwrap());
+ s.select_tool("directSelection", view()).unwrap();
+ id
+}
+
+fn anchor(s: &Session, id: NodeId) -> Anchor {
+ node(s, id).path_data().unwrap().subpaths[0].anchors[1]
+}
+
+fn pointer(s: &mut Session, kind: PointerKind, at: Point, mods: Mods) {
+ s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(mods), view()).unwrap();
+}
+
+fn press_handle(s: &mut Session, at: Point) {
+ pointer(s, PointerKind::Down, at, Mods::default());
+ assert_eq!(s.tool_id(), "directSelection");
+ assert!(s.in_interaction(), "the visible handle press begins Reshape");
+}
+
+fn near(actual: Point, expected: Point) {
+ assert!(actual.distance(expected) < 1e-6, "point {actual:?}, expected {expected:?}");
+}
+
+fn handles(a: Anchor, incoming: Point, outgoing: Point, kind: AnchorKind) {
+ near(a.h_in, incoming);
+ near(a.h_out, outgoing);
+ assert_eq!(a.kind, kind);
+}
+
+fn assert_other_geometry(s: &Session, id: NodeId, before: &Node) {
+ let after = node(s, id);
+ let (old, new) = (before.path_data().unwrap(), after.path_data().unwrap());
+ assert_eq!(new.subpaths.len(), old.subpaths.len());
+ assert_eq!(new.subpaths[0].closed, old.subpaths[0].closed);
+ assert_eq!(new.subpaths[0].anchors.len(), 3);
+ assert_eq!(new.subpaths[0].anchors[0], old.subpaths[0].anchors[0]);
+ assert_eq!(new.subpaths[0].anchors[2], old.subpaths[0].anchors[2]);
+ assert_eq!(new.subpaths[0].anchors[1].p, old.subpaths[0].anchors[1].p);
+ assert_eq!(after.appearance, before.appearance);
+}
+
+#[test]
+fn direct_handle_baseline_ordinary_smooth_keeps_the_opposite_length() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let before = node(&s, id);
+ assert_eq!(anchor(&s, id).kind, AnchorKind::Smooth);
+ let selection = json!(s.doc().unwrap().selection);
+ let undo = s.doc().unwrap().history.undo.len();
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
+ assert_other_geometry(&s, id, &before);
+ pointer(&mut s, PointerKind::Up, q, Mods::default());
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ assert_eq!(json!(s.doc().unwrap().selection), selection);
+}
+
+#[test]
+fn direct_handle_baseline_cmd_added_mid_drag_mirrors_the_opposite() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let before = node(&s, id);
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, q, Mods { cmd: true, ..Mods::default() });
+ handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth);
+ assert_other_geometry(&s, id, &before);
+ pointer(&mut s, PointerKind::Up, q, Mods { cmd: true, ..Mods::default() });
+}
+
+#[test]
+fn direct_handle_cmd_mirror_holds_through_a_space_translation() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth);
+ // Space moves the anchor and both handles; the opposite handle stays mirrored.
+ let moved = Point::new(200.0, 190.0);
+ pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() });
+ let a = anchor(&s, id);
+ near(a.p, Point::new(120.0, 130.0));
+ handles(a, Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth);
+ // Releasing Space without moving keeps the translated, mirrored handles.
+ pointer(&mut s, PointerKind::Drag, moved, cmd());
+ handles(anchor(&s, id), Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth);
+ let next = Point::new(220.0, 190.0);
+ pointer(&mut s, PointerKind::Drag, next, cmd());
+ assert_mirrored(anchor(&s, id), next, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Up, next, cmd());
+}
+
+#[test]
+fn direct_handle_modifiers_changed_during_a_space_translation_apply_at_once() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd());
+ let moved = Point::new(200.0, 190.0);
+ pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() });
+ handles(anchor(&s, id), Point::new(40.0, 70.0), moved, AnchorKind::Smooth);
+ // Releasing Cmd while Space is held gives the opposite handle its own length again.
+ pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..Mods::default() });
+ let a = anchor(&s, id);
+ near(a.p, Point::new(120.0, 130.0));
+ handles(a, Point::new(80.0, 100.0), moved, AnchorKind::Smooth);
+ // Alt while Space is held leaves the opposite handle where the translation put it.
+ pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, alt: true, ..cmd() });
+ handles(anchor(&s, id), Point::new(70.0, 130.0), moved, AnchorKind::Corner);
+ pointer(&mut s, PointerKind::Up, moved, Mods { alt: true, ..cmd() });
+}
+
+#[derive(Debug, PartialEq)]
+struct Snapshot {
+ document: Value,
+ selection: Value,
+ undo: usize,
+ redo: usize,
+}
+
+fn snapshot(s: &Session) -> Snapshot {
+ let st = s.doc().unwrap();
+ Snapshot { document: json!(st.doc), selection: json!(st.selection), undo: st.history.undo.len(), redo: st.history.redo.len() }
+}
+
+fn assert_content(s: &Session, expected: &Snapshot) {
+ let got = snapshot(s);
+ assert_eq!(got.document, expected.document);
+ assert_eq!(got.selection, expected.selection);
+}
+
+fn cmd() -> Mods {
+ Mods { cmd: true, ..Mods::default() }
+}
+
+fn reflected(a: Point, q: Point) -> Point {
+ a - (q - a)
+}
+
+fn constrained(a: Point, q: Point) -> Point {
+ a + vectorcraft_geom::constrain_angle_from(q - a, 45.0, 0.0)
+}
+
+fn assert_mirrored(a: Anchor, q: Point, kind: AnchorKind) {
+ handles(a, reflected(a.p, q), q, kind);
+}
+
+#[test]
+fn direct_handle_stationary_cmd_release_repress_commit_and_next_gesture() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let before = snapshot(&s);
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let q = Point::new(180.0, 160.0);
+ for (mods, opposite) in [(cmd(), Point::new(20.0, 40.0)), (Mods::default(), Point::new(60.0, 70.0)), (cmd(), Point::new(20.0, 40.0))] {
+ pointer(&mut s, PointerKind::Drag, q, mods);
+ handles(anchor(&s, id), opposite, q, AnchorKind::Smooth);
+ assert_eq!(s.doc().unwrap().history.undo.len(), before.undo, "previews are not separate edits");
+ }
+ pointer(&mut s, PointerKind::Up, q, cmd());
+ let committed = snapshot(&s);
+ assert_eq!(committed.undo, before.undo + 1);
+ assert_eq!(committed.selection, before.selection);
+ run(&mut s, "edit.undo", json!({}));
+ assert_content(&s, &before);
+ run(&mut s, "edit.redo", json!({}));
+ assert_content(&s, &committed);
+ // Cmd did not install a persistent coupling mode: a later ordinary Smooth drag keeps
+ // the opposite handle's committed length, rather than matching the newly dragged length.
+ press_handle(&mut s, q);
+ let next = Point::new(180.0, 200.0);
+ pointer(&mut s, PointerKind::Drag, next, Mods::default());
+ let a = anchor(&s, id);
+ near(a.h_out, next);
+ assert_eq!(a.kind, AnchorKind::Smooth);
+ assert!((a.h_in.distance(a.p) - 100.0).abs() < 1e-6);
+ assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 20.0);
+ assert!(((a.h_in - a.p).cross(a.h_out - a.p)).abs() < 1e-6);
+ pointer(&mut s, PointerKind::Up, next, Mods::default());
+ assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 2);
+}
+
+#[test]
+fn direct_handle_shift_constrains_before_mirroring_and_alt_takes_priority() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let p = anchor(&s, id).p;
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let raw = Point::new(180.0, 150.0);
+ let q = constrained(p, raw);
+ let shifted = Mods { shift: true, ..cmd() };
+ pointer(&mut s, PointerKind::Drag, raw, shifted);
+ assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..shifted });
+ handles(anchor(&s, id), Point::new(50.0, 100.0), q, AnchorKind::Corner);
+ // Removing Alt rebuilds from the original Smooth anchor, not the Corner preview.
+ pointer(&mut s, PointerKind::Drag, raw, shifted);
+ assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..cmd() });
+ handles(anchor(&s, id), Point::new(50.0, 100.0), raw, AnchorKind::Corner);
+ pointer(&mut s, PointerKind::Up, raw, Mods { alt: true, ..cmd() });
+}
+
+#[test]
+fn direct_handle_corner_with_collapsed_partner_is_reversible_without_changing_kind() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(100.0, 100.0));
+ let before = snapshot(&s);
+ assert_eq!(anchor(&s, id).kind, AnchorKind::Corner);
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_mirrored(anchor(&s, id), q, AnchorKind::Corner);
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ handles(anchor(&s, id), Point::new(100.0, 100.0), q, AnchorKind::Corner);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_mirrored(anchor(&s, id), q, AnchorKind::Corner);
+ s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap();
+ assert_eq!(snapshot(&s), before);
+}
+
+#[test]
+fn direct_handle_stationary_drag_still_mirrors_unequal_partner_but_equal_is_noop() {
+ for (incoming, changes) in [(Point::new(50.0, 100.0), true), (Point::new(20.0, 100.0), false)] {
+ let mut s = session();
+ let id = curve(&mut s, incoming);
+ let before = snapshot(&s);
+ let q = Point::new(180.0, 100.0);
+ press_handle(&mut s, q);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Up, q, cmd());
+ if changes {
+ assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1);
+ run(&mut s, "edit.undo", json!({}));
+ assert_content(&s, &before);
+ } else {
+ assert_eq!(snapshot(&s), before, "an already reflected pair records no edit");
+ }
+ }
+}
+
+#[test]
+fn direct_handle_escape_restores_document_selection_and_existing_redo() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ run(&mut s, "shape.rectangle", json!({"x": 500, "y": 400, "width": 25, "height": 30}));
+ let redo_document = snapshot(&s).document;
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "select.set", json!({"ids": [id.0]}));
+ let before = snapshot(&s);
+ assert_eq!(before.redo, 1, "a real existing Redo is the cancellation control");
+ press_handle(&mut s, Point::new(180.0, 100.0));
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
+ s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap();
+ assert!(!s.in_interaction());
+ assert_eq!(snapshot(&s), before);
+ pointer(&mut s, PointerKind::Up, q, Mods::default());
+ assert_eq!(snapshot(&s), before, "a later release does not commit the canceled preview");
+ run(&mut s, "edit.redo", json!({}));
+ assert_eq!(snapshot(&s).document, redo_document, "the prior Redo still restores its actual content");
+}
+
+#[test]
+fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let before = snapshot(&s);
+ let a = anchor(&s, id);
+ pointer(&mut s, PointerKind::Down, a.p, cmd());
+ assert_eq!(s.tool_id(), "selection", "Cmd before Down keeps the existing Selection loan");
+ pointer(&mut s, PointerKind::Up, a.p, cmd());
+ assert_eq!(s.tool_id(), "directSelection");
+ assert_eq!(anchor(&s, id), a);
+ assert_eq!(snapshot(&s).document, before.document);
+ assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
+}
+
+#[test]
+fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ s.select_tool("pen", view()).unwrap();
+ let before = node(&s, id);
+ let undo = s.doc().unwrap().history.undo.len();
+ pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd());
+ assert_eq!(s.tool_id(), "directSelection", "Cmd lends the Pen the last selection tool");
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
+ // Cmd let go and pressed again during the drag mirrors, as it does in Direct Selection itself.
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth);
+ assert_other_geometry(&s, id, &before);
+ pointer(&mut s, PointerKind::Up, q, cmd());
+ assert_eq!(s.tool_id(), "pen");
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+}
+
+#[test]
+fn direct_handle_cmd_held_through_a_pen_lent_drag_leaves_the_opposite_length() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ s.select_tool("pen", view()).unwrap();
+ pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd());
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ pointer(&mut s, PointerKind::Up, q, cmd());
+ assert_eq!(s.tool_id(), "pen");
+ handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
+}
+
+fn text_anchor(s: &Session, id: NodeId) -> Anchor {
+ let n = node(s, id);
+ let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") };
+ t.type_path().unwrap().subpaths[0].anchors[1]
+}
+
+fn text_properties(s: &Session, id: NodeId) -> Value {
+ let n = node(s, id);
+ let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") };
+ let vectorcraft_doc::TextKind::OnPath { start, end, .. } = &t.kind else { panic!("path text") };
+ json!({"runs": t.runs, "para": t.para, "paras": t.paras, "xf": t.xf, "start": start, "end": end,
+ "effect": t.path_effect, "align": t.path_align, "spacing": t.path_spacing, "appearance": n.appearance})
+}
+
+fn path_text(s: &mut Session) -> NodeId {
+ let path = curve(s, Point::new(50.0, 100.0));
+ let made = run(
+ s,
+ "text.createInPath",
+ json!({"path": path.0, "mode": "onPath", "text": "Along the original curve", "font": "Source Sans 3", "size": 12}),
+ );
+ let id = NodeId(made["id"].as_u64().unwrap());
+ run(s, "type.pathOptions", json!({"id": id.0, "start": 0.15, "end": 0.85}));
+ run(s, "object.transform", json!({"ids": [id.0], "matrix": [1.5, 0.4, 0.25, 0.9, 250, 80]}));
+ s.select_tool("directSelection", view()).unwrap();
+ id
+}
+
+#[test]
+fn direct_handle_affine_path_text_mirrors_in_drawn_space_and_keeps_brackets() {
+ let mut s = session();
+ let id = path_text(&mut s);
+ let before = snapshot(&s);
+ let properties = text_properties(&s, id);
+ assert_eq!(properties["start"], json!(0.15));
+ assert_eq!(properties["end"], json!(0.85));
+ let a = text_anchor(&s, id);
+ assert_eq!(a.kind, AnchorKind::Smooth);
+ near(a.p, Point::new(425.0, 210.0));
+ near(a.h_out, Point::new(545.0, 242.0));
+ assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 40.0);
+ press_handle(&mut s, a.h_out);
+ let raw = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0);
+ pointer(&mut s, PointerKind::Drag, raw, cmd());
+ assert_mirrored(text_anchor(&s, id), raw, AnchorKind::Smooth);
+ assert_eq!(text_properties(&s, id), properties);
+ let shifted = Mods { shift: true, ..cmd() };
+ pointer(&mut s, PointerKind::Drag, raw, shifted);
+ assert_mirrored(text_anchor(&s, id), constrained(a.p, raw), AnchorKind::Smooth);
+ assert_eq!(text_properties(&s, id), properties);
+ pointer(&mut s, PointerKind::Up, raw, shifted);
+ let after = snapshot(&s);
+ assert_eq!(after.undo, before.undo + 1);
+ run(&mut s, "edit.undo", json!({}));
+ assert_content(&s, &before);
+ run(&mut s, "edit.redo", json!({}));
+ assert_content(&s, &after);
+}
+
+fn blend_state(s: &Session, id: NodeId) -> (Anchor, Value, Vec) {
+ let n = node(s, id);
+ let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") };
+ assert!(spec.spine.is_some(), "the fixture uses an already pinned spine");
+ let path = vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0;
+ (path.subpaths[0].anchors[1], json!(children), spec.key_anchors.clone())
+}
+
+fn blend(s: &mut Session) -> NodeId {
+ let a = run(s, "shape.rectangle", json!({"x": 15, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap();
+ let b = run(s, "shape.rectangle", json!({"x": 295, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap();
+ let made = run(s, "object.blend.make", json!({"ids": [a, b], "steps": 2}));
+ let id = NodeId(made["id"].as_u64().unwrap());
+ let added = run(s, "object.blend.spine.addAnchor", json!({"id": id.0, "x": 100, "y": 100}));
+ assert_eq!(added["anchor"], json!(1));
+ run(s, "object.blend.spine.convertAnchor", json!({"id": id.0, "anchor": 1, "to": "smooth", "x": 180, "y": 100}));
+ run(s, "object.blend.spine.moveAnchor", json!({"id": id.0, "anchor": 1, "handle": "in", "x": 50, "y": 100}));
+ run(s, "select.set", json!({"ids": [id.0]}));
+ s.select_tool("directSelection", view()).unwrap();
+ let (middle, _, keys) = blend_state(s, id);
+ near(middle.p, Point::new(100.0, 100.0));
+ handles(middle, Point::new(50.0, 100.0), Point::new(180.0, 100.0), AnchorKind::Smooth);
+ assert_eq!(keys, [0, 2]);
+ // An actual spine-point click makes its handles visible to Direct Selection.
+ pointer(s, PointerKind::Down, middle.p, Mods::default());
+ pointer(s, PointerKind::Up, middle.p, Mods::default());
+ assert!(!s.in_interaction());
+ id
+}
+
+#[test]
+fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
+ let mut s = session();
+ let id = blend(&mut s);
+ let before = snapshot(&s);
+ let (a, keys, mapping) = blend_state(&s, id);
+ press_handle(&mut s, a.h_out);
+ let q = Point::new(180.0, 160.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_mirrored(blend_state(&s, id).0, q, AnchorKind::Smooth);
+ let raw = Point::new(180.0, 150.0);
+ let shifted = Mods { shift: true, ..cmd() };
+ pointer(&mut s, PointerKind::Drag, raw, shifted);
+ assert_mirrored(blend_state(&s, id).0, constrained(a.p, raw), AnchorKind::Smooth);
+ // The existing spine Shift-only path is deliberately unconstrained; Cmd's new rule
+ // must not leak into that old branch after the modifier is released.
+ pointer(&mut s, PointerKind::Drag, raw, Mods { shift: true, ..Mods::default() });
+ near(blend_state(&s, id).0.h_out, raw);
+ pointer(&mut s, PointerKind::Drag, raw, shifted);
+ let (after_anchor, after_keys, after_mapping) = blend_state(&s, id);
+ assert_mirrored(after_anchor, constrained(a.p, raw), AnchorKind::Smooth);
+ assert_eq!(after_keys, keys, "handle edits leave the actual key art unchanged");
+ assert_eq!(after_mapping, mapping);
+ pointer(&mut s, PointerKind::Up, raw, shifted);
+ let after = snapshot(&s);
+ assert_eq!(after.undo, before.undo + 1);
+ assert_eq!(after.selection, before.selection);
+ run(&mut s, "edit.undo", json!({}));
+ assert_content(&s, &before);
+ run(&mut s, "edit.redo", json!({}));
+ assert_content(&s, &after);
+}
+
+#[test]
+fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let before = snapshot(&s);
+ let original = node(&s, id);
+ press_handle(&mut s, Point::new(50.0, 100.0));
+ let q = Point::new(40.0, 20.0);
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_other_geometry(&s, id, &original);
+ pointer(&mut s, PointerKind::Up, q, cmd());
+ handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth);
+ assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1);
+ assert_eq!(snapshot(&s).selection, before.selection);
+ run(&mut s, "edit.undo", json!({}));
+ assert_content(&s, &before);
+}
+
+/// `command` with `params` is refused with an error containing `message`, and the document,
+/// selection and undo history stay as they were.
+fn refused(s: &mut Session, command: &str, params: Value, message: &str) {
+ let before = snapshot(s);
+ let err = s.execute(command, ¶ms).unwrap_err().to_string();
+ assert!(err.contains(message), "{command} {params}: {err}");
+ assert_eq!(snapshot(s), before);
+}
+
+#[test]
+fn path_set_handle_symmetric_mirrors_refuses_bad_values_and_records_no_step_when_in_place() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let at = |x: f64, y: f64| json!({"id": id.0, "anchor": 1, "which": "out", "x": x, "y": y});
+ for bad in [json!("yes"), json!(1)] {
+ let mut p = at(180.0, 160.0);
+ p["symmetric"] = bad;
+ refused(&mut s, "path.setHandle", p, "`symmetric` must be true or false");
+ }
+ let mut both = at(180.0, 160.0);
+ both["symmetric"] = json!(true);
+ both["independent"] = json!(true);
+ refused(&mut s, "path.setHandle", both, "`independent` and `symmetric` cannot both be true");
+
+ let undo = s.doc().unwrap().history.undo.len();
+ let mut mirror = at(180.0, 160.0);
+ mirror["symmetric"] = json!(true);
+ run(&mut s, "path.setHandle", mirror.clone());
+ handles(anchor(&s, id), Point::new(20.0, 40.0), Point::new(180.0, 160.0), AnchorKind::Smooth);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ let placed = snapshot(&s);
+ run(&mut s, "path.setHandle", mirror);
+ assert_eq!(snapshot(&s), placed, "both handles already in place record no undo step");
+}
+
+#[test]
+fn symmetric_leaves_the_other_handle_retracted_at_an_open_end() {
+ let mut s = session();
+ let id = curve(&mut s, Point::new(50.0, 100.0));
+ let first = |s: &Session| node(s, id).path_data().unwrap().subpaths[0].anchors[0];
+ let p = first(&s).p;
+ run(&mut s, "path.setHandle", json!({"id": id.0, "anchor": 0, "which": "out", "x": 60, "y": 180, "symmetric": true}));
+ handles(first(&s), p, Point::new(60.0, 180.0), AnchorKind::Corner);
+
+ let mut s = session();
+ let blend_id = blend(&mut s);
+ let end = |s: &Session| {
+ let n = node(s, blend_id);
+ let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") };
+ vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0.subpaths[0].anchors[0]
+ };
+ let start = end(&s);
+ run(&mut s, "object.blend.spine.moveAnchor", json!({"id": blend_id.0, "anchor": 0, "handle": "out", "x": 60, "y": 60, "symmetric": true}));
+ near(end(&s).h_out, Point::new(60.0, 60.0));
+ near(end(&s).h_in, start.h_in);
+ near(end(&s).h_in, start.p);
+}
+
+#[test]
+fn spine_and_type_path_handles_refuse_bad_symmetric_values() {
+ let mut s = session();
+ let id = blend(&mut s);
+ let spine = |extra: Value| {
+ let mut p = json!({"id": id.0, "anchor": 1, "handle": "out", "x": 180, "y": 160});
+ p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ p
+ };
+ refused(&mut s, "object.blend.spine.moveAnchor", spine(json!({"symmetric": "yes"})), "`symmetric` must be true or false");
+ refused(
+ &mut s,
+ "object.blend.spine.moveAnchor",
+ spine(json!({"symmetric": true, "independent": true})),
+ "`independent` and `symmetric` cannot both be true",
+ );
+ refused(
+ &mut s,
+ "object.blend.spine.moveAnchor",
+ json!({"id": id.0, "anchor": 1, "x": 180, "y": 160, "symmetric": true}),
+ "`symmetric` places a handle",
+ );
+
+ let text = path_text(&mut s);
+ let a = text_anchor(&s, text);
+ let at = json!({"id": text.0, "anchor": 1, "which": "out", "x": a.h_out.x, "y": a.h_out.y + 20.0});
+ let mut bad = at.clone();
+ bad["symmetric"] = json!(0);
+ refused(&mut s, "text.setPathHandle", bad, "`symmetric` must be true or false");
+ let mut both = at;
+ both["symmetric"] = json!(true);
+ both["independent"] = json!(true);
+ refused(&mut s, "text.setPathHandle", both, "`independent` and `symmetric` cannot both be true");
+}
+
+#[test]
+fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror_type_on_a_path() {
+ let mut s = session();
+ let id = path_text(&mut s);
+ let a = text_anchor(&s, id);
+ let length = a.h_in.distance(a.p);
+ s.select_tool("pen", view()).unwrap();
+ pointer(&mut s, PointerKind::Down, a.h_out, cmd());
+ assert_eq!(s.tool_id(), "directSelection");
+ let q = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0);
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ let held = text_anchor(&s, id);
+ near(held.h_out, q);
+ assert!((held.h_in.distance(held.p) - length).abs() < 1e-6, "the other handle keeps its length");
+ pointer(&mut s, PointerKind::Drag, q, Mods::default());
+ pointer(&mut s, PointerKind::Drag, q, cmd());
+ assert_mirrored(text_anchor(&s, id), q, AnchorKind::Smooth);
+ pointer(&mut s, PointerKind::Up, q, cmd());
+ assert_eq!(s.tool_id(), "pen");
+}
diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs
index 17177671cf..88daf4d7a1 100644
--- a/crates/eps/src/ai_editing.rs
+++ b/crates/eps/src/ai_editing.rs
@@ -118,7 +118,12 @@
//! `%AI24_EndSymbolList`); each instance as `/SymbolInstance :`, `(name) /SymbolRef ,`, the
//! matrix taking the art to art space as `a b c d tx ty /RTransformMatrix`, `;`, then its name
//! and opacity mask and a state block as a group's with its opacity and blending mode (an
-//! instance with isolation, knockout or knockout shape of its own is written as its art). The
+//! instance with isolation, knockout or knockout shape of its own is written as its art). A
+//! dynamic symbol's art dictionary also holds `VectorCraftDynamicSymbol` (`/Int`, 1), and the
+//! dictionary of an instance with changes of its own (`symbol_overrides`) holds
+//! `VectorCraftSymbolOverrides`, a `/String` of the changes as hex-coded JSON: the format's own
+//! entries, as other apps' editing data is not documented, read back by this reader and left out by
+//! others. The
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
//! a gradient's take the art to the canvas's space turned y up about art space's origin there,
//! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are
@@ -191,7 +196,7 @@
//! and instances of
//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects
//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice
-//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as
+//! guides, export types left out, gradient meshes the reader wouldn't read back as
//! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh
//! on a large canvas as their drawn look, blends the reader wouldn't read back live as
//! their steps, other live objects (placed documents included) as their art,
@@ -220,6 +225,7 @@ use vectorcraft_pdf::PrivateData;
use crate::ps;
mod writer;
+pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
use writer::Writer;
diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs
index 22d3203e3b..3fc99847d6 100644
--- a/crates/eps/src/ai_editing/tests.rs
+++ b/crates/eps/src/ai_editing/tests.rs
@@ -2432,6 +2432,26 @@ fn an_unpainted_paths_transparency_after_a_compound_path_is_its_own() {
assert_eq!((art[0].opacity, art[0].blend, art[1].opacity, art[1].blend), (1.0, BlendMode::Normal, 0.5, BlendMode::Multiply));
}
+/// A distorted image as deep as the writer goes, in the art of 8 nested opacity masks, is written
+/// as one image at the placement nearest its corners, with a warning, not left out.
+#[test]
+fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement() {
+ let mut doc = Document::new(200.0, 100.0);
+ let layer = doc.layers[0].id;
+ let mut n = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::translate((10.0, 10.0)) * Affine::scale(10.0), None);
+ n.set_image_corners([(14.0, 10.0), (36.0, 10.0), (40.0, 30.0), (10.0, 30.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap();
+ for _ in 0..8 {
+ let mut owner = square(&mut doc, Rect::new(10.0, 10.0, 40.0, 30.0), Color::gray(0.5));
+ owner.extras_mut().mask = Some(Box::new(OpacityMask::new(n, true)));
+ n = owner;
+ }
+ doc.insert(Some(layer), usize::MAX, n).unwrap();
+ let out = export_ai_editing(&doc, &opts()).unwrap();
+ assert!(out.warnings.iter().any(|w| w == writer::DEEP_DISTORTED), "{:?}", out.warnings);
+ // The samples are binary: count the `XI` lines in the bytes.
+ assert_eq!(out.program.windows(4).filter(|w| w == b"XI\r\n").count(), 1, "the one image");
+}
+
/// Opacity masks in mask art nested past the limit are left out, not written empty.
#[test]
fn opacity_masks_nested_too_deep_are_left_out() {
@@ -6394,7 +6414,8 @@ fn instances_the_data_cant_hold_are_written_as_their_art() {
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, changed).unwrap();
doc.insert(Some(layer), usize::MAX, plain).unwrap();
- assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART, writer::SYMBOL_OPTIONS]);
+ doc.symbols[0].dynamic = false;
+ assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]);
let back = read_back(&doc);
assert_eq!(kinds(&back), ["art", "instance"]);
let green = back.layers[0].children().unwrap()[0].clone();
@@ -6890,7 +6911,7 @@ fn symbol_options_and_linked_images_in_symbols_are_reported() {
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, one).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
- assert_eq!(out.warnings, [writer::SYMBOL_OPTIONS, writer::LINKS_EMBEDDED]);
+ assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]);
let p = program_shown(&doc);
assert!(p.contains("%AI5_BeginRaster") && !p.contains("%AI5_BeginPlace"), "{p}");
let back = read_back(&doc);
@@ -15982,3 +16003,56 @@ fn a_mesh_eight_levels_down_is_written_as_a_mesh() {
assert_eq!(back.len(), 1, "{back:#?}");
assert_mesh_exact(mesh_of(&back[0]), &want, "eight levels down");
}
+
+fn dynamic_doc() -> Document {
+ let mut doc = Document::new(200.0, 100.0);
+ let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF);
+ doc.symbols.push(Symbol { dynamic: true, name: "Leaf".into(), art: Arc::new(art) });
+ let layer = doc.layers[0].id;
+ for (x, c) in [(10.0, Color::rgb(1.0, 0.0, 0.0)), (50.0, Color::rgb(0.0, 0.0, 1.0))] {
+ let mut i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0)));
+ i.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { fill: Some(solid(c)), opacity: Some(0.5), ..Default::default() }];
+ doc.insert(Some(layer), usize::MAX, i).unwrap();
+ }
+ let plain = instance(&mut doc, "Leaf", Affine::translate((90.0, 10.0)));
+ doc.insert(Some(layer), usize::MAX, plain).unwrap();
+ doc
+}
+
+#[test]
+fn dynamic_symbols_and_their_instance_changes_survive_a_round_trip() {
+ let doc = dynamic_doc();
+ let out = export_ai_editing(&doc, &opts()).unwrap();
+ assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]);
+ let back = read_back(&doc);
+ assert!(back.symbols[0].dynamic);
+ let kids = back.layers[0].children().unwrap();
+ assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })));
+ let want: Vec<_> = doc.layers[0].children().unwrap().iter().map(|n| n.extras().symbol_overrides.clone()).collect();
+ let got: Vec<_> = kids.iter().map(|n| n.extras().symbol_overrides.clone()).collect();
+ assert_eq!(got, want);
+ assert_ne!(got[0], got[1]);
+ assert!(got[2].is_empty());
+}
+
+#[test]
+fn static_symbols_write_no_dynamic_entries() {
+ let mut doc = dynamic_doc();
+ doc.symbols[0].dynamic = false;
+ let layer = doc.layers[0].id;
+ for n in doc.layers[0].children().unwrap().to_vec() {
+ doc.remove(n.id).unwrap();
+ }
+ for x in [10.0, 50.0] {
+ let i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0)));
+ doc.insert(Some(layer), usize::MAX, i).unwrap();
+ }
+ let p = program(&doc);
+ assert!(!p.contains("VectorCraftDynamicSymbol") && !p.contains("VectorCraftSymbolOverrides"));
+ assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty());
+ let back = read_back(&doc);
+ assert!(!back.symbols[0].dynamic);
+ let kids = back.layers[0].children().unwrap();
+ assert_eq!(kids.len(), 2);
+ assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }) && n.extras().symbol_overrides.is_empty()));
+}
diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs
index 41254840cb..263353c675 100644
--- a/crates/eps/src/ai_editing/writer.rs
+++ b/crates/eps/src/ai_editing/writer.rs
@@ -48,8 +48,9 @@ pub(super) use paints::{
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
SWATCH_PLACEMENT, free_gradient_name,
};
+pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
#[cfg(test)]
-pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
+pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS};
#[cfg(test)]
pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES};
#[cfg(test)]
@@ -66,7 +67,9 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
-pub(super) const LIVE: &str = "repeats, placed documents and intertwines are written as their art in the editing data for other apps";
+pub(super) const LIVE: &str =
+ "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps";
+pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort more than 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps";
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
pub(super) const ITEM_TRANSPARENCY: &str =
@@ -286,6 +289,7 @@ pub(super) struct Writer<'a> {
symbol_scales: HashMap,
/// The entries a symbol's dictionary adds to its art's dictionary, and the art's id.
root_entries: Option<(vectorcraft_doc::NodeId, String)>,
+ instance_entries: Option<(vectorcraft_doc::NodeId, String)>,
/// The objects that may be written with an art style, as they were before baking, by id
/// ([`styles::styled_objects`]).
pub(super) styled: HashMap>,
@@ -405,6 +409,7 @@ impl<'a> Writer<'a> {
inner_scale: 1.0,
symbol_scales: HashMap::new(),
root_entries: None,
+ instance_entries: None,
styled: HashMap::new(),
symbol_styled: HashMap::new(),
pattern_styled: HashMap::new(),
@@ -799,6 +804,7 @@ impl<'a> Writer<'a> {
}
NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy),
NodeKind::Text(_) => self.text(n, xy),
+ NodeKind::Image(im) if n.is_distorted_image() => self.distorted_image(n, im, xy),
NodeKind::Image(im) => {
// An opacity mask that clips shows the image within what its art paints only (its
// effects and its symbol instances' art included, as the renderer measures it).
@@ -818,7 +824,7 @@ impl<'a> Writer<'a> {
mask_window = self.windowed.take();
}
}
- NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy),
+ NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(n, symbol, *xf, xy),
NodeKind::SymbolInstance { symbol, xf } => {
if !self.open_group("u") {
return;
@@ -944,6 +950,18 @@ impl<'a> Writer<'a> {
self.warn(GRAPHS);
}
+ /// Distorted image `n` (`im`), of transparency `xy`: the mesh of its pieces while the art may
+ /// nest further, else one image at the placement nearest its corners, with a warning.
+ fn distorted_image(&mut self, n: &Node, im: &vectorcraft_doc::ImageObject, xy: Xy) {
+ if self.nest < MAX_NEST {
+ return self.drawn_art(n, xy, Some(LIVE), true);
+ }
+ let Some(near) = vectorcraft_doc::image_quad::nearest_affine(n) else { return };
+ self.warn(DEEP_DISTORTED);
+ self.windowed = None;
+ self.image(&vectorcraft_doc::ImageObject { xf: near, ..self.doc.shown_image(n, im).into_owned() }, xy);
+ }
+
/// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given.
/// With `bounds`, `n`'s text wrap options go on the rectangle of its bounds, the group's first
/// member ([`Self::wrap_on_bounds`]); without it, in the group's dictionary.
@@ -1016,6 +1034,10 @@ impl<'a> Writer<'a> {
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
_ => None,
};
+ let entries = match &self.instance_entries {
+ Some((id, _)) if *id == n.id => entries.or_else(|| self.instance_entries.take().map(|(_, e)| e)),
+ _ => entries,
+ };
let role = match &self.blend_role {
Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e),
_ => None,
diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs
index 4d4bb2acba..a616d748d1 100644
--- a/crates/eps/src/ai_editing/writer/symbols.rs
+++ b/crates/eps/src/ai_editing/writer/symbols.rs
@@ -14,7 +14,27 @@ use crate::ps;
pub(in crate::ai_editing) const SYMBOL_ART: &str = "symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects, instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times, instances on the layers of a large canvas and instances of symbols past 4,096 are written as their art in the editing data for other apps";
pub(in crate::ai_editing) const SYMBOL_OPTIONS: &str =
- "the 9-slice guides, export types and dynamic type of symbols are left out of the editing data for other apps";
+ "the 9-slice guides and export types of symbols are left out of the editing data for other apps";
+pub(in crate::ai_editing) const SYMBOL_CHANGES: &str =
+ "the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out";
+pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol";
+pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides";
+const MAX_OVERRIDES_BYTES: usize = 1 << 20;
+
+pub(crate) fn hex_decode(s: &str) -> Option> {
+ if !s.len().is_multiple_of(2) || s.len() / 2 > MAX_OVERRIDES_BYTES {
+ return None;
+ }
+ s.as_bytes().chunks(2).map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()).collect()
+}
+
+fn hex_encode(b: &[u8]) -> String {
+ b.iter().fold(String::with_capacity(b.len() * 2), |mut s, v| {
+ let _ = write!(s, "{v:02x}");
+ s
+ })
+}
+
pub(in crate::ai_editing) const MISSING_SYMBOL: &str =
"symbol instances of symbols the document doesn't have are written as empty groups in the editing data for other apps";
/// The most an instance may scale its symbol's art, nested instances' scales included: the art's
@@ -55,7 +75,8 @@ impl Writer<'_> {
/// that keeps the art's area as it is written and scales it as the definition allows
/// ([`Self::keeps_scale`]).
pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool {
- let own = vectorcraft_brush::stain(n).is_some() || !n.extras().symbol_overrides.is_empty();
+ let dynamic = self.symbol_doc.symbols.iter().any(|s| s.name == symbol && s.dynamic);
+ let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !n.extras().symbol_overrides.is_empty());
let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape;
// The matrix as written (to ten decimals) must still keep the art's area.
let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10));
@@ -153,7 +174,16 @@ impl Writer<'_> {
/// canvas's space turned y up about art space's origin there) as `a b c d tx ty
/// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd`
/// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two.
- pub(super) fn symbol_instance(&mut self, symbol: &str, xf: Affine, xy: Xy) {
+ pub(super) fn symbol_instance(&mut self, n: &Node, symbol: &str, xf: Affine, xy: Xy) {
+ let o = &n.extras().symbol_overrides;
+ if !o.is_empty()
+ && let Ok(json) = serde_json::to_vec(o)
+ && json.len() <= MAX_OVERRIDES_BYTES
+ {
+ let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes()));
+ self.instance_entries = Some((n.id, e));
+ self.warn(SYMBOL_CHANGES);
+ }
let m = self.instance_space * xf;
let _ = write!(self.body, "/SymbolInstance :\n{} /SymbolRef ,\n", ps::bytes(symbol.as_bytes()));
for v in m.as_coeffs() {
@@ -201,7 +231,7 @@ impl Writer<'_> {
self.warn(SYMBOL_COUNT);
return false;
}
- if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() {
+ if doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() {
self.warn(SYMBOL_OPTIONS);
}
// The art's effects are its own, not those of a drawn look that first places it, and its
@@ -260,7 +290,10 @@ impl Writer<'_> {
(self.to_art, self.grad_space, self.canvas, self.instance_space) = (Affine::IDENTITY, about_origin, Affine::IDENTITY, about_origin);
self.block_end = usize::MAX;
let registration = u16::from(doc.symbol_registration(name).0.min(8)) + 1;
- let entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n");
+ let mut entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n");
+ if sym.dynamic {
+ let _ = writeln!(entries, "%_1 /Int ({DYNAMIC_KEY}) ,");
+ }
// The canvas draws a symbol's art even when its root is hidden, so the root is written shown.
let shown;
let root: &Node = if sym.art.visible {
diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs
index 55adb56a7c..4c5b48c04d 100644
--- a/crates/eps/src/import/ai/read/directives.rs
+++ b/crates/eps/src/import/ai/read/directives.rs
@@ -627,7 +627,7 @@ impl<'a> Reader<'a> {
|| sub.mesh.is_some()
|| sub.gradient_def.is_some();
let head = sub.symbol.take().unwrap_or_default();
- let registration = head.registration;
+ let (registration, dynamic) = (head.registration, head.dynamic);
let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1;
let Some(frame) = sub.frames.pop().filter(|_| measured) else { return };
let mut kids = frame.children;
@@ -669,7 +669,7 @@ impl<'a> Reader<'a> {
}
}
let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name });
- self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false });
+ self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic });
if let Some(reg) = registration.and_then(symbol_registration) {
self.doc.set_symbol_registration(&named, reg);
}
diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs
index 29463daa85..ae2772a3c9 100644
--- a/crates/eps/src/import/ai/read/document.rs
+++ b/crates/eps/src/import/ai/read/document.rs
@@ -783,6 +783,19 @@ impl<'a> Reader<'a> {
{
head.registration = Some(*r);
}
+ if self.frames.len() == 1
+ && let Some(head) = self.symbol.as_mut()
+ && o.nums(crate::ai_editing::DYNAMIC_KEY).first().is_some_and(|v| *v != 0.0)
+ {
+ head.dynamic = true;
+ }
+ if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY)
+ && let Some(bytes) = crate::ai_editing::hex_decode(&text)
+ && let Ok(list) = serde_json::from_slice::>(&bytes)
+ && let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
+ {
+ n.extras_mut().symbol_overrides = list.into_iter().filter(|s| !s.is_empty()).collect();
+ }
self.constraint_art(o);
self.placed_page(o);
// A blend's key object or spine.
diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs
index 02d4a3354a..a155d9f505 100644
--- a/crates/eps/src/import/ai/read/types.rs
+++ b/crates/eps/src/import/ai/read/types.rs
@@ -244,6 +244,7 @@ pub(super) struct PatternHead {
pub(super) struct SymbolHead {
/// `AI13PatternRegistrationType` in the dictionary after the art.
pub(super) registration: Option,
+ pub(super) dynamic: bool,
/// Art the reader left out (type, a placed file, non-native art, an image it can't read or
/// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the
/// page draws them, within the box of the rest.
diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs
index ea569c94a5..d1ae8ef9ab 100644
--- a/crates/eps/src/legacy_ai.rs
+++ b/crates/eps/src/legacy_ai.rs
@@ -128,7 +128,9 @@ const CONIC_WEDGES: usize = 360;
const STROKES: &str =
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
-const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art";
+const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art";
+const DEEP_DISTORTED: &str =
+ "images changed by Perspective Distort or Free Distort more than 8 deep in symbols and live objects are written as the nearest parallelogram";
const GRAPHS: &str = "graphs are written as their art, without their data or settings";
/// The warning for an image left out because it can't be decoded: the note raster exports give
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs
index 108c90c2fc..6018bc6920 100644
--- a/crates/eps/src/legacy_ai/tests.rs
+++ b/crates/eps/src/legacy_ai/tests.rs
@@ -703,6 +703,25 @@ fn picture(doc: &mut Document, r: Rect) -> Node {
)
}
+/// A distorted image as deep as the writer goes, the art of the innermost of 8 nested symbols, is
+/// written as one image at the placement nearest its corners, with a warning, not left out.
+#[test]
+fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement() {
+ let mut doc = Document::new(200.0, 100.0);
+ let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0));
+ art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap();
+ for i in 0..8 {
+ let name = format!("S{i}");
+ doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) });
+ art = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY });
+ }
+ doc.insert(doc.default_layer(), usize::MAX, art).unwrap();
+ let out = write(&doc);
+ assert!(out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings);
+ let text = String::from_utf8(out.bytes).unwrap();
+ assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image");
+}
+
/// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group
/// holding an image and an image; a layer `Above` holding an orange square. Without `images`,
/// `Below` is empty.
diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs
index 2e5510d3d0..7e7dbfe4fc 100644
--- a/crates/eps/src/legacy_ai/writer.rs
+++ b/crates/eps/src/legacy_ai/writer.rs
@@ -9,7 +9,7 @@ use super::{
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
};
-use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED};
+use super::{CONIC, CONIC_WEDGES, DEEP_DISTORTED, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED};
#[cfg(test)]
thread_local! {
@@ -322,14 +322,23 @@ impl<'a> Writer<'a> {
self.lock(locked);
self.text(t);
}
- NodeKind::Image(im) => {
+ // A distorted image too deep for its pieces is written at the placement nearest its
+ // corners.
+ NodeKind::Image(im) if !n.is_distorted_image() || self.nest >= MAX_NEST => {
self.lock(locked);
let shown = self.doc.shown_image(n, im);
let blob = self.doc.image_blob(&shown);
// A colorize color the renderer draws the image in.
let colorize =
n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize));
- self.image(blob, im.width, im.height, im.xf, colorize);
+ let xf = match vectorcraft_doc::image_quad::nearest_affine(n) {
+ Some(near) => {
+ self.warn(DEEP_DISTORTED);
+ near
+ }
+ None => im.xf,
+ };
+ self.image(blob, im.width, im.height, xf, colorize);
}
NodeKind::SymbolInstance { symbol, xf } => {
self.warn(LIVE);
@@ -348,7 +357,8 @@ impl<'a> Writer<'a> {
| NodeKind::Mesh(_)
| NodeKind::Repeat(_)
| NodeKind::PlacedDocument(_)
- | NodeKind::Intertwine { .. } => {
+ | NodeKind::Intertwine { .. }
+ | NodeKind::Image(_) => {
self.warn(LIVE);
if self.nest < MAX_NEST {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs
index c715d817ec..349bc2a16b 100644
--- a/crates/eps/src/scene.rs
+++ b/crates/eps/src/scene.rs
@@ -585,7 +585,7 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
- NodeKind::Image(im) => {
+ NodeKind::Image(im) if !n.is_distorted_image() => {
let shown = self.doc.shown_image(n, im);
let im = &*shown;
let blob = self.doc.image_blob(im);
@@ -606,13 +606,15 @@ impl<'a> Scene<'a> {
self.nest -= 1;
}
}
- // Live blends, envelopes, meshes and repeats are written as their evaluated art.
+ // Live blends, envelopes, meshes and repeats (and distorted images) are written as
+ // their evaluated art.
NodeKind::Blend { .. }
| NodeKind::Envelope { .. }
| NodeKind::Mesh(_)
| NodeKind::Repeat(_)
| NodeKind::PlacedDocument(_)
- | NodeKind::Intertwine { .. } => {
+ | NodeKind::Intertwine { .. }
+ | NodeKind::Image(_) => {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
for c in g.children().into_iter().flatten() {
self.node(c, false);
diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs
index 60b5832859..0b92c6f8a6 100644
--- a/crates/eps/src/tests.rs
+++ b/crates/eps/src/tests.rs
@@ -1255,6 +1255,50 @@ fn an_envelopes_image_pieces_draw_one_copy_of_its_samples() {
}
}
+/// An image changed by Perspective Distort is written as the pieces of its mesh, placed so that
+/// its pixel rectangle's corners land on its corners: read back, each corner of the quad is a
+/// corner of one of the pieces' images.
+#[test]
+fn a_distorted_image_is_written_with_its_corners_on_its_quad() {
+ let mut d = png_doc();
+ let id = d.layers[0].children().unwrap()[0].id;
+ let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y));
+ d.node_mut(id).unwrap().set_image_corners(q).unwrap();
+ for level in Level::ALL {
+ let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
+ let back = import::import(&out.bytes).unwrap().document;
+ let (mut seen, mut pieces) = ([false; 4], 0);
+ back.walk(|n| {
+ if let NodeKind::Image(im) = &n.kind {
+ pieces += 1;
+ let (w, h) = (f64::from(im.width), f64::from(im.height));
+ for p in [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)] {
+ let at = im.xf * Point::new(p.0, p.1);
+ for (i, c) in q.iter().enumerate() {
+ seen[i] |= at.distance(*c) < 0.01;
+ }
+ }
+ }
+ });
+ assert!(pieces > 2, "{level:?}: {pieces}");
+ assert_eq!(seen, [true; 4], "{level:?}");
+ // The pieces are clipped by the quad: a clipping path with its bounds and its area.
+ let mut quad_clips = 0;
+ back.walk(|n| {
+ if let NodeKind::Group { children, clip: true } = &n.kind
+ && let Some(p) = children.first().and_then(|c| c.path_data())
+ && let Some(b) = p.bounds()
+ {
+ let area: f64 = p.subpaths.iter().map(|s| s.area()).sum::().abs();
+ if [b.x0 - 10.0, b.y0 - 10.0, b.x1 - 90.0, b.y1 - 90.0].iter().all(|v| v.abs() < 0.01) && (area - 4000.0).abs() < 1.0 {
+ quad_clips += 1;
+ }
+ }
+ });
+ assert!(quad_clips >= 1, "{level:?}: no clipping path on the quad");
+ }
+}
+
#[test]
fn each_ink_of_a_colorized_image_placed_twice_is_written_once() {
let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs
index 5641900186..1cb52b4559 100644
--- a/crates/geom/src/shapes.rs
+++ b/crates/geom/src/shapes.rs
@@ -570,6 +570,143 @@ pub fn arc(a: Point, b: Point, slope: f64, closed: bool, _base_along_x: bool) ->
PathData::single(SubPath::new(anchors, closed))
}
+/// A circular arc from `start` to `end`: its circle's `center` and `radius`, and the turn from
+/// `start` to `end` about the center in radians, positive the way the angle `atan2(y, x)` grows
+/// (clockwise on the y-down page). The turn is never 0 and never a whole turn.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct CircularArc {
+ pub start: Point,
+ pub end: Point,
+ pub center: Point,
+ pub radius: f64,
+ pub sweep: f64,
+}
+
+impl CircularArc {
+ /// The arc from `start` to `end` that passes through `through`. `None` when two of the points
+ /// are the same or the three lie on one line ([`circle_through`]).
+ pub fn through(start: Point, end: Point, through: Point) -> Option {
+ let (center, radius) = circle_through(start, end, through)?;
+ let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
+ let a = angle(start);
+ let to_end = (angle(end) - a).rem_euclid(TAU);
+ let to_through = (angle(through) - a).rem_euclid(TAU);
+ // The turn that goes past `through` on its way to `end`.
+ let sweep = if to_through < to_end { to_end } else { to_end - TAU };
+ Self::checked(start, end, center, radius, sweep)
+ }
+
+ /// The arc that leaves `start` heading along `direction` (its tangent there) and ends at
+ /// `end`. `None` when `start` and `end` are the same, `direction` is zero, or `end` lies on the
+ /// line through `start` along `direction` (no circle touches that line at `start` and passes
+ /// through `end`). The same test as [`circle_through`] decides that: twice the area of the
+ /// triangle `start`, `end` and `start + direction` scaled to the chord's length is at most
+ /// 10⁻¹⁰ of the chord's length squared.
+ pub fn leaving(start: Point, direction: Vec2, end: Point) -> Option {
+ let len = direction.hypot();
+ let chord = end - start;
+ let c2 = chord.hypot2();
+ if !(len.is_finite() && len > 0.0 && c2.is_finite() && c2 > 0.0) {
+ return None;
+ }
+ let t = direction / len;
+ // Twice the triangle's area with the tangent as long as the chord.
+ let cross = t.cross(chord);
+ if cross.is_nan() || (cross * c2.sqrt()).abs() <= 1e-10 * c2 {
+ return None;
+ }
+ // The center lies on the normal at `start` on the side `end` is: `start + n * s` with
+ // `|n * s - chord| = |s|`, so `s = |chord|² / (2 n·chord)`.
+ let n = Vec2::new(-t.y, t.x);
+ let s = c2 / (2.0 * n.dot(chord));
+ let center = start + n * s;
+ let radius = s.abs();
+ let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
+ let a = angle(start);
+ let to_end = (angle(end) - a).rem_euclid(TAU);
+ // Leaving along `t`: the turn grows when `t` points the way the angle grows at `start`.
+ let grows = Vec2::new(-(start.y - center.y), start.x - center.x).dot(t) > 0.0;
+ let sweep = if grows { to_end } else { to_end - TAU };
+ Self::checked(start, end, center, radius, sweep)
+ }
+
+ /// The arc that ends at `end` arriving along `direction` and starts at `start`: [`Self::leaving`]
+ /// from `end` back along `-direction`, turned round.
+ pub fn arriving(start: Point, end: Point, direction: Vec2) -> Option {
+ let back = Self::leaving(end, -direction, start)?;
+ Some(Self { start, end, center: back.center, radius: back.radius, sweep: -back.sweep })
+ }
+
+ fn checked(start: Point, end: Point, center: Point, radius: f64, sweep: f64) -> Option {
+ let ok = center.is_finite() && radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() < TAU;
+ ok.then_some(Self { start, end, center, radius, sweep })
+ }
+
+ /// The point at `t` (0 at `start`, 1 at `end`) along the arc.
+ pub fn at(&self, t: f64) -> Point {
+ let a = (self.start.y - self.center.y).atan2(self.start.x - self.center.x) + self.sweep * t;
+ Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin())
+ }
+
+ /// The open path of the arc: an anchor at `start`, at `end`, and between them as many smooth
+ /// anchors, evenly spaced, as keep each cubic piece to a quarter turn at most. The ends are the
+ /// given points exactly.
+ pub fn to_path(&self) -> PathData {
+ let quarter = std::f64::consts::FRAC_PI_2;
+ // A quarter turn and a hair more is still one piece.
+ let pieces = ((self.sweep.abs() / quarter) - 1e-9).ceil().clamp(1.0, 4.0) as u32;
+ let step = self.sweep / f64::from(pieces);
+ // The handle length of a cubic that follows a circle through the turn `step`, per unit
+ // of radius; negative when the arc runs the other way.
+ let k = 4.0 / 3.0 * (step / 4.0).tan();
+ let a0 = (self.start.y - self.center.y).atan2(self.start.x - self.center.x);
+ let mut anchors = Vec::with_capacity(pieces as usize + 1);
+ for i in 0..=pieces {
+ let a = a0 + step * f64::from(i);
+ let p = if i == 0 {
+ self.start
+ } else if i == pieces {
+ self.end
+ } else {
+ Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin())
+ };
+ // The handle along the tangent the way the arc runs.
+ let d = Vec2::new(-a.sin(), a.cos()) * (self.radius * k);
+ let h_in = if i == 0 { p } else { p - d };
+ let h_out = if i == pieces { p } else { p + d };
+ let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth };
+ anchors.push(Anchor { p, h_in, h_out, kind });
+ }
+ PathData::single(SubPath::new(anchors, false))
+ }
+
+ /// [`Self::to_path`] with a smooth anchor at `via`, a point on the arc such as the one
+ /// [`Self::through`] passes through, so the path passes through it exactly: the arc to `via`
+ /// and the arc on from it, each cut into quarter turns at most. A `via` at an end, or off the
+ /// stretch between the ends, gives [`Self::to_path`].
+ pub fn to_path_via(&self, via: Point) -> PathData {
+ let angle = |p: Point| (p.y - self.center.y).atan2(p.x - self.center.x);
+ let turn = (angle(via) - angle(self.start)).rem_euclid(TAU);
+ // The turn from `start` to `via` the way the arc runs.
+ let to_via = if self.sweep > 0.0 { turn } else { turn - TAU };
+ let share = to_via / self.sweep;
+ if !(share > 0.0 && share < 1.0) || via == self.start || via == self.end {
+ return self.to_path();
+ }
+ let first = Self { end: via, sweep: to_via, ..*self }.to_path();
+ let second = Self { start: via, sweep: self.sweep - to_via, ..*self }.to_path();
+ let (Some(a), Some(b)) = (first.subpaths.into_iter().next(), second.subpaths.into_iter().next()) else { return self.to_path() };
+ let mut anchors: Vec = a.anchors.iter().copied().collect();
+ let mut rest = b.anchors.iter().copied();
+ if let (Some(joint), Some(next)) = (anchors.last_mut(), rest.next()) {
+ joint.h_out = next.h_out;
+ joint.kind = AnchorKind::Smooth;
+ }
+ anchors.extend(rest);
+ PathData::single(SubPath::new(anchors, false))
+ }
+}
+
/// Logarithmic spiral with decay per full wind (`segments` quarter turns).
pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clockwise: bool) -> PathData {
let decay = (decay_percent / 100.0).clamp(0.05, 0.9999);
@@ -846,6 +983,144 @@ mod tests {
assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}");
}
+ /// Every point of `path`'s cubics lies on the arc's circle (to 3·10⁻⁴ of the radius, the
+ /// quarter-turn cubic's error), and the path runs from the arc's start to its end.
+ fn assert_on_circle(arc: &CircularArc) {
+ use kurbo::ParamCurve;
+ let path = arc.to_path();
+ let sp = &path.subpaths[0];
+ assert!(!sp.closed);
+ assert_eq!(sp.anchors.first().map(|a| a.p), Some(arc.start));
+ assert_eq!(sp.anchors.last().map(|a| a.p), Some(arc.end));
+ for seg in path.to_bezpath().segments() {
+ for i in 0..=8 {
+ let p = seg.eval(f64::from(i) / 8.0);
+ assert!((p.distance(arc.center) - arc.radius).abs() <= 3e-4 * arc.radius, "{p:?} off the circle");
+ }
+ }
+ }
+
+ /// The arc through a third point: from (0, 0) to (8, 0) through (4, -2) (above the chord on the
+ /// page) bulges up; through (4, 2) it bulges down; each has the circle through the three points
+ /// and goes past the third point. Through (4, 10) it is the larger part of its circle.
+ #[test]
+ fn the_arc_through_a_point_passes_through_it() {
+ let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0));
+ for (c, major) in
+ [(Point::new(4.0, -2.0), false), (Point::new(4.0, 2.0), false), (Point::new(4.0, 10.0), true), (Point::new(-1.0, -3.0), true)]
+ {
+ let arc = CircularArc::through(a, b, c).unwrap();
+ let (center, radius) = circle_through(a, b, c).unwrap();
+ assert!(arc.center.distance(center) < 1e-12 && (arc.radius - radius).abs() < 1e-12);
+ assert_eq!(arc.sweep.abs() > PI, major, "{c:?}: {}", arc.sweep);
+ // The third point is on the arc: some point along it is the third point.
+ let nearest = (0..=10_000).map(|i| arc.at(f64::from(i) / 10_000.0).distance(c)).fold(f64::INFINITY, f64::min);
+ assert!(nearest < 0.01, "{c:?}: {nearest}");
+ assert!(arc.at(0.0).distance(a) < 1e-12 && arc.at(1.0).distance(b) < 1e-9);
+ assert_on_circle(&arc);
+ }
+ // A half circle: two pieces, its middle anchor at the third point.
+ let arc = CircularArc::through(a, b, Point::new(4.0, -4.0)).unwrap();
+ let path = arc.to_path();
+ assert_eq!(path.subpaths[0].anchors.len(), 3);
+ assert!(path.subpaths[0].anchors[1].p.distance(Point::new(4.0, -4.0)) < 1e-12);
+ assert_eq!(path.subpaths[0].anchors[1].kind, AnchorKind::Smooth);
+ // Almost a whole circle: four pieces.
+ let arc = CircularArc::through(a, Point::new(0.0, 0.01), Point::new(8.0, 0.0)).unwrap();
+ assert_eq!(arc.to_path().subpaths[0].anchors.len(), 5);
+ assert_on_circle(&arc);
+ }
+
+ /// With an anchor at the third point, the path passes through it exactly, whichever way the
+ /// arc runs, even where one cubic would miss it (a quarter turn of radius 1000 misses a point
+ /// 20° along by about 0.27). Each part keeps to a quarter turn, the anchor there is smooth, and
+ /// a point at an end leaves the path as `to_path` makes it.
+ #[test]
+ fn the_path_via_the_third_point_passes_through_it_exactly() {
+ let center = Point::new(0.0, 0.0);
+ let on = |deg: f64| Point::new(1000.0 * deg.to_radians().cos(), 1000.0 * deg.to_radians().sin());
+ for (a, b, c) in [(0.0, 90.0, 20.0), (90.0, 0.0, 20.0), (0.0, 300.0, 170.0), (300.0, 0.0, 10.0)] {
+ let arc = CircularArc::through(on(a), on(b), on(c)).unwrap();
+ assert!(arc.center.distance(center) < 1e-6);
+ let path = arc.to_path_via(on(c));
+ let sp = &path.subpaths[0];
+ let joint = sp.anchors.iter().find(|x| x.p == on(c)).expect("an anchor at the third point");
+ assert_eq!(joint.kind, AnchorKind::Smooth);
+ assert_eq!((sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p)), (Some(arc.start), Some(arc.end)));
+ // No piece turns more than a quarter turn.
+ let points: Vec = sp.anchors.iter().map(|x| x.p).collect();
+ for w in points.windows(2) {
+ let (u, v) = (w[0] - arc.center, w[1] - arc.center);
+ assert!(u.cross(v).atan2(u.dot(v)).abs() <= std::f64::consts::FRAC_PI_2 + 1e-9, "{a} {b} {c}");
+ }
+ use kurbo::ParamCurve;
+ for seg in path.to_bezpath().segments() {
+ for i in 0..=8 {
+ let p = seg.eval(f64::from(i) / 8.0);
+ assert!((p.distance(arc.center) - arc.radius).abs() <= 0.3, "{p:?} off the circle");
+ }
+ }
+ }
+ // A third point a hair from an end is still an anchor.
+ let near = Point::new(1000.0, 0.0000005);
+ let arc = CircularArc::through(on(0.0), on(90.0), near).unwrap();
+ assert!(arc.to_path_via(near).subpaths[0].anchors.iter().any(|x| x.p == near));
+ let arc = CircularArc::through(on(0.0), on(90.0), on(20.0)).unwrap();
+ assert_eq!(arc.to_path_via(on(0.0)), arc.to_path());
+ assert_eq!(arc.to_path_via(on(180.0)), arc.to_path());
+ }
+
+ /// The arc that leaves its start along a direction: from (0, 0) heading up the page (-y) to
+ /// (8, 0) is the upper half circle about (4, 0); heading down, the lower one. Its tangent at the
+ /// start is the direction, and arriving at the end mirrors it.
+ #[test]
+ fn the_arc_leaving_along_a_direction_has_that_tangent() {
+ let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0));
+ let up = CircularArc::leaving(a, Vec2::new(0.0, -3.0), b).unwrap();
+ assert!(up.center.distance(Point::new(4.0, 0.0)) < 1e-12 && (up.radius - 4.0).abs() < 1e-12);
+ assert!(up.at(0.5).distance(Point::new(4.0, -4.0)) < 1e-9, "{:?}", up.at(0.5));
+ let down = CircularArc::leaving(a, Vec2::new(0.0, 3.0), b).unwrap();
+ assert!(down.at(0.5).distance(Point::new(4.0, 4.0)) < 1e-9, "{:?}", down.at(0.5));
+ // Leaving at 45° up and right: a quarter circle, tangent along the direction.
+ for d in [Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, -0.2), Vec2::new(-1.0, 3.0)] {
+ let arc = CircularArc::leaving(a, d, b).unwrap();
+ let first = &arc.to_path().subpaths[0].anchors[0];
+ let tangent = first.h_out - first.p;
+ assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}");
+ assert_on_circle(&arc);
+ // Arriving along a direction at the end: the tangent into the end is the direction.
+ let arc = CircularArc::arriving(a, b, d).unwrap();
+ let last = arc.to_path().subpaths[0].anchors.last().copied().unwrap();
+ let tangent = last.p - last.h_in;
+ assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}");
+ assert_eq!((arc.start, arc.end), (a, b));
+ assert_on_circle(&arc);
+ }
+ }
+
+ /// No arc for points that are the same, a third point on the chord's line, a zero or not
+ /// finite direction, or a direction along the chord's line.
+ #[test]
+ fn degenerate_points_give_no_arc() {
+ let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0));
+ assert_eq!(CircularArc::through(a, a, b), None);
+ assert_eq!(CircularArc::through(a, b, b), None);
+ assert_eq!(CircularArc::through(a, b, a.midpoint(b)), None);
+ assert_eq!(CircularArc::through(a, b, a + (b - a) * 3.0), None);
+ assert_eq!(CircularArc::through(a, b, Point::new(f64::INFINITY, 0.0)), None);
+ assert_eq!(CircularArc::leaving(a, Vec2::new(1.0, 0.0), a), None);
+ assert_eq!(CircularArc::leaving(a, Vec2::ZERO, b), None);
+ assert_eq!(CircularArc::leaving(a, Vec2::new(f64::NAN, 1.0), b), None);
+ assert_eq!(CircularArc::leaving(a, b - a, b), None);
+ assert_eq!(CircularArc::leaving(a, a - b, b), None);
+ assert_eq!(CircularArc::arriving(a, b, b - a), None);
+ // Off the line by 10⁻⁴ over a chord of 2000 still makes an arc.
+ let (p, q) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0));
+ assert!(CircularArc::leaving(p, Vec2::new(2000.0, 1e-4), q).is_some());
+ // Off the line by 10⁻¹² of the chord is in line: no arc, rather than a circle 10¹² chords wide.
+ assert_eq!(CircularArc::leaving(p, Vec2::new(1.0, 1e-12), q), None);
+ }
+
/// Two points that are the same, or three on one line, give no circle.
#[test]
fn coincident_or_collinear_points_give_no_circle() {
diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs
index ffa10d9a9c..290623b48b 100644
--- a/crates/mcp/src/ui_catalog.rs
+++ b/crates/mcp/src/ui_catalog.rs
@@ -687,6 +687,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state",
),
("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"),
+ (
+ "window.taskBar.actions",
+ "Bar Actions",
+ "",
+ "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
+ ),
+ (
+ "window.taskBar.resetActions",
+ "Reset Bar Actions",
+ "",
+ "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again",
+ ),
(
"window.dock",
"Panels",
@@ -837,7 +849,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"retype.find",
"Find Matching Fonts",
"",
- "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does, or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more that is not true or false, is an error and leaves the list as it was; returns what retype.list returns",
+ "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns",
),
(
"retype.list",
@@ -1162,7 +1174,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.proofSetupDialog",
"Customize…",
"",
- "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back)",
+ "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; on the desktop only, Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder (Load… once a save has made it), whose setups View › Proof Setup lists below Customize…)",
),
(
"ui.indexedColorDialog",
@@ -1561,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
- "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}",
+ "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}",
),
(
"ui.savePdfDialog",
diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs
index 125126790c..1cfb3038cd 100644
--- a/crates/metafile/src/import/picture.rs
+++ b/crates/metafile/src/import/picture.rs
@@ -16,7 +16,11 @@
//! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between.
//! It is also carried on to the end of the last character's advance. Type on more than one line
//! is placed a line at a time: each line is aligned by its own advances and split as a single
-//! line is.
+//! line is. A character cell runs from the font's OS/2 usWinAscent above the baseline to its
+//! usWinDescent below it, and top or bottom aligned text has the top or the bottom of its cells
+//! at the reference point. Text drawn in the opaque background mode (the mode a playback starts
+//! in) has one rectangle of the background color behind the character cells of each line, as
+//! far as its advances reach.
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
//! the whole picture clips nothing and is left out.
//!
@@ -541,22 +545,38 @@ impl Mapper {
// one for every character: a NUL's advance goes to the character before it, or moves the
// start when the string begins with one.
let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite());
- let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64);
+ let (mut s, mut dx) = (String::new(), Vec::new());
+ // How far before and after its start each character's advances (its own and the NULs'
+ // after it) reach (text units): an advance may be negative. And the advance of the NULs
+ // that move the start, with how far they reach.
+ let mut reach = Vec::new();
+ let mut lead = Lead::default();
for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) {
if c != '\0' {
s.push(c);
dx.push(d);
- } else if let Some(last) = dx.last_mut() {
+ reach.push((d.min(0.0), d.max(0.0)));
+ } else if let (Some(last), Some(r)) = (dx.last_mut(), reach.last_mut()) {
*last += d;
+ *r = (r.0.min(*last), r.1.max(*last));
} else {
- lead += d;
+ lead.by += d;
+ lead.reach = (lead.reach.0.min(lead.by), lead.reach.1.max(lead.by));
}
}
if !advances {
dx.clear();
- lead = 0.0;
+ reach.clear();
+ lead = Lead::default();
}
- if s.trim().is_empty() || t.color[3] == 0 {
+ // The leading NULs, of the text or of a string of NULs alone.
+ let first = lead;
+ // Type that draws nothing still fills its character cells on an opaque background.
+ let background = t.background.filter(|c| c[3] > 0);
+ let shows = !s.trim().is_empty() && t.color[3] > 0;
+ // A string of NULs only fills the cells across its advances.
+ let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some();
+ if (s.is_empty() && !nuls) || !(shows || background.is_some()) {
return;
}
// Text space → document without the move: its vertical scale gives the type size, and what
@@ -613,11 +633,26 @@ impl Mapper {
if !dx.is_empty() {
style.kerning = Some(0.0);
}
- // Where the baseline is below the reference point.
+ // The character cell above and below the baseline (points): the face's OS/2 usWinAscent
+ // and usWinDescent at the type size (its own ascent and descent when it has no OS/2
+ // table), as tall as a positive height asks.
+ let cell = face
+ .as_ref()
+ .map(|face| {
+ let (a, d) = face.win_ascent_descent().unwrap_or_else(|| face.vertical_metrics());
+ (a / face.units_per_em() * size, d / face.units_per_em() * size)
+ })
+ .filter(|(a, d)| a.is_finite() && d.is_finite() && *a >= 0.0 && *d >= 0.0 && a + d > 0.0)
+ .unwrap_or_else(|| {
+ let c = if h > 0.0 { size / 0.85 } else { size };
+ (0.8 * c, 0.2 * c)
+ });
+ // Where the baseline is below the reference point: the top or the bottom of the cell is at
+ // the reference point.
let drop = match t.v_align {
VAlign::Baseline => 0.0,
- VAlign::Bottom => -0.2 * size,
- VAlign::Top => 0.8 * size,
+ VAlign::Bottom => -cell.1,
+ VAlign::Top => cell.0,
};
let origin = self.xf * Point::new(t.transform[4], t.transform[5]);
let base = Affine::translate(origin.to_vec2()) * shape;
@@ -633,19 +668,65 @@ impl Mapper {
};
let whole = point(&s);
let opacity = f32::from(t.color[3]) / 255.0;
+ let line = Line {
+ base,
+ drop,
+ align: &t.h_align,
+ decorated: f.underline || f.strike,
+ shows,
+ color: t.color,
+ opacity,
+ background,
+ cell,
+ point: &point,
+ };
+ // The backgrounds of every line and piece, and the type added after them so that none of
+ // them covers it.
+ let mut out = TextOut::default();
if dx.is_empty() {
let mut text = whole;
+ let laid = vectorcraft_text::layout(db, &text);
text.xf = base * Affine::translate((0.0, drop));
- text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds);
- let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
- n.opacity = opacity;
- self.push(chain, n);
- return;
+ text.cached_bounds = Some(laid.bounds);
+ if background.is_some() {
+ // How far one line's glyphs reach each way, and the sum of their advances, its
+ // trailing blanks included.
+ let along = laid.glyphs.iter().fold((f64::INFINITY, f64::NEG_INFINITY, 0.0), |(from, to, width), g| {
+ let (a, b) = (g.origin.x, g.origin.x + g.advance);
+ (from.min(a.min(b)), to.max(a.max(b)), width + g.advance)
+ });
+ let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite() && along.2.is_finite();
+ // The cells of one line run as far as its glyphs' advances reach, or for blanks
+ // alone, which draw no type, where the alignment puts a line that long.
+ // Those of more than one line run across each line's glyphs. NULs alone span
+ // their advances, where the alignment puts them.
+ let cells = if nuls {
+ let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k;
+ cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell)
+ } else if one {
+ let (x0, x1) = if shows {
+ (along.0, along.1)
+ } else {
+ let x0 = aligned(0.0, along.2, &t.h_align);
+ (x0, x0 + along.2)
+ };
+ cell_rect(x0, x1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell)
+ } else {
+ cells(&laid, &s, cell, &t.h_align, shows && line.decorated)
+ };
+ out.backs.extend(self.background(&line, cells, text.xf));
+ }
+ if shows {
+ let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
+ n.opacity = opacity;
+ out.texts.push(n);
+ }
+ return self.add_text(&chain, out);
}
// Text units grow by `k` along the baseline in the text object's own space.
let dx: Vec = dx.iter().map(|d| d * k).collect();
+ let reach: Vec<(f64, f64)> = reach.iter().map(|(lo, hi)| (lo * k, hi * k)).collect();
let chars: Vec = s.chars().collect();
- let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain };
// Type on more than one line is placed a line at a time, each line aligned by its own
// advances (layout leaves the tracking after a line's last character out of the width it
// aligns, and each line ends with its own) and its underline carried on to its own end.
@@ -655,25 +736,68 @@ impl Mapper {
// a search.
let starts: Vec = s.char_indices().map(|(at, _)| at).collect();
let count = |to: usize| starts.partition_point(|at| *at < to);
- let first = laid.lines.first().map_or(0.0, |l| l.baseline);
+ let top = laid.lines.first().map_or(0.0, |l| l.baseline);
for (n, l) in laid.lines.iter().enumerate() {
let (from, to) = (count(l.start), count(l.end));
- let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue };
+ let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue };
// A leading NUL's advance comes before the first line only.
- let lead = if n == 0 { lead * k } else { 0.0 };
- let down = l.baseline - first;
- self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 });
+ let lead = if n == 0 { first.scaled(k) } else { Lead::default() };
+ let down = l.baseline - top;
+ self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out);
}
} else {
- self.line(&line, &chars, &dx, lead * k, 0.0);
+ self.line(&line, &chars, Advances { dx: &dx, reach: &reach, lead: first.scaled(k) }, 0.0, &mut out);
+ }
+ self.add_text(&chain, out);
+ }
+
+ /// Adds a text record's backgrounds and then its type, leaving out backgrounds when there is
+ /// no room for both.
+ fn add_text(&mut self, chain: &[Arc], out: TextOut) {
+ let TextOut { mut backs, texts } = out;
+ let keep = MAX_NODES.saturating_sub(self.out.len()).saturating_sub(texts.len());
+ if backs.len() > keep {
+ backs.truncate(keep);
+ self.warn(TOO_MANY);
+ }
+ for n in backs.into_iter().chain(texts) {
+ self.push(chain.to_vec(), n);
}
}
- /// One line of text with advances `dx` (points along the baseline) for its characters `chars`,
- /// `down` below the first line's baseline: in pieces, each a text object of its own, a new
- /// piece after each cluster that tracking can't space by its advance.
- fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) {
- if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) {
+ /// Character cells `cells`, placed by `xf`, filled with the line's background when it has one.
+ fn background(&self, line: &Line, mut cells: BezPath, xf: Affine) -> Option {
+ let bg = line.background?;
+ if cells.elements().is_empty() {
+ return None;
+ }
+ cells.apply_affine(xf);
+ self.path_node(cells, Some(bg), None, false)
+ }
+
+ /// One line of text with advances `adv` (points along the baseline) for its characters
+ /// `chars`, `down` below the first line's baseline: in pieces, each a text object of its own,
+ /// a new piece after each cluster that tracking can't space by its advance.
+ fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) {
+ let Advances { dx, reach, lead } = adv;
+ // The line's cells, one rectangle behind every piece, run as far each way as its
+ // advances reach (an advance may be negative), from where the leading NULs' advances
+ // start, which the alignment puts where it puts a line as long as its advances. A line
+ // of leading NULs alone fills the cells across their advances.
+ let start = aligned(lead.by, dx.iter().sum(), line.align);
+ if line.background.is_some() {
+ let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64);
+ for (d, r) in dx.iter().zip(reach) {
+ (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1));
+ pos += d;
+ }
+ let xf = line.base * Affine::translate((0.0, line.drop + down));
+ out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf));
+ }
+ let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace());
+ // A piece's type draws when it shows: blanks only when underlined or struck through.
+ let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated);
+ if chars.is_empty() || !draws(chars) {
return;
}
let db = vectorcraft_text::FontDb::global();
@@ -684,13 +808,13 @@ impl Mapper {
// Along the baseline (the text object's own space), where the next piece starts from the
// reference point: the line as long as its advances (a leading NUL's included), where the
// alignment puts it.
- let mut at = aligned(lead, dx.iter().sum(), line.align);
+ let mut at = start;
let last = pieces.len().saturating_sub(1);
for (i, (from, to)) in pieces.into_iter().enumerate() {
- let piece: String = chars.get(from..to).unwrap_or_default().iter().collect();
+ let cs = chars.get(from..to).unwrap_or_default();
+ let piece: String = cs.iter().collect();
let dx = dx.get(from..to).unwrap_or_default();
- // Blanks of their own draw nothing unless they are underlined or struck through.
- if piece.trim().is_empty() && !line.decorated {
+ if !draws(cs) {
at += dx.iter().sum::();
continue;
}
@@ -715,12 +839,12 @@ impl Mapper {
let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() };
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone())));
n.opacity = line.opacity;
- self.push(line.chain.to_vec(), n);
+ out.texts.push(n);
if !gap.elements().is_empty() {
let mut gap = gap;
gap.apply_affine(text.xf);
if let Some(n) = self.path_node(gap, Some(line.color), None, false) {
- self.push(line.chain.to_vec(), n);
+ out.texts.push(n);
}
}
}
@@ -785,16 +909,95 @@ fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
/// What every piece of a text record's lines shares: the text space (`base`, with the baseline
/// `drop` below the reference point), the alignment, whether the type is underlined or struck
-/// through, its color and opacity, a point type object of a string in its style, and its clips.
+/// through, whether the type shows, its color and opacity, its background and the character cell
+/// above and below the baseline (points), and a point type object of a string in its style.
struct Line<'a> {
base: Affine,
drop: f64,
align: &'a HAlign,
decorated: bool,
+ shows: bool,
color: [u8; 4],
opacity: f32,
+ background: Option<[u8; 4]>,
+ cell: (f64, f64),
point: &'a dyn Fn(&str) -> TextObject,
- chain: &'a [Arc],
+}
+
+/// What a text record draws: the backgrounds behind its character cells, and its type (with the
+/// bars that carry an underline or strikethrough on), added after them.
+#[derive(Default)]
+struct TextOut {
+ backs: Vec