Files
vectorcraft/crates/engine/src/tests/pathops.rs
T
dotCooCoo aa5f1bdca1 Clean Up: Hairline Slivers leaves art at 0% opacity alone
A sliver at 0% opacity, or inside a group or layer at 0% opacity, paints
nothing, so Clean Up and Select > Object > Hairline Slivers now skip it.
The params text and docs/mcp.md say so, and docs/mcp.md also names what a
group or compound path used as a clipping path holds among the objects
both commands leave.
2026-11-28 20:07:16 -08:00

2559 lines
132 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Tests for Pathfinder, Object → Path and Type commands.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect()
}
fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn path_of(s: &Session, id: NodeId) -> (PathData, FillRule) {
let n = node(s, id);
match &n.kind {
NodeKind::Path { path, rule, .. } => (path.clone(), *rule),
NodeKind::Compound { children, rule } => {
(PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule)
}
_ => panic!("not a path"),
}
}
fn area_of(s: &Session, id: NodeId) -> f64 {
let (p, r) = path_of(s, id);
vectorcraft_pathops::area(&p, r)
}
fn bounds(s: &Session, id: NodeId) -> Rect {
node(s, id).geometric_bounds().unwrap()
}
fn close(a: Rect, b: Rect, tol: f64) -> bool {
(a.x0 - b.x0).abs() < tol && (a.y0 - b.y0).abs() < tol && (a.x1 - b.x1).abs() < tol && (a.y1 - b.y1).abs() < tol
}
fn set_fill(s: &mut Session, id: NodeId, c: Color) {
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance.set_fill(Paint::solid(c));
Ok(())
})
.unwrap();
}
fn two_rects(s: &mut Session) -> (NodeId, NodeId) {
let a = rect(s, 0.0, 0.0, 100.0, 100.0);
let b = rect(s, 50.0, 50.0, 100.0, 100.0);
set_fill(s, a, Color::rgb(1.0, 0.0, 0.0));
set_fill(s, b, Color::rgb(0.0, 0.0, 1.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
(a, b)
}
#[test]
fn unite_two_rects() {
let mut s = session();
let (a, b) = two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.unite", &json!({})).unwrap());
assert_eq!(r.len(), 1);
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
assert!(matches!(node(&s, r[0]).kind, NodeKind::Path { .. }));
assert!(close(bounds(&s, r[0]), Rect::new(0.0, 0.0, 150.0, 150.0), 1e-3));
assert!((area_of(&s, r[0]) - (10000.0 + 10000.0 - 2500.0)).abs() < 1.0);
// Top object's style.
assert_eq!(node(&s, r[0]).appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
assert_eq!(s.doc().unwrap().selection.objects, r);
}
#[test]
fn minus_front_keeps_back_style() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap());
assert!((area_of(&s, r[0]) - 7500.0).abs() < 1.0);
assert!(close(bounds(&s, r[0]), Rect::new(0.0, 0.0, 100.0, 100.0), 1e-3));
assert_eq!(node(&s, r[0]).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
}
#[test]
fn minus_back_keeps_front_style() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.minusBack", &json!({})).unwrap());
assert!((area_of(&s, r[0]) - 7500.0).abs() < 1.0);
assert!(close(bounds(&s, r[0]), Rect::new(50.0, 50.0, 150.0, 150.0), 1e-3));
assert_eq!(node(&s, r[0]).appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
}
#[test]
fn intersect_rects() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.intersect", &json!({})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(50.0, 50.0, 100.0, 100.0), 1e-3));
assert!((area_of(&s, r[0]) - 2500.0).abs() < 1.0);
}
#[test]
fn intersect_disjoint_is_error_and_no_change() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let undo_len = s.doc().unwrap().history.undo.len();
assert!(s.execute("object.pathfinder.intersect", &json!({})).is_err());
assert!(s.doc().unwrap().doc.node(a).is_some());
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
#[test]
fn exclude_makes_compound() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.exclude", &json!({})).unwrap());
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
}
#[test]
fn divide_produces_group_of_faces() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap());
let g = node(&s, r[0]);
assert!(matches!(g.kind, NodeKind::Group { .. }));
let ch = g.children().unwrap();
assert_eq!(ch.len(), 3);
let total: f64 = ch.iter().map(|c| area_of(&s, c.id)).sum();
assert!((total - 17500.0).abs() < 1.0);
// The overlap face takes the top (blue) style.
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
assert_eq!(ch.iter().filter(|c| c.appearance.fill_paint() == blue).count(), 2);
}
#[test]
fn trim_and_merge() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.trim", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(g.children().unwrap().len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
// Same colour → merge joins them.
let sel = s.doc().unwrap().selection.objects.clone();
set_fill(&mut s, sel[0], Color::rgb(0.0, 0.0, 1.0));
s.execute("select.set", &json!({"ids": [sel[0].0, sel[1].0]})).unwrap();
let r = ids(&s.execute("object.pathfinder.merge", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(g.children().unwrap().len(), 1);
}
#[test]
fn crop_and_outline() {
let mut s = session();
two_rects(&mut s);
let r = ids(&s.execute("object.pathfinder.crop", &json!({})).unwrap());
let g = node(&s, r[0]);
let ch = g.children().unwrap();
assert_eq!(ch.len(), 1);
assert!((area_of(&s, ch[0].id) - 2500.0).abs() < 1.0);
s.execute("edit.undo", &json!({})).unwrap();
let r = ids(&s.execute("object.pathfinder.outline", &json!({})).unwrap());
let g = node(&s, r[0]);
assert!(g.children().unwrap().len() >= 4);
assert!(g.children().unwrap().iter().all(|c| c.appearance.stroke_width() > 0.0));
}
#[test]
fn pathfinder_undo_restores() {
let mut s = session();
let (a, b) = two_rects(&mut s);
let before = s.doc().unwrap().doc.clone();
s.execute("object.pathfinder.unite", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *before);
assert!(s.doc().unwrap().selection.contains(a) && s.doc().unwrap().selection.contains(b));
}
/// #1450: a group selected alone gives the shape modes its members to work on.
#[test]
fn a_group_selected_alone_is_combined_member_by_member() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 10.0, 0.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection.len(), 1);
let id = s.execute("object.pathfinder.minusFront", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let bounds = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
assert_eq!((bounds.x0, bounds.x1), (0.0, 10.0), "the back member less the front one");
}
/// #2178: Unite on separated shapes is one compound path; Release releases each subpath (Illustrator parity).
#[test]
fn pathfinder_unite_non_overlapping_shapes_become_compound_path_releasable() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
let layer = s.doc().unwrap().doc.parent_of(a).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.pathfinder.unite", &json!({})).unwrap();
let result = s.doc().unwrap().selection.objects[0];
let united = node(&s, result);
assert!(matches!(united.kind, NodeKind::Compound { .. }));
assert_eq!(united.children().unwrap().len(), 2);
s.execute("object.compoundPath.release", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(result).is_none());
assert_eq!(s.doc().unwrap().selection.len(), 2);
for id in &s.doc().unwrap().selection.objects {
assert_eq!(d.parent_of(*id), Some(layer));
}
}
/// #2178: Unite keeps disjoint geometry in one compound path (not a group of separate path objects).
#[test]
fn pathfinder_unite_disjoint_islands_stay_one_compound_path() {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let hole = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [outer.0, hole.0]})).unwrap();
let ring = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let separate = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [ring.0, separate.0]})).unwrap();
s.execute("object.pathfinder.unite", &json!({})).unwrap();
let result = s.doc().unwrap().selection.objects[0];
assert!(matches!(node(&s, result).kind, NodeKind::Compound { .. }));
assert_eq!(path_of(&s, result).0.subpaths.len(), 3);
}
#[test]
fn unite_with_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let c = rect(&mut s, 5.0, 5.0, 20.0, 10.0);
s.execute("select.set", &json!({"ids": [g, c.0]})).unwrap();
let r = ids(&s.execute("object.pathfinder.unite", &json!({})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(0.0, 0.0, 30.0, 15.0), 1e-3));
assert!((area_of(&s, r[0]) - (100.0 + 100.0 + 200.0 - 25.0 - 25.0)).abs() < 1.0);
}
fn name_sources(s: &mut Session, a: NodeId, b: NodeId, names: [Option<&str>; 2]) {
s.edit("Name sources", |d, _| {
for (id, name) in [(a, names[0]), (b, names[1])] {
d.node_mut(id).unwrap().name = name.map(str::to_owned);
}
Ok(())
})
.unwrap();
}
fn named_nodes<'a>(n: &'a vectorcraft_doc::Node, name: &str, out: &mut Vec<&'a vectorcraft_doc::Node>) {
if n.name.as_deref() == Some(name) {
out.push(n);
}
if let Some(children) = n.children() {
for c in children {
named_nodes(c, name, out);
}
}
}
fn check_svg_name(s: &Session, id: NodeId, name: &str) {
let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default());
assert_eq!(svg.matches(&format!("id=\"{name}\"")).count(), 1, "{svg}");
let imported = vectorcraft_svg::import(&svg).unwrap();
let mut matches = vec![];
for layer in &imported.layers {
named_nodes(layer, name, &mut matches);
}
assert_eq!(matches.len(), 1, "{name}: {svg}");
assert!(close(matches[0].geometric_bounds().unwrap(), bounds(s, id), 1e-2));
assert_eq!(matches[0].appearance.fill_paint(), node(s, id).appearance.fill_paint());
}
#[test]
fn pathfinder_shape_names_follow_paint_order_without_changing_output_or_undo() {
for op in ["minusFront", "minusBack", "unite", "intersect", "exclude"] {
let mut s = session();
let (a, b) = two_rects(&mut s);
let untouched = rect(&mut s, 300.0, 300.0, 30.0, 20.0);
name_sources(&mut s, a, b, [Some("base-plate"), Some("blade")]);
s.edit("Source opacity and blend", |d, _| {
d.node_mut(a).unwrap().opacity = 0.4;
d.node_mut(b).unwrap().opacity = 0.8;
d.node_mut(b).unwrap().blend = vectorcraft_color::BlendMode::Multiply;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let undo_len = s.doc().unwrap().history.undo.len();
let cmd = format!("object.pathfinder.{op}");
let id = ids(&s.execute(&cmd, &json!({})).unwrap())[0];
let expected = if op == "minusBack" { "blade" } else { "base-plate" };
let mut result = node(&s, id);
assert_eq!(result.name.as_deref(), Some(expected), "{op}");
assert_eq!(node(&s, untouched), *before.node(untouched).unwrap());
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len + 1);
check_svg_name(&s, id, expected);
let after = s.doc().unwrap().doc.clone();
let after_selection = s.doc().unwrap().selection.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *before);
assert_eq!(s.doc().unwrap().selection, selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *after);
assert_eq!(s.doc().unwrap().selection, after_selection);
s.execute("edit.undo", &json!({})).unwrap();
name_sources(&mut s, a, b, [None, None]);
let bare_id = ids(&s.execute(&cmd, &json!({})).unwrap())[0];
result.name = None;
assert_eq!(result, node(&s, bare_id), "names must not change geometry or appearance: {op}");
}
}
#[test]
fn pathfinder_shape_names_do_not_borrow_a_cutters_name_for_an_unnamed_source() {
for names in [[None, Some("blade")], [Some("base-plate"), None], [None, None]] {
for op in ["minusFront", "minusBack", "unite", "intersect", "exclude"] {
let mut s = session();
let (a, b) = two_rects(&mut s);
name_sources(&mut s, a, b, names);
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
let expected = match op {
"minusFront" => names[0],
"minusBack" => names[1],
_ => names[0].or(names[1]),
};
let id = ids(&s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap())[0];
assert_eq!(node(&s, id).name.as_deref(), expected, "{op}: {names:?}");
}
}
}
#[test]
fn pathfinder_shape_names_keep_group_and_compound_identity_once() {
for (compound, count, root_name) in
[(false, 1, Some("root-identity")), (false, 2, Some("root-identity")), (true, 2, Some("root-identity")), (false, 2, None)]
{
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 100.0);
let mut children = vec![a.0];
if count == 2 {
children.push(rect(&mut s, 60.0, 0.0, 40.0, 100.0).0);
}
s.execute("select.set", &json!({"ids": children})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Name grouped source", |d, _| {
d.node_mut(a).unwrap().name = Some("leaf-identity".into());
let appearance = d.node(a).unwrap().appearance.clone();
let n = d.node_mut(group).unwrap();
n.name = root_name.map(str::to_owned);
if compound {
n.kind = NodeKind::Compound { children: n.children().unwrap().to_vec(), rule: FillRule::NonZero };
n.appearance = appearance;
}
Ok(())
})
.unwrap();
let cutter = rect(&mut s, 35.0, -10.0, 30.0, 120.0);
name_sources(&mut s, group, cutter, [root_name, Some("blade")]);
s.execute("select.set", &json!({"ids": [cutter.0, group.0]})).unwrap();
let id = ids(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap())[0];
let n = node(&s, id);
let expected = root_name.unwrap_or("leaf-identity");
assert_eq!(n.name.as_deref(), Some(expected));
assert!((area_of(&s, id) - 3500.0 * f64::from(count)).abs() < 1.0);
assert!(n.children().is_none_or(|children| children.iter().all(|c| c.name.is_none())));
check_svg_name(&s, id, expected);
}
}
#[test]
fn pathfinder_fragment_names_do_not_change_style_merging() {
for op in ["divide", "trim", "merge", "crop", "outline"] {
let mut s = session();
let (a, b) = two_rects(&mut s);
set_fill(&mut s, a, Color::rgb(0.0, 0.0, 1.0));
name_sources(&mut s, a, b, [Some("base-plate"), Some("blade")]);
let cmd = format!("object.pathfinder.{op}");
let id = ids(&s.execute(&cmd, &json!({})).unwrap())[0];
let result = node(&s, id);
assert!(result.name.is_none());
assert!(result.children().unwrap().iter().all(|c| c.name.is_none()));
if op == "merge" {
assert_eq!(result.children().unwrap().len(), 1);
}
s.execute("edit.undo", &json!({})).unwrap();
name_sources(&mut s, a, b, [None, None]);
let bare_id = ids(&s.execute(&cmd, &json!({})).unwrap())[0];
assert_eq!(result, node(&s, bare_id), "{op}");
}
}
#[test]
fn offset_rect_grows_bounds() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": 10, "joins": "miter", "miterLimit": 4})).unwrap());
assert_eq!(r.len(), 1);
assert!(s.doc().unwrap().doc.node(a).is_some(), "original is kept");
assert!(close(bounds(&s, r[0]), Rect::new(90.0, 90.0, 160.0, 150.0), 1e-2), "{:?}", bounds(&s, r[0]));
assert_eq!(s.doc().unwrap().selection.objects, r);
// Above the original.
let d = &s.doc().unwrap().doc;
assert!(d.index_path(r[0]).unwrap() > d.index_path(a).unwrap());
// Negative insets; string params are accepted.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "-5 pt", "joins": "round"})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(105.0, 105.0, 145.0, 135.0), 1e-2));
}
/// #3773: an open path whose last anchor sits on its first is offset as the closed shape, not as a
/// ring around its outline.
#[test]
fn offset_open_path_whose_ends_meet_grows_the_shape() {
let mut s = session();
s.execute("path.create", &json!({"d": "M0 0 L40 0 L40 40 L0 40 L0 0"})).unwrap();
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": 2, "joins": "miter"})).unwrap());
assert!((area_of(&s, r[0]) - 44.0 * 44.0).abs() < 1e-3, "{}", area_of(&s, r[0]));
assert_eq!(path_of(&s, r[0]).0.subpaths.len(), 1);
}
/// The ids of the objects in the first layer, back to front.
fn first_layer(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
/// Offset Path of several objects at once: each result goes directly above its object and takes
/// the next ids in the objects' order, a group gives a group of its paths' offsets with their
/// styles, a compound path gives a compound path, an inset that leaves nothing and type give
/// nothing, and one undo gives the objects back.
#[test]
fn offset_path_of_several_objects_keeps_their_order() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let c = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
set_fill(&mut s, b, Color::rgb(1.0, 0.0, 0.0));
set_fill(&mut s, c, Color::rgb(0.0, 0.0, 1.0));
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let tiny = rect(&mut s, 100.0, 0.0, 4.0, 4.0);
let outer = rect(&mut s, 200.0, 0.0, 40.0, 40.0);
let inner = rect(&mut s, 210.0, 10.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
let cp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let t = NodeId(s.execute("text.create", &json!({"x": 300, "y": 10, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
let before = first_layer(&s);
assert_eq!(before, [a, g, tiny, cp, t]);
let first = s.doc().unwrap().doc.peek_next_id();
s.execute("select.set", &json!({"ids": [a.0, g.0, tiny.0, cp.0, t.0]})).unwrap();
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": -3, "joins": "miter"})).unwrap());
// a's offset, then b's and c's and their group, then the compound path and its two subpaths.
assert_eq!(r, [NodeId(first), NodeId(first + 3), NodeId(first + 4)]);
assert_eq!(first_layer(&s), [a, r[0], g, r[1], tiny, cp, r[2], t]);
assert_eq!(s.doc().unwrap().selection.objects, r);
assert!(close(bounds(&s, r[0]), Rect::new(3.0, 3.0, 17.0, 17.0), 1e-2), "{:?}", bounds(&s, r[0]));
let group = node(&s, r[1]);
assert!(matches!(group.kind, NodeKind::Group { .. }), "{:?}", group.kind);
let kids = group.children().unwrap();
assert_eq!(kids.iter().map(|k| k.id).collect::<Vec<_>>(), [NodeId(first + 1), NodeId(first + 2)]);
assert_eq!(kids[0].appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
assert_eq!(kids[1].appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let rings = node(&s, r[2]);
assert!(matches!(rings.kind, NodeKind::Compound { .. }), "{:?}", rings.kind);
assert!(close(bounds(&s, r[2]), Rect::new(203.0, 3.0, 237.0, 37.0), 1e-2), "{:?}", bounds(&s, r[2]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first_layer(&s), before);
}
/// Offset Path works out the offsets of several paths on more than one thread, and gives the
/// results in the paths' order.
#[test]
fn offset_path_works_on_several_threads_in_order() {
let seen = std::sync::Mutex::new(vec![]);
let items: Vec<usize> = (0..8).collect();
let work = |i: &usize| {
if let Ok(mut seen) = seen.lock() {
seen.push(std::thread::current().id());
}
i * 2
};
let (out, used) = crate::cmd::pathops::ordered_map(&items, 4, work, |_| false);
assert_eq!(out, (0..8).map(|i| Some(i * 2)).collect::<Vec<_>>());
assert_eq!(used, 4);
let threads: std::collections::HashSet<_> = seen.into_inner().unwrap().into_iter().collect();
assert_eq!(threads.len(), 4);
// A count just past the threads still uses every thread.
let (out, used) = crate::cmd::pathops::ordered_map(&items[..5], 4, |i| i * 2, |_| false);
assert_eq!(out, (0..5).map(|i| Some(i * 2)).collect::<Vec<_>>());
assert_eq!(used, 4);
// One item, or one thread, is worked on here.
let (out, used) = crate::cmd::pathops::ordered_map(&items[..1], 4, |i| i * 2, |_| false);
assert_eq!((out, used), (vec![Some(0)], 1));
let (out, used) = crate::cmd::pathops::ordered_map(&items, 1, |i| i * 2, |_| false);
assert_eq!(used, 1);
assert_eq!(out.len(), 8);
}
/// Once a result stops the work (an offset that fails), the paths after it are left out, and every
/// path before it has its result, so the first failure in the paths' order is the one reported.
#[test]
fn offset_path_stops_after_the_first_failure() {
let items: Vec<usize> = (0..8).collect();
let (out, _) = crate::cmd::pathops::ordered_map(&items, 1, |i| *i, |r| *r == 2 || *r == 5);
assert_eq!(out, [Some(0), Some(1), Some(2), None, None, None, None, None]);
for threads in [2, 4, 8] {
let (out, _) = crate::cmd::pathops::ordered_map(&items, threads, |i| *i, |r| *r == 2 || *r == 5);
assert_eq!(out[..3], [Some(0), Some(1), Some(2)], "{threads} threads");
let first = out.iter().position(|r| r.is_some_and(|r| r == 2 || r == 5));
assert_eq!(first, Some(2), "{threads} threads");
}
}
/// A straight line, closed as the Shape Modes close open paths, encloses no area, so it does not
/// change the result's shape: Unite, Minus Front, Exclude and Minus Back still give the 100 pt square's area
/// (with a line in a group selected beside it, the group's square too), and the reply carries a
/// warning that names Outline Stroke, as it does with the line in a compound path or in a group
/// selected alone; where the line leaves nothing (Intersect, the backmost object in Minus Front, or
/// the frontmost in Minus Back), the error names it, and where the other objects leave nothing
/// anyway, a flat closed path included, it doesn't. An open evenodd square traced twice is the same. An open path
/// that encloses an area once closed (a bow tie whose lobes cancel in signed area included), closed
/// shapes alone, and Divide, where a line cuts, give no warning (#7849).
#[test]
fn shape_modes_report_lines_that_enclose_no_area() {
use crate::cmd::SHAPE_MODE_OPEN_PATH_NO_AREA;
fn id_of(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn line_of(s: &mut Session) -> NodeId {
id_of(s.execute("shape.line", &json!({"x1": 20, "y1": 50, "x2": 80, "y2": 50})).unwrap())
}
fn vee_of(s: &mut Session) -> NodeId {
let anchors = json!([{"x": 20, "y": 50}, {"x": 50, "y": 150}, {"x": 80, "y": 50}]);
id_of(s.execute("path.create", &json!({ "anchors": anchors })).unwrap())
}
fn bow_tie_of(s: &mut Session) -> NodeId {
let anchors = json!([{"x": 20, "y": 120}, {"x": 80, "y": 180}, {"x": 80, "y": 120}, {"x": 20, "y": 180}]);
id_of(s.execute("path.create", &json!({ "anchors": anchors })).unwrap())
}
fn twice_around_of(s: &mut Session) -> NodeId {
let d = "M20 20 L80 20 L80 80 L20 80 L20 20 L80 20 L80 80 L20 80";
let id = id_of(s.execute("path.create", &json!({ "d": d })).unwrap());
s.execute("path.setFillRule", &json!({"rule": "evenOdd"})).unwrap();
id
}
fn grouped_line_of(s: &mut Session) -> NodeId {
let ids = [line_of(s), rect(s, 200.0, 0.0, 100.0, 100.0)];
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
id_of(s.execute("object.group", &json!({})).unwrap())
}
fn compound_line_of(s: &mut Session) -> NodeId {
let ids = [line_of(s), rect(s, 200.0, 0.0, 100.0, 100.0)];
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
id_of(s.execute("object.compoundPath.make", &json!({})).unwrap())
}
fn square_of(s: &mut Session) -> NodeId {
rect(s, 50.0, 0.0, 100.0, 100.0)
}
type Build = fn(&mut Session) -> NodeId;
// (case, command, the other object, whether it goes behind the 100 pt square, warned, area drawn)
type Case = (&'static str, &'static str, Build, bool, bool, Option<f64>);
let cases: [Case; 12] = [
("a line", "unite", line_of, false, true, Some(10_000.0)),
("a line in front", "minusFront", line_of, false, true, Some(10_000.0)),
("a line", "exclude", line_of, false, true, Some(10_000.0)),
("a line behind", "minusBack", line_of, true, true, Some(10_000.0)),
("an open evenodd square traced twice", "unite", twice_around_of, false, true, Some(10_000.0)),
("a group of a line and a square", "unite", grouped_line_of, false, true, Some(20_000.0)),
("a compound path of a line and a square", "unite", compound_line_of, false, true, Some(20_000.0)),
("an open path that encloses an area", "unite", vee_of, false, false, None),
("an open bow tie, whose signed area is zero", "unite", bow_tie_of, false, false, None),
("a square", "unite", square_of, false, false, Some(15_000.0)),
("a square", "minusFront", square_of, false, false, Some(5_000.0)),
("a line, dividing", "divide", line_of, false, false, None),
];
for (what, op, build, behind, warned, want) in cases {
let mut s = session();
let (back, front) = if behind {
let other = build(&mut s);
(other, rect(&mut s, 0.0, 0.0, 100.0, 100.0))
} else {
let sq = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
(sq, build(&mut s))
};
s.execute("select.set", &json!({"ids": [back.0, front.0]})).unwrap();
let r = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_or_else(|e| panic!("{what}, {op}: {e}"));
let warning = r.get("warning").and_then(Value::as_str);
assert_eq!(warning, warned.then_some(SHAPE_MODE_OPEN_PATH_NO_AREA), "{what}, {op}: {r}");
if let Some(want) = want {
let got = area_of(&s, ids(&r)[0]);
assert!((got - want).abs() < 1.0, "{what}, {op}: area {got}, want {want}");
}
}
// A group of a line and a square selected alone: its members are the shapes, and the line warns.
let mut s = session();
let group = grouped_line_of(&mut s);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
let r = s.execute("object.pathfinder.unite", &json!({})).unwrap();
assert_eq!(r.get("warning").and_then(Value::as_str), Some(SHAPE_MODE_OPEN_PATH_NO_AREA), "{r}");
let got = area_of(&s, ids(&r)[0]);
assert!((got - 10_000.0).abs() < 1.0, "a group alone: area {got}");
// A line that leaves nothing (Intersect, the backmost object in Minus Front, or the frontmost in
// Minus Back) gives an error that names it; two squares that don't meet give the plain one.
// (command, the other object, whether it goes behind the square, whether the error names the line)
let cases: [(&str, Build, bool, bool); 4] = [
("intersect", line_of, false, true),
("minusFront", line_of, true, true),
("minusBack", line_of, false, true),
("intersect", |s| rect(s, 300.0, 0.0, 50.0, 50.0), false, false),
];
for (op, build, behind, named) in cases {
let mut s = session();
let (back, front) = if behind {
let other = build(&mut s);
(other, rect(&mut s, 0.0, 0.0, 100.0, 100.0))
} else {
let sq = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
(sq, build(&mut s))
};
s.execute("select.set", &json!({"ids": [back.0, front.0]})).unwrap();
let e = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_err().to_string();
assert!(e.contains("produced an empty result"), "{op}: {e}");
assert_eq!(e.contains("Outline Stroke"), named, "{op}: {e}");
}
// Two squares that don't meet leave Intersect empty whatever a line beside them does.
let mut s = session();
let objects = [rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0), line_of(&mut s)];
s.execute("select.set", &json!({"ids": objects.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string();
assert!(e.contains("produced an empty result") && !e.contains("Outline Stroke"), "{e}");
// A closed path without area (a flat one) leaves Intersect empty with or without the line, so
// the error is the plain one.
let mut s = session();
let flat = id_of(s.execute("path.create", &json!({"d": "M50 0 L50 100 Z"})).unwrap());
let objects = [rect(&mut s, 0.0, 0.0, 100.0, 100.0), flat, line_of(&mut s)];
s.execute("select.set", &json!({"ids": objects.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string();
assert!(e.contains("produced an empty result") && !e.contains("Outline Stroke"), "a flat closed path: {e}");
}
#[test]
fn outline_stroke_of_line() {
let mut s = session();
let r = s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap();
let l = NodeId(r["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(l).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 10.0).into();
Ok(())
})
.unwrap();
let r = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, r[0]);
assert!(close(n.geometric_bounds().unwrap(), Rect::new(0.0, 45.0, 100.0, 55.0), 1e-2));
assert_eq!(n.appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
assert!(n.appearance.stroke().is_none());
assert!((area_of(&s, r[0]) - 1000.0).abs() < 1.0);
}
#[test]
fn outline_stroke_preserves_a_zero_area_fill_without_retaining_a_live_stroke() {
let mut s = session();
s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 60, "y2": 90})).unwrap();
s.execute("paint.setFill", &json!({"color":"#ffffff"})).unwrap();
let before = s.doc().unwrap().doc.clone();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, result[0]);
let children = n.children().expect("the original fill and the outlined stroke");
assert_eq!(children.len(), 2);
assert!(children.iter().all(|n| n.appearance.stroke().is_none()));
assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)), "an invisible fill is not a live stroke");
assert!(n.appearance.stroke().is_none());
assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::BLACK)));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
s.execute("edit.redo", &json!({})).unwrap();
assert!(node(&s, result[0]).appearance.stroke().is_none());
}
#[test]
fn outline_stroke_with_fill_makes_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.edit("t", |d, _| {
d.node_mut(a).unwrap().appearance.stroke_mut().unwrap().width = 4.0;
Ok(())
})
.unwrap();
let r = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let g = node(&s, r[0]);
let ch = g.children().unwrap();
assert_eq!(ch.len(), 2);
assert_eq!(ch[0].appearance.fill_paint(), Paint::solid(Color::WHITE));
assert_eq!(ch[1].appearance.fill_paint(), Paint::solid(Color::BLACK));
assert!(close(ch[1].geometric_bounds().unwrap(), Rect::new(-2.0, -2.0, 102.0, 102.0), 1e-2));
}
#[test]
fn simplify_dense_polyline() {
let mut s = session();
let anchors: Vec<Value> = (0..=100)
.map(|i| {
let x = i as f64 * 3.0;
json!({"x": x, "y": 100.0 + 40.0 * (x / 50.0).sin()})
})
.collect();
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let before = path_of(&s, id).0.anchor_count();
let out = s.execute("object.path.simplify", &json!({"tolerance": 1.0})).unwrap();
let after = path_of(&s, id).0.anchor_count();
assert_eq!(before, 101);
assert!(after < before / 4, "{after}");
assert_eq!(out["after"].as_u64().unwrap() as usize, after);
assert!(close(bounds(&s, id), Rect::new(0.0, 60.0, 300.0, 140.0), 2.0));
}
/// A sine wave with an anchor every point over `width` pt, `amplitude` pt high and a wavelength of
/// `2π × period` pt, its anchors `jag` pt above and below it in turn, selected: (the session, the
/// path's id).
fn dense_wave(width: u32, amplitude: f64, period: f64, jag: f64) -> (Session, NodeId) {
let mut s = session();
let y = |i: u32| 100.0 + amplitude * (f64::from(i) / period).sin() + if i.is_multiple_of(2) { jag } else { -jag };
let anchors: Vec<Value> = (0..=width).map(|i| json!({"x": f64::from(i), "y": y(i)})).collect();
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
(s, NodeId(r["id"].as_u64().unwrap()))
}
/// The Simplify slider: moving its level from 0 to 100 never lowers the anchor count, level 0
/// leaves fewer anchors than level 100, and level 50 gives the 1 pt result.
#[test]
fn simplify_level_moves_the_anchor_count_monotonically() {
let (mut s, id) = dense_wave(300, 40.0, 25.0, 0.0);
let mut counts = vec![];
for level in (0..=100).step_by(10) {
let out = s.execute("object.path.simplify", &json!({ "level": level })).unwrap();
assert_eq!(out["level"], json!(f64::from(level)));
counts.push(path_of(&s, id).0.anchor_count());
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}");
assert!(counts[0] < counts[10], "{counts:?}");
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!(path_of(&s, id).0.anchor_count(), counts[5], "level 50 is 1 pt");
}
/// Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer
/// side, and 11 sampled points on each segment of the original path stay that close to the result.
#[test]
fn auto_simplify_keeps_the_shape_within_a_400th_of_its_size() {
let (mut s, id) = dense_wave(100, 15.0, 8.0, 0.2);
let original = path_of(&s, id).0.clone();
// The level the Simplify slider opens at for this selection is the one auto uses.
assert_eq!(crate::auto_simplify_level(&s).unwrap(), 70.0);
let out = s.execute("object.path.simplify", &json!({"auto": true})).unwrap();
// 100 pt across: 0.25 pt at most, level 70 (0.25 pt).
assert_eq!(out["level"], json!(70.0));
let result = path_of(&s, id).0.clone();
assert!(result.anchor_count() < original.anchor_count() / 2, "{}", result.anchor_count());
// How far each point along the original lies from the nearest point of the result.
use vectorcraft_geom::ParamCurve;
use vectorcraft_geom::kurbo::ParamCurveNearest;
let fitted = &result.subpaths[0];
let off = |p: vectorcraft_geom::Point| {
(0..fitted.segment_count()).map(|i| fitted.segment(i).nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)
};
let sp = &original.subpaths[0];
let worst = (0..sp.segment_count()).flat_map(|i| (0..=10).map(move |k| sp.segment(i).eval(f64::from(k) / 10.0))).map(off).fold(0.0, f64::max);
assert!(worst <= 100.0 / 400.0, "{worst}");
}
/// How many steps there are to undo and to redo, and whether the document has unsaved changes.
fn history(s: &Session) -> (usize, usize, bool) {
let st = s.doc().unwrap();
(st.history.undo.len(), st.history.redo.len(), st.is_dirty())
}
/// Select `ids` with a move of them left to redo, and mark the document saved.
fn select_with_a_step_to_redo(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.doc_mut().unwrap().mark_saved();
}
/// Simplify that leaves every path as it is records no undo step: a rectangle, a star and a line,
/// whose sides are straight segments between corners, and a path with one anchor. The step to redo
/// stays, the document stays unmodified, the rectangle and the line stay live shapes, and the reply
/// counts the anchors. With a path it simplifies selected too, Simplify is one undo step that
/// changes only that path, and the others stay as they are, live shapes included.
#[test]
fn simplify_that_changes_no_path_records_no_undo_step() {
let mut s = session();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let r = rect(&mut s, 0.0, 0.0, 100.0, 60.0);
let star = id(s.execute("shape.star", &json!({"cx": 300, "cy": 100, "radius1": 60, "radius2": 30})).unwrap());
let line = id(s.execute("shape.line", &json!({"x1": 0, "y1": 200, "x2": 100, "y2": 240})).unwrap());
let point = id(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 300}]})).unwrap());
let ids = [r, star, line, point];
let paths = |s: &Session| ids.map(|i| path_of(s, i).0);
let is_live = |s: &Session, i| matches!(node(s, i).kind, NodeKind::Path { live: Some(_), .. });
let was = paths(&s);
select_with_a_step_to_redo(&mut s, &ids);
let before = history(&s);
assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved");
for p in [json!({}), json!({"tolerance": 5, "straightLines": true})] {
let out = s.execute("object.path.simplify", &p).unwrap();
assert_eq!(out, json!({"ids": ids.map(|i| i.0), "before": 17, "after": 17}), "{p}");
assert_eq!(history(&s), before, "{p}");
assert_eq!(paths(&s), was, "{p}");
assert!(is_live(&s, r) && is_live(&s, line), "{p}");
assert_eq!(s.journal.last().unwrap(), &("object.path.simplify".to_string(), p));
}
// The 101 anchors of a sine wave become a few.
let anchors: Vec<Value> = (0..=100)
.map(|i| {
let x = i as f64 * 3.0;
json!({"x": x, "y": 400.0 + 40.0 * (x / 50.0).sin()})
})
.collect();
let wave = id(s.execute("path.create", &json!({"anchors": anchors})).unwrap());
s.execute("select.set", &json!({"ids": [r.0, star.0, line.0, point.0, wave.0]})).unwrap();
let undo = history(&s).0;
s.execute("object.path.simplify", &json!({})).unwrap();
assert_eq!(history(&s), (undo + 1, 0, true));
assert!(path_of(&s, wave).0.anchor_count() < 25);
assert_eq!(paths(&s), was);
assert!(is_live(&s, r) && is_live(&s, line), "the paths Simplify leaves as they are stay live shapes");
}
/// The Simplify dialog previews Simplify in an interaction, and OK commits the preview. When the
/// preview changes no path, OK records no undo step: the step to redo stays, the document stays
/// unmodified and the rectangle stays a live shape.
#[test]
fn simplify_preview_that_changes_no_path_commits_no_undo_step() {
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 100.0, 60.0);
select_with_a_step_to_redo(&mut s, &[r]);
let before = history(&s);
s.begin_interaction("Simplify").unwrap();
let out = s.preview("object.path.simplify", &json!({"tolerance": 1.0})).unwrap();
assert_eq!(out, json!({"ids": [r.0], "before": 4, "after": 4}));
s.commit_interaction().unwrap();
assert_eq!(history(&s), before);
assert!(matches!(node(&s, r).kind, NodeKind::Path { live: Some(_), .. }));
}
#[test]
fn simplify_refreshes_changed_path_selection_and_undo() {
let mut s = session();
let anchors: Vec<Value> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 100.0 + (i % 2) as f64 * 0.1})).collect();
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
// A one-anchor path cannot be simplified; its component selection must stay.
let kept = NodeId(s.execute("path.create", &json!({"anchors": [{"x": 350, "y": 180}]})).unwrap()["id"].as_u64().unwrap());
let unrelated = rect(&mut s, 400.0, 200.0, 40.0, 30.0);
s.edit("selection fixture", |d, sel| {
let guide = d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 30.0));
sel.set([kept, id]);
sel.anchors.insert(id, [(0, 19)].into_iter().collect());
sel.anchors.insert(kept, [(0, 0)].into_iter().collect());
sel.key = Some(kept);
sel.target = Some(id);
sel.guides.push(guide);
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let undo_len = s.doc().unwrap().history.undo.len();
let out = s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!((out["before"].as_u64(), out["after"].as_u64()), (Some(21), Some(3)));
assert_eq!(path_of(&s, id).0.anchor_count(), 2);
let mut expected_selection = selection.clone();
expected_selection.anchors.remove(&id);
assert_eq!(s.doc().unwrap().selection, expected_selection, "only the changed path becomes selected whole");
assert_eq!(node(&s, unrelated), before.node(unrelated).unwrap().clone());
let after = s.doc().unwrap().doc.clone();
let mut restored = after.clone();
std::sync::Arc::make_mut(&mut restored).node_mut(id).unwrap().kind = before.node(id).unwrap().kind.clone();
assert_eq!(restored, before, "all document state except the simplified geometry is preserved");
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().selection, selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
assert_eq!(s.doc().unwrap().selection, expected_selection);
}
#[test]
fn add_anchor_points_refreshes_components_even_when_old_indexes_still_exist() {
let mut s = session();
let id = rect(&mut s, 20.0, 30.0, 100.0, 70.0);
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let out = s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
assert_eq!((out["before"].as_u64(), out["after"].as_u64()), (Some(4), Some(8)));
assert!(s.doc().unwrap().selection.anchors.is_empty());
assert_eq!(s.doc().unwrap().selection.objects, selection.objects);
assert!(close(bounds(&s, id), before.node(id).unwrap().geometric_bounds().unwrap(), 1e-9));
let after = s.doc().unwrap().doc.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().selection, selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
assert!(s.doc().unwrap().selection.anchors.is_empty());
}
#[test]
fn simplify_refreshes_components_inside_selected_groups() {
let mut s = session();
let anchors: Vec<Value> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 100.0 + (i % 2) as f64 * 0.1})).collect();
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let other = rect(&mut s, 400.0, 200.0, 40.0, 30.0);
s.execute("select.set", &json!({"ids": [id.0, other.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| {
sel.anchors.insert(id, [(0, 19)].into_iter().collect());
})
.unwrap();
let other_before = node(&s, other);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![group]);
assert!(s.doc().unwrap().selection.anchors.is_empty());
assert_eq!(path_of(&s, id).0.anchor_count(), 2);
assert_eq!(node(&s, other).appearance, other_before.appearance);
}
#[test]
fn add_anchor_points_doubles() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
assert_eq!(path_of(&s, a).0.anchor_count(), 8);
assert!(close(bounds(&s, a), Rect::new(0.0, 0.0, 10.0, 10.0), 1e-9));
}
/// Add Anchor Points with only paths of one anchor selected records no undo step. With a rectangle
/// selected too, it is one undo step that adds four anchors to the rectangle and leaves the
/// one-anchor path as it is.
#[test]
fn add_anchor_points_with_no_segment_records_no_undo_step() {
let mut s = session();
let point = NodeId(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap());
let a = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let was = path_of(&s, point).0;
select_with_a_step_to_redo(&mut s, &[point]);
let before = history(&s);
let out = s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
assert_eq!(out, json!({"ids": [point.0], "before": 1, "after": 1}));
assert_eq!(history(&s), before);
assert_eq!(s.journal.last().unwrap().0, "object.path.addAnchorPoints");
s.execute("select.set", &json!({"ids": [point.0, a.0]})).unwrap();
let out = s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
assert_eq!(out, json!({"ids": [point.0, a.0], "before": 5, "after": 9}));
assert_eq!(history(&s), (before.0 + 1, 0, true));
assert_eq!(path_of(&s, point).0, was);
}
#[test]
fn split_into_grid_cells() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 110.0, 50.0);
let r = ids(&s.execute("object.path.splitIntoGrid", &json!({"rows": 2, "columns": 3, "gutter": 10})).unwrap());
assert_eq!(r.len(), 6);
assert!(close(bounds(&s, r[0]), Rect::new(0.0, 0.0, 30.0, 20.0), 1e-9));
assert!(s.execute("object.path.splitIntoGrid", &json!({"rows": 0})).is_err());
}
/// Split Into Grid's documented options: a gutter for the rows and one for the columns, the size
/// of each row and column or of the whole grid, and guides along the row and column edges. Several
/// selected paths give one grid over them all, painted as the topmost one, where it was.
#[test]
fn split_into_grid_options() {
let grid = |p: Value| {
let mut s = session();
rect(&mut s, 10.0, 20.0, 110.0, 50.0);
let r = s.execute("object.path.splitIntoGrid", &p).unwrap();
let cells: Vec<Rect> = ids(&r).iter().map(|id| bounds(&s, *id)).collect();
let guides: Vec<(bool, f64)> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect();
assert_eq!(r["guides"], guides.len());
(cells, guides)
};
// A gutter each way; the grid keeps the path's size.
let (cells, guides) = grid(json!({"rows": 2, "columns": 3, "rowGutter": 10, "columnGutter": 4}));
assert!(close(cells[0], Rect::new(10.0, 20.0, 44.0, 40.0), 1e-9) && close(cells[5], Rect::new(86.0, 50.0, 120.0, 70.0), 1e-9), "{cells:?}");
assert!(guides.is_empty());
// The whole grid's size, from the path's top left corner.
let (cells, _) = grid(json!({"rows": 1, "columns": 2, "gutter": 0, "totalWidth": 60, "totalHeight": "1 in"}));
assert!(close(cells[1], Rect::new(40.0, 20.0, 70.0, 92.0), 1e-9), "{cells:?}");
// The size of each row and column makes the total, whatever total is given.
let (cells, guides) = grid(json!({"rows": 2, "columns": 2, "gutter": 5, "width": 20, "height": 10, "totalWidth": 500, "addGuides": true}));
assert!(close(cells[3], Rect::new(35.0, 35.0, 55.0, 45.0), 1e-9), "{cells:?}");
let edges = |vertical, at: [f64; 4]| at.map(|pos| (vertical, pos));
assert_eq!(guides, [edges(true, [10.0, 30.0, 35.0, 55.0]), edges(false, [20.0, 30.0, 35.0, 45.0])].concat());
// Without a gutter the rows share their edges: one guide for each.
let (_, guides) = grid(json!({"rows": 2, "columns": 1, "gutter": 0, "addGuides": true}));
assert_eq!(guides, [(true, 10.0), (true, 120.0), (false, 20.0), (false, 45.0), (false, 70.0)]);
let mut s = session();
let back = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let kept = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
let front = rect(&mut s, 60.0, 20.0, 40.0, 40.0);
set_fill(&mut s, front, Color::rgb(0.1, 0.6, 0.3));
s.execute("select.set", &json!({"ids": [front.0, back.0]})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
let r = ids(&s.execute("object.path.splitIntoGrid", &json!({"rows": 1, "columns": 2, "gutter": 20, "addGuides": true})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(0.0, 0.0, 40.0, 60.0), 1e-9) && close(bounds(&s, r[1]), Rect::new(60.0, 0.0, 100.0, 60.0), 1e-9));
let st = s.doc().unwrap();
assert!(r.iter().all(|id| node(&s, *id).appearance == node(&s, r[0]).appearance) && st.doc.node(back).is_none() && st.doc.node(front).is_none());
let art: Vec<NodeId> = st.doc.layers[0].children().unwrap().iter().filter(|n| !n.is_ruler_guide()).map(|n| n.id).collect();
assert_eq!(art, [kept, r[0], r[1]], "above the path left alone");
let children = st.doc.layers[0].children().unwrap();
assert!(children.len() == 9 && children[3..].iter().all(|n| n.is_ruler_guide()), "the six guides are above the art");
assert_eq!(st.selection.objects, r);
assert!(st.doc.ruler_guides().iter().all(|g| g.layer == Some(st.doc.layers[0].id)));
assert_eq!(st.history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(st.doc.node(back).is_some() && st.doc.node(front).is_some() && st.doc.ruler_guides().is_empty());
// A grid with no room for its gutters is refused and changes nothing.
assert!(s.execute("object.path.splitIntoGrid", &json!({"columns": 4, "gutter": 50})).is_err());
assert!(s.execute("object.path.splitIntoGrid", &json!({"width": -5})).is_err());
assert!(s.doc().unwrap().doc.node(back).is_some());
}
#[test]
fn clean_up_removes_junk() {
let mut s = session();
let keep = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let unpainted = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
s.edit("t", |d, _| {
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 1.0).into();
Ok(())
})
.unwrap();
let stray = NodeId(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap());
let empty = NodeId(s.execute("text.create", &json!({"x": 10, "y": 10, "text": ""})).unwrap()["id"].as_u64().unwrap());
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
assert_eq!(r["removed"], 3);
let d = &s.doc().unwrap().doc;
assert!(d.node(keep).is_some());
assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none());
}
/// A path drawn by `d`, filled black with no stroke.
fn filled(s: &mut Session, d: &str) -> NodeId {
let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap());
fill_only(s, id);
id
}
fn fill_only(s: &mut Session, id: NodeId) {
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into();
Ok(())
})
.unwrap();
}
/// Hairline Slivers' test art: (the slivers, the shapes with a width).
fn sliver_art(s: &mut Session) -> (Vec<NodeId>, Vec<NodeId>) {
// A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide
// and tall. A long one across the page. A compound path of two slivers.
let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z");
let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z");
let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z");
let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, two);
// Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it
// draws a line), an open path, and a compound path of a sliver and a square.
let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z");
let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap());
fill_only(s, dot);
let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into();
Ok(())
})
.unwrap();
let open = filled(s, "M500 10 L540 40 L500.001 10.0015");
let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z");
let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z");
s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap();
let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, mixed);
s.execute("select.none", &json!({})).unwrap();
(vec![triangle, long, two], vec![strip, dot, stroked, open, mixed])
}
#[test]
fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() {
let mut s = session();
let (slivers, kept) = sliver_art(&mut s);
// Off by default.
assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0);
// A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is
// at 0 % opacity paints nothing either.
let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z");
let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z");
s.edit("t", |d, _| {
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0);
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() {
f.opacity = 0.0;
}
d.node_mut(clear).unwrap().appearance = a.into();
Ok(())
})
.unwrap();
let kept = [kept, vec![unpainted, clear]].concat();
let undo = s.doc().unwrap().history.undo.len();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left");
for (k, id) in kept.iter().enumerate() {
assert!(d.node(*id).is_some(), "shape {k} with a width went");
}
assert_eq!(r["removed"], slivers.len());
// One undo step brings every sliver back.
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some()));
// A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot.
let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"});
assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1);
assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some());
}
/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or
/// locked slivers.
#[test]
fn select_hairline_slivers_selects_what_clean_up_removes() {
let mut s = session();
let (slivers, _) = sliver_art(&mut s);
let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z");
let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z");
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
d.node_mut(locked).unwrap().locked = true;
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], slivers.len());
let mut selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
selected.sort_unstable();
let mut want = slivers.clone();
want.sort_unstable();
assert_eq!(selected, want);
// Inside an isolated group, only the slivers in it are selected.
let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z");
let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z");
s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
// A sliver in a group is selected as Clean Up finds it.
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1);
assert!(s.doc().unwrap().selection.objects.contains(&inner));
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A template layer that was unlocked afterward.
let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z");
s.edit("t", |d, _| {
let n = d.node_mut(template).unwrap();
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = true;
}
n.locked = false;
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(template).unwrap().is_template());
s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert!(!s.doc().unwrap().selection.objects.contains(&traced));
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some());
}
/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint
/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's
/// clipping path; Clean Up's other options keep the layer's clipping path too.
#[test]
fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() {
let mut s = session();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [rough.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap();
let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z");
let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z");
s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap();
s.execute("livePaint.make", &json!({})).unwrap();
// A group's own 5 pt stroke draws along its member.
let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into();
Ok(())
})
.unwrap();
// A thin part of type's glyph outlines.
let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap();
let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(outlines).unwrap().extras_mut().type_outlines = true;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
// A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects
// removes the clipping path.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z");
let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z");
let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went");
// A clip group whose clipping path is a sliver.
let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z");
let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
// A guide drawn as a sliver, and a sliver with an effect on its stroke.
let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z");
let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind {
*guide = true;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(mask).is_some(), "the clip group's clipping path went");
assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went");
// A layer clipped by a group (as an opened file can have it): its sliver member clips too.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z");
let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [bare.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind {
*clip = true;
let i = children.iter().position(|c| c.id == g).unwrap();
let c = children.remove(i);
children.insert(0, c);
}
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went");
}
/// A sliver on a locked artboard is left alone.
#[test]
fn hairline_slivers_leave_art_on_a_locked_artboard_alone() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.edit("t", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
assert!(s.doc().unwrap().doc.node(sliver).is_some());
}
/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone.
#[test]
fn hairline_slivers_leave_art_at_zero_opacity_alone() {
let mut s = session();
let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(clear).unwrap().opacity = 0.0;
d.node_mut(group).unwrap().opacity = 0.0;
d.node_mut(seen).unwrap().opacity = 0.5;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1);
let d = &s.doc().unwrap().doc;
assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went");
assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed");
}
/// A shape too complex to measure is kept, and both commands say how many there were.
#[test]
fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
// A closed zigzag of more anchors than one shape is measured with.
let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1;
let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect();
let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind {
*path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true));
}
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
assert_eq!(r["removed"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let d = &s.doc().unwrap().doc;
assert!(d.node(sliver).is_none() && d.node(huge).is_some());
}
/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the
/// document, the selection and the undo history stay as they were.
#[test]
fn hairline_slivers_refuse_a_width_out_of_range() {
let mut s = session();
sliver_art(&mut s);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] {
for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] {
let mut p = serde_json::Map::new();
p.insert(key.into(), w.clone());
if cmd == "object.path.cleanUp" {
p.insert("hairlineSlivers".into(), json!(true));
}
let r = s.execute(cmd, &Value::Object(p));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}");
assert!(state(&s) == before, "{cmd} {w} changed the document");
}
}
// Both ends of the range are taken.
for w in [json!(0.001), json!(3), json!("3 pt")] {
assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}");
let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w});
assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}");
}
}
/// A page-sized square under a ring (a compound path with a square hole), nothing selected.
fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) {
let art = rect(s, 0.0, 0.0, 100.0, 100.0);
let (outer, inner) = (rect(s, 10.0, 10.0, 80.0, 80.0), rect(s, 35.0, 35.0, 30.0, 30.0));
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
s.execute("path.reverse", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let ring = s.doc().unwrap().selection.objects[0];
s.execute("select.none", &json!({})).unwrap();
(art, ring)
}
fn one_anchor_path(s: &mut Session) -> NodeId {
NodeId(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap())
}
fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap())
}
fn clip_path_of(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
let n = node(s, id);
assert!(n.clips(), "{id:?} still clips");
(*n.children().unwrap()[0]).clone()
}
/// Unpainted Objects leaves a clipping layer's clipping path, which has no paint of its own.
#[test]
fn clean_up_keeps_a_layers_clipping_path() {
let mut s = session();
let (art, ring) = art_and_ring(&mut s);
let layer = s.doc().unwrap().current_layer().unwrap();
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap()["clip"].as_bool().unwrap());
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
assert_eq!(r["removed"], 0);
assert_eq!(clip_path_of(&s, layer).id, ring);
assert!(s.doc().unwrap().doc.node(art).is_some());
}
/// Stray Points leaves the one-anchor members of a compound path used as a clipping path.
#[test]
fn clean_up_keeps_the_members_of_a_compound_clipping_path() {
let mut s = session();
let (art, ring) = art_and_ring(&mut s);
let stray = one_anchor_path(&mut s);
let g = clip_group(&mut s, &[art, ring]);
s.edit("t", |d, _| {
let n = d.remove(stray)?;
d.children_mut(Some(ring))?.push(n);
Ok(())
})
.unwrap();
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
assert_eq!(r["removed"], 0);
let clip = clip_path_of(&s, g);
assert_eq!(clip.id, ring);
assert!(clip.children().unwrap().iter().any(|c| c.id == stray));
}
/// No option removes a member of a group used as a clipping path, or empty type used as one.
#[test]
fn clean_up_keeps_a_group_or_type_used_as_a_clipping_path() {
let mut s = session();
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let top = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
let g = clip_group(&mut s, &[art, top]);
let unpainted = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
let stray = one_anchor_path(&mut s);
let empty = NodeId(s.execute("text.create", &json!({"x": 10, "y": 10, "text": ""})).unwrap()["id"].as_u64().unwrap());
let inner = s
.edit("t", |d, _| {
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 1.0).into();
let members = [top, unpainted, stray, empty].map(|id| d.remove(id)).into_iter().collect::<std::result::Result<Vec<_>, _>>()?;
let inner = d.alloc_id();
d.children_mut(Some(g))?.insert(0, std::sync::Arc::new(vectorcraft_doc::Node::group(inner, members)));
Ok(inner)
})
.unwrap();
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
assert_eq!(r["removed"], 0);
let clip = clip_path_of(&s, g);
assert_eq!(clip.id, inner);
assert_eq!(clip.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>(), [top, unpainted, stray, empty]);
// Type of spaces on top of a clip group clips by nothing, and still stays its clipping path.
let art = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
let blank = NodeId(s.execute("text.create", &json!({"x": 210, "y": 10, "text": " "})).unwrap()["id"].as_u64().unwrap());
let g = clip_group(&mut s, &[art, blank]);
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
assert_eq!(r["removed"], 0);
assert_eq!(clip_path_of(&s, g).id, blank);
}
/// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an
/// error naming the param, and leave the document, the selection and the undo history as they were.
/// Null keeps a param's default, and a distance still takes a string with a unit.
#[test]
fn path_commands_refuse_a_param_of_the_wrong_type() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
let number = |k: &str, v: &str| format!("`{k}` must be a number, not {v}");
let switch = |k: &str| format!("`{k}` must be true or false");
for (cmd, p, want) in [
("object.path.offsetPath", json!({"offset": true}), number("offset", "true")),
("object.path.offsetPath", json!({"offset": "wide"}), number("offset", "\"wide\"")),
("object.path.offsetPath", json!({"offset": "10abc"}), number("offset", "\"10abc\"")),
("object.path.offsetPath", json!({"offset": 5, "miterLimit": "4x"}), number("miterLimit", "\"4x\"")),
("object.path.offsetPath", json!({"offset": 5, "joins": 3}), "`joins` must be a string".to_string()),
("object.path.offsetPath", json!({"offset": 5, "joins": "pointy"}), "`joins` must be one of miter, round, bevel".to_string()),
("object.path.offsetPath", json!({"offset": 5, "miterLimit": [4]}), number("miterLimit", "[4]")),
("object.path.simplify", json!({"auto": "true"}), switch("auto")),
("object.path.simplify", json!({"level": false}), number("level", "false")),
("object.path.simplify", json!({"level": 50, "tolerance": {}}), number("tolerance", "{}")),
("object.path.simplify", json!({"cornerAngle": "sharp"}), number("cornerAngle", "\"sharp\"")),
("object.path.simplify", json!({"straightLines": 1}), switch("straightLines")),
("object.path.simplify", json!({"wholePaths": "no"}), switch("wholePaths")),
("object.path.splitIntoGrid", json!({"rows": "many"}), number("rows", "\"many\"")),
("object.path.splitIntoGrid", json!({"columns": true}), number("columns", "true")),
("object.path.splitIntoGrid", json!({"gutter": false}), number("gutter", "false")),
("object.path.splitIntoGrid", json!({"rowGutter": 2, "gutter": "x"}), number("gutter", "\"x\"")),
("object.path.splitIntoGrid", json!({"height": 5, "totalHeight": [1]}), number("totalHeight", "[1]")),
("object.path.splitIntoGrid", json!({"width": "wide"}), number("width", "\"wide\"")),
("object.path.splitIntoGrid", json!({"columnGutter": true}), number("columnGutter", "true")),
("object.path.splitIntoGrid", json!({"totalWidth": {}}), number("totalWidth", "{}")),
("object.path.splitIntoGrid", json!({"rowGutter": "a"}), number("rowGutter", "\"a\"")),
("object.path.splitIntoGrid", json!({"addGuides": "yes"}), switch("addGuides")),
("object.path.cleanUp", json!({"strayPoints": "false"}), switch("strayPoints")),
("object.path.cleanUp", json!({"unpaintedObjects": 0}), switch("unpaintedObjects")),
("object.path.cleanUp", json!({"emptyTextPaths": "no"}), switch("emptyTextPaths")),
] {
let r = s.execute(cmd, &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}");
assert!(state(&s) == before, "{cmd} {p} changed the document, the selection or the undo history");
}
// Null takes the default: a 10 pt offset with mitered joins.
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": null, "joins": null, "miterLimit": null})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(90.0, 90.0, 160.0, 150.0), 1e-2), "{:?}", bounds(&s, r[0]));
// A distance with a unit, and a join named in capitals.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0]));
// A product with a unit, which the offset used to refuse: 0.05x2 in is 0.1 in.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.05x2 in", "joins": "Bevel"})).unwrap());
assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0]));
// Null switches keep Clean Up's defaults, which remove the stray point.
let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap();
assert_eq!(r["removed"], 1);
// Split Into Grid with null counts and a gutter with a unit: two by two, 0.5 in apart.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let r = ids(&s.execute("object.path.splitIntoGrid", &json!({"rows": null, "columns": null, "gutter": "0.5 in", "addGuides": null})).unwrap());
assert_eq!(r.len(), 4);
assert!(close(bounds(&s, r[0]), Rect::new(100.0, 100.0, 107.0, 102.0), 1e-9), "{:?}", bounds(&s, r[0]));
}
#[test]
fn divide_objects_below_cuts() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let cutter = rect(&mut s, 50.0, -10.0, 100.0, 120.0);
s.execute("select.set", &json!({"ids": [cutter.0]})).unwrap();
let r = ids(&s.execute("object.path.divideObjectsBelow", &json!({})).unwrap());
assert_eq!(r.len(), 2);
let d = &s.doc().unwrap().doc;
assert!(d.node(a).is_none() && d.node(cutter).is_none());
let total: f64 = r.iter().map(|id| area_of(&s, *id)).sum();
assert!((total - 10000.0).abs() < 1.0);
}
fn text(s: &mut Session, t: &str, size: f64) -> NodeId {
let r = s.execute("text.create", &json!({"x": 10, "y": 50, "text": t, "size": size})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
#[test]
fn create_outlines_matches_text_bounds() {
let mut s = session();
let t = text(&mut s, "Hello bo", 36.0);
let tb = bounds(&s, t);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
assert!(s.doc().unwrap().doc.node(t).is_none());
let g = node(&s, r[0]);
let ch = g.children().unwrap();
assert_eq!(ch.len(), 7, "one per visible glyph");
assert!(ch.iter().any(|c| matches!(c.kind, NodeKind::Compound { .. })), "o/b have holes");
assert!(ch.iter().all(|c| c.appearance.fill_paint() == Paint::solid(Color::BLACK)));
let gb = g.geometric_bounds().unwrap();
assert!(gb.x0 >= tb.x0 - 2.0 && gb.x1 <= tb.x1 + 2.0 && gb.y0 >= tb.y0 - 2.0 && gb.y1 <= tb.y1 + 2.0, "{gb:?} vs {tb:?}");
assert!(gb.width() > tb.width() * 0.8);
assert_eq!(s.doc().unwrap().selection.objects, r);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(t).is_some());
}
/// The type object's own fills and strokes (not its characters') become paths of its whole outline,
/// with ids of their own: those below the Characters row under the glyph paths, the others over
/// them, in their order. The group keeps no appearance of its own, and Undo brings the type back.
#[test]
fn create_outlines_keeps_the_objects_own_fills_and_strokes() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
for (cmd, p) in [
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 0, "color": "#ff0000"})),
("appearance.addStroke", json!({"target": "object"})),
("appearance.setItem", json!({"index": 1, "color": "#0000ff", "weight": 5})),
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 2, "color": "#00ff00", "opacity": 50})),
// The red fill paints below the characters; the stroke and the green fill over them.
("appearance.moveItem", json!({"from": "contents", "to": 1})),
] {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
}
let own = node(&s, t).appearance.items.clone();
assert_eq!(own.len(), 3);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert!(g.appearance.items.is_empty(), "the group paints nothing of its own");
let ch = g.children().unwrap();
assert_eq!(ch.len(), 4, "a path below, the two glyphs, a path above");
let (first, last) = (&ch[0], &ch[3]);
assert_eq!(first.appearance.items, own[..1], "the item below the characters");
assert_eq!(last.appearance.items, own[1..], "the items over them, in their order");
for c in [first, last] {
assert!(matches!(c.kind, NodeKind::Path { .. }), "{:?}", c.kind);
assert!(c.id != t && c.id != g.id, "a fresh id");
}
assert!(first.id != last.id);
for c in &ch[1..3] {
assert_eq!(c.appearance.fill_paint(), Paint::solid(Color::BLACK), "the characters keep their own paint");
}
// The whole-outline paths cover both glyphs.
let glyphs = ch[1].geometric_bounds().unwrap().union(ch[2].geometric_bounds().unwrap());
assert!(close(first.geometric_bounds().unwrap(), glyphs, 1e-6), "{:?} vs {glyphs:?}", first.geometric_bounds());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, t).appearance.items, own, "one undo step brings the type back");
}
/// The type object's own effects go on the group once, in their order, with their settings and a
/// hidden one still hidden; a fill's own effect stays on its path of the whole outline, and no
/// glyph or whole-outline path takes the object's effects. Undo brings the type back with them.
#[test]
fn create_outlines_keeps_the_objects_own_effects_on_the_group() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
for (cmd, p) in [
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 0, "color": "#ff0000"})),
("effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 2}, "item": 0})),
("effect.apply", json!({"effect": "stylize.dropShadow", "params": {"x": 7, "y": 3, "blur": 0, "opacity": 60}, "item": null})),
("effect.apply", json!({"effect": "distort.transform", "params": {"rotate": 15}, "item": null})),
("effect.setParams", json!({"index": 1, "visible": false, "item": null})),
] {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
}
let own: Appearance = (*node(&s, t).appearance).clone();
let ids_of = |fx: &[vectorcraft_doc::Effect]| fx.iter().map(|e| (e.id.clone(), e.visible)).collect::<Vec<_>>();
assert_eq!(ids_of(&own.effects), [("stylize.dropShadow".to_string(), true), ("distort.transform".to_string(), false)]);
assert_eq!(ids_of(own.items[0].effects()), [("path.offsetPath".to_string(), true)]);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(g.appearance.effects, own.effects, "the group holds the object's effects as they were");
let ch = g.children().unwrap();
assert!(ch.iter().all(|c| c.appearance.effects.is_empty()), "no piece takes the object's effects");
let rows: Vec<_> = ch.iter().filter(|c| c.appearance.items == own.items).collect();
assert_eq!(rows.len(), 1, "one path of the whole outline paints the object's fill");
assert_eq!(rows[0].appearance.items[0].effects(), own.items[0].effects(), "the fill keeps its own effect");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*node(&s, t).appearance, own, "one undo step brings the type back with its effects");
}
/// The group takes the type object's opacity, blend mode, Isolate Blending, Opacity & Mask Define
/// Knockout Shape and opacity mask.
#[test]
fn create_outlines_keeps_the_objects_transparency_and_opacity_mask() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
let m = rect(&mut s, 0.0, 0.0, 40.0, 80.0);
s.execute("select.set", &json!({"ids": [t.0, m.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let p = json!({"ids": [t.0], "opacity": 70, "blend": "multiply", "isolate": true, "knockoutShape": true});
s.execute("transparency.set", &p).unwrap();
let before = node(&s, t);
assert!(before.extras().mask.is_some(), "the type has a mask");
let look = |n: &vectorcraft_doc::Node| (n.opacity, n.blend, n.isolate, n.knockout_shape);
assert_eq!(look(&before), (0.7, vectorcraft_color::BlendMode::Multiply, true, true));
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(look(&g), look(&before));
assert_eq!(g.extras().mask, before.extras().mask, "the group keeps the type's opacity mask");
}
/// Colour bitmap glyphs (emoji) become embedded images where they sat; glyphs showing one image
/// share its pixels.
#[test]
fn create_outlines_turns_bitmap_glyphs_into_images() {
let _fonts = crate::adding_fonts();
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colour_bitmap_family, colour_bitmap_font};
vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap());
let mut s = session();
let r = s
.execute(
"text.create",
&json!({"x": 10, "y": 50, "text": format!("{COLOUR_CHAR}F{COLOUR_CHAR}"), "size": 32, "font": colour_bitmap_family(false)}),
)
.unwrap();
let t = NodeId(r["id"].as_u64().unwrap());
let tb = bounds(&s, t);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
let ch = g.children().unwrap();
let images: Vec<_> = ch.iter().filter_map(|c| if let NodeKind::Image(im) = &c.kind { Some(im) } else { None }).collect();
assert_eq!(images.len(), 2, "{:?}", ch.iter().map(|c| c.kind_label()).collect::<Vec<_>>());
assert!(matches!(ch[1].kind, NodeKind::Path { .. } | NodeKind::Compound { .. }), "the outline between them");
assert_eq!(images[0].key, images[1].key, "one image");
let d = &s.doc().unwrap().doc;
assert!(d.images.contains_key(&images[0].key));
// The first one em (32 pt) square, from 2 px (4 pt) right of the origin and 12 px (24 pt)
// above the baseline; inside the type's bounds.
let b = ch[0].geometric_bounds().unwrap();
assert!((b.x0 - 14.0).abs() < 1e-6 && (b.y0 - 26.0).abs() < 1e-6 && (b.width() - 32.0).abs() < 1e-6, "{b:?}");
assert!(b.x0 >= tb.x0 && b.y0 >= tb.y0 - 1e-6 && b.y1 <= tb.y1 + 1e-6, "{b:?} in {tb:?}");
}
/// A glyph image whose key another image of the document holds gets a key of its own.
#[test]
fn create_outlines_keeps_an_image_already_under_a_glyph_images_key() {
let _fonts = crate::adding_fonts();
use vectorcraft_text::test_fonts::{COLOUR_CHAR, COLOUR_LARGE, COLOUR_PPEM, colour_bitmap_family, colour_bitmap_font, solid_png};
vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap());
let mut s = session();
let glyph = vectorcraft_doc::ImageBlob::png(solid_png(COLOUR_PPEM.into(), COLOUR_LARGE));
let taken = glyph.content_key();
let other = vectorcraft_doc::ImageBlob::png(solid_png(4, [0, 255, 0, 255]));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(taken.clone(), other.clone());
s.execute("text.create", &json!({"x": 10, "y": 50, "text": COLOUR_CHAR.to_string(), "size": 32, "font": colour_bitmap_family(false)})).unwrap();
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
let Some(NodeKind::Image(im)) = g.children().unwrap().first().map(|c| &c.kind) else { panic!("an image") };
let d = &s.doc().unwrap().doc;
assert_ne!(im.key, taken);
assert_eq!(d.images[&im.key].bytes, glyph.bytes, "the glyph's own pixels");
assert_eq!(d.images[&taken].bytes, other.bytes, "the other image is kept");
}
#[test]
fn set_style_size_changes_bounds() {
let mut s = session();
let t = text(&mut s, "Hello", 12.0);
let b0 = bounds(&s, t);
s.execute("text.setStyle", &json!({"size": 24, "justify": "center", "fill": "#ff0000", "leading": "auto"})).unwrap();
let b1 = bounds(&s, t);
assert!(b1.width() > b0.width() * 1.8, "{b0:?} → {b1:?}");
let NodeKind::Text(tx) = node(&s, t).kind else { panic!() };
assert_eq!(tx.first_style().size, 24.0);
assert_eq!(tx.para.justify, vectorcraft_doc::Justify::Center);
assert_eq!(tx.first_style().fill, Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
assert!(s.execute("text.setStyle", &json!({"justify": "diagonal"})).is_err());
assert!(s.execute("text.setStyle", &json!({})).is_err());
}
#[test]
fn set_text_updates_bounds() {
let mut s = session();
let t = text(&mut s, "Hi", 24.0);
let b0 = bounds(&s, t);
s.execute("text.setText", &json!({"id": t.0, "text": "Hello there"})).unwrap();
let NodeKind::Text(tx) = node(&s, t).kind else { panic!() };
assert_eq!(tx.plain_text(), "Hello there");
assert!(bounds(&s, t).width() > b0.width() * 2.0);
assert!(s.execute("text.setText", &json!({"id": t.0})).is_err());
s.execute("edit.undo", &json!({})).unwrap();
let NodeKind::Text(tx) = node(&s, t).kind else { panic!() };
assert_eq!(tx.plain_text(), "Hi");
}
#[test]
fn commands_reject_bad_input() {
let mut s = session();
two_rects(&mut s);
for (c, p) in [
("object.path.offsetPath", json!({"offset": "abc"})),
("object.path.offsetPath", json!({"offset": 1e300})),
("object.path.simplify", json!({"tolerance": -5})),
("object.path.splitIntoGrid", json!({"rows": 1e9, "columns": -1})),
("text.setStyle", json!({"size": -3})),
("type.createOutlines", json!({})),
("object.pathfinder.divide", json!({"junk": [1, 2]})),
] {
let _ = s.execute(c, &p);
}
}
#[test]
fn divide_cutting_lines_keep_appearance_unrelated_art_and_one_undo() {
for (line_has_fill, curved) in [(false, false), (true, false), (false, true)] {
let mut s = session();
let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let cutter =
NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap());
let kept = rect(&mut s, 200.0, 0.0, 30.0, 30.0);
s.edit("divide fixture", |d, sel| {
let n = d.node_mut(base).unwrap();
n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.7)), Paint::solid(Color::BLACK), 3.0).into();
n.opacity = 0.65;
n.blend = vectorcraft_color::BlendMode::Multiply;
let n = d.node_mut(cutter).unwrap();
n.appearance =
Appearance::basic(if line_has_fill { Paint::solid(Color::BLACK) } else { Paint::None }, Paint::solid(Color::rgb(0.8, 0.2, 0.1)), 2.0)
.into();
if curved {
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((-10.0, 50.0));
bp.curve_to((30.0, 15.0), (70.0, 85.0), (110.0, 50.0));
n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
}
sel.set([cutter, base]);
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let selected = s.doc().unwrap().selection.clone();
let undo_len = s.doc().unwrap().history.undo.len();
let result = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap())[0];
let group = node(&s, result);
let pieces = group.children().unwrap();
assert_eq!(pieces.len(), 2, "line fill {line_has_fill}, curved {curved}");
let source = before.node(base).unwrap();
assert!(pieces.iter().all(|n| n.appearance == source.appearance && n.opacity == source.opacity && n.blend == source.blend));
let total: f64 = pieces.iter().map(|n| area_of(&s, n.id)).sum();
assert!((total - 10000.0).abs() < 0.01);
assert_eq!(node(&s, kept), *before.node(kept).unwrap());
assert!(s.doc().unwrap().doc.node(base).is_none() && s.doc().unwrap().doc.node(cutter).is_none());
assert_eq!(s.doc().unwrap().selection.objects, vec![result]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len + 1);
let after = s.doc().unwrap().doc.clone();
let result_selection = s.doc().unwrap().selection.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().selection, selected);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
assert_eq!(s.doc().unwrap().selection, result_selection);
}
}
#[test]
fn divide_keeps_implicitly_closed_filled_paths_including_zero_signed_area() {
for anchors in [
json!([{"x": 10, "y": 10}, {"x": 50, "y": 90}, {"x": 90, "y": 10}]),
json!([{"x": 0, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}, {"x": 100, "y": 0}]),
] {
let mut s = session();
let filled = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let cutter =
NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 150}, {"x": 110, "y": 150}]})).unwrap()["id"].as_u64().unwrap());
s.edit("open fill fixture", |d, sel| {
let mut appearance = Appearance::basic(Paint::solid(Color::rgb(0.1, 0.7, 0.2)), Paint::None, 0.0);
// An empty top fill must not hide the nonempty fill below it.
appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::None)));
d.node_mut(filled).unwrap().appearance = appearance.into();
d.node_mut(cutter).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
sel.set([cutter, filled]);
Ok(())
})
.unwrap();
let source = node(&s, filled);
assert!(source.path_data().unwrap().subpaths.iter().all(|sp| !sp.closed));
let expected = area_of(&s, filled);
assert!(expected > 3000.0);
let result = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap())[0];
let group = node(&s, result);
let pieces = group.children().unwrap();
let actual: f64 = pieces.iter().map(|n| area_of(&s, n.id)).sum();
assert!((actual - expected).abs() < 0.01, "{actual} != {expected}");
assert!(pieces.iter().all(|n| n.appearance == source.appearance));
}
}
/// #1570: Trim, Merge and Crop remove the objects' strokes; Merge then merges same-coloured
/// fills whatever their strokes were.
#[test]
fn trim_merge_and_crop_remove_strokes() {
for op in ["trim", "merge", "crop"] {
let mut s = session();
let (a, b) = two_rects(&mut s);
for (id, c) in [(a, Color::rgb(0.0, 0.0, 0.0)), (b, Color::rgb(1.0, 0.0, 0.0))] {
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::solid(c), 3.0).into();
Ok(())
})
.unwrap();
}
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let r = ids(&s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap());
let g = node(&s, r[0]);
let pieces = g.children().unwrap();
assert!(!pieces.is_empty(), "{op}");
assert!(pieces.iter().all(|c| c.appearance.stroke_width() == 0.0 && c.appearance.fill().is_some()), "{op} keeps a stroke");
if op == "merge" {
assert_eq!(pieces.len(), 1, "same fill, different strokes: merged");
}
}
}
#[test]
fn outline_stroke_preserves_tiny_and_signed_area_canceling_closed_fills() {
for points in [vec![[0.0, 0.0], [100.0, 100.0], [0.0, 100.0], [100.0, 0.0]], vec![[0.0, 0.0], [1e-8, 0.0], [1e-8, 1e-8]]] {
let mut s = session();
let anchors: Vec<Value> = points.into_iter().map(|[x, y]| json!({"x":x,"y":y})).collect();
s.execute("path.create", &json!({"anchors":anchors,"closed":true})).unwrap();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, result[0]);
let retains_fill = n.children().is_some_and(|ch| ch.iter().any(|c| c.appearance.fill_paint() == Paint::solid(Color::WHITE)))
|| n.appearance.fill_paint() == Paint::solid(Color::WHITE);
assert!(retains_fill, "a real fill survives independently of its signed area or scale");
}
}
#[test]
fn outline_stroke_preserves_bent_open_fill_and_history() {
let mut s = session();
s.execute("path.create", &json!({"anchors":[{"x":0,"y":0},{"x":60,"y":0},{"x":75,"y":-15},{"x":110,"y":-15}],"closed":false})).unwrap();
let before = s.doc().unwrap().doc.clone();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, result[0]);
let children = n.children().expect("original fill beside the outlined stroke");
assert_eq!(children.len(), 2);
let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap();
assert!(!fill.path_data().unwrap().subpaths[0].closed);
assert!(children.iter().all(|n| n.appearance.stroke().is_none()));
let after = s.doc().unwrap().doc.layers.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, after);
}
#[test]
fn outline_stroke_mixed_contours_preserve_all_fill() {
use vectorcraft_geom::{Anchor, Point, SubPath};
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.edit("mixed contours", |d, _| {
let n = d.node_mut(id).unwrap();
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(SubPath::new(
vec![Anchor::corner(Point::new(50.0, 0.0)), Anchor::corner(Point::new(80.0, 0.0)), Anchor::corner(Point::new(80.0, 20.0))],
false,
));
}
Ok(())
})
.unwrap();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let outlined = node(&s, result[0]);
let children = outlined.children().unwrap();
let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap();
let NodeKind::Path { path, .. } = &fill.kind else { panic!("fill is a path") };
assert_eq!(path.subpaths.len(), 2);
assert!(path.subpaths[0].closed);
assert!(!path.subpaths[1].closed);
}
#[test]
fn outline_stroke_keeps_closed_compound_members_editable() {
check_outlined_compound_members(false);
}
#[test]
fn outline_stroke_keeps_open_compound_contours_and_members() {
check_outlined_compound_members(true);
}
fn check_outlined_compound_members(mixed: bool) {
use vectorcraft_geom::{Anchor, Point, SubPath};
let mut s = session();
let outer = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
let inner = rect(&mut s, 35.0, 35.0, 30.0, 30.0);
let mut members = vec![outer.0, inner.0];
if mixed {
let open = s.execute("path.create", &json!({"anchors":[{"x":140,"y":10},{"x":170,"y":30},{"x":140,"y":50}]})).unwrap();
members.push(open["id"].as_u64().unwrap());
s.edit("Mixed compound member", |d, _| {
let NodeKind::Path { path, .. } = &mut d.node_mut(inner).unwrap().kind else { panic!("path") };
path.subpaths.push(SubPath::new(vec![Anchor::corner(Point::new(45.0, 80.0)), Anchor::corner(Point::new(70.0, 90.0))], false));
Ok(())
})
.unwrap();
}
s.execute("select.set", &json!({"ids":members})).unwrap();
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Compound member names and rule", |d, _| {
d.node_mut(outer).unwrap().name = Some("outer-member".into());
d.node_mut(inner).unwrap().name = Some("inner-member".into());
let NodeKind::Compound { rule, .. } = &mut d.node_mut(compound).unwrap().kind else { panic!("compound") };
*rule = FillRule::EvenOdd;
Ok(())
})
.unwrap();
let original = node(&s, compound);
let expected: Vec<_> = original
.children()
.unwrap()
.iter()
.map(|child| {
let path = child.path_data().unwrap().clone();
(child.name.clone(), path)
})
.collect();
let before = s.doc().unwrap().doc.layers.clone();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0];
let group = node(&s, result);
let fill = group.children().unwrap().iter().find(|child| child.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap();
let NodeKind::Compound { children, rule } = &fill.kind else { panic!("closed fill must retain editable compound members") };
assert_eq!(*rule, FillRule::EvenOdd);
assert_eq!(children.len(), if mixed { 3 } else { 2 });
for (child, (name, path)) in children.iter().zip(expected) {
assert_eq!(child.name, name);
assert_eq!(child.path_data().unwrap(), &path);
assert_ne!(child.id, outer);
assert_ne!(child.id, inner);
}
let member = children[0].id;
let sibling = children[1].id;
let member_bounds = children[0].geometric_bounds().unwrap();
let sibling_before = children[1].clone();
let after = s.doc().unwrap().doc.layers.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, after);
// Group Selection can still address one retained child without moving its sibling.
s.execute("select.set", &json!({"ids":[member.0]})).unwrap();
s.execute("object.move", &json!({"dx":7,"dy":3})).unwrap();
assert!(close(
node(&s, member).geometric_bounds().unwrap(),
Rect::new(member_bounds.x0 + 7.0, member_bounds.y0 + 3.0, member_bounds.x1 + 7.0, member_bounds.y1 + 3.0),
1e-6
));
assert_eq!(node(&s, sibling), *sibling_before);
}
/// Exercise the real Group Selection pointer route, not select.set by id.
#[test]
fn outline_fill_and_stroke_move_independently_with_group_selection() {
use vectorcraft_tools::{PointerEvent, PointerKind};
for closed in [true, false] {
for move_fill in [false, true] {
for click_first in [false, true] {
let mut s = session();
s.execute(
"path.create",
&json!({"anchors":[{"x":100,"y":100},{"x":200,"y":100},{"x":200,"y":200},{"x":100,"y":200}],"closed":closed}),
)
.unwrap();
s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"color":"#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight":10})).unwrap();
let root = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0];
let group = node(&s, root);
let children = group.children().expect("fill and outlined stroke stay separate");
assert_eq!(children.len(), 2);
let fill = children.iter().find(|c| c.appearance.fill_paint().color().is_some_and(|c| c.to_hex() == "#ff0000")).unwrap().id;
let stroke = children.iter().find(|c| c.id != fill).unwrap().id;
group.walk(&mut |n| assert!(n.appearance.stroke().is_none(), "no retained live stroke"));
let moved = if move_fill { fill } else { stroke };
let other = if move_fill { stroke } else { fill };
let other_before = node(&s, other);
let bounds_before = bounds(&s, moved);
let layers_before_move = s.doc().unwrap().doc.layers.clone();
let v = ViewInfo { smart_guides: false, snap_to_point: false, ..ViewInfo::default() };
s.select_tool("groupSelection", v).unwrap();
// Start empty, as clicking the art with Group Selection does after deselection.
s.execute("select.none", &json!({})).unwrap();
let (x, y) = if move_fill { (150.0, 150.0) } else { (150.0, 100.0) };
let compound_stroke = !move_fill && matches!(node(&s, stroke).kind, NodeKind::Compound { .. });
for _ in 0..if compound_stroke {
2
} else if click_first {
1
} else {
0
} {
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
}
for (kind, x, y) in [(PointerKind::Down, x, y), (PointerKind::Drag, x + 30.0, y + 15.0), (PointerKind::Up, x + 30.0, y + 15.0)] {
s.pointer(&PointerEvent::new(kind, x, y), v).unwrap();
}
assert_eq!(node(&s, other), other_before, "sibling unchanged: closed={closed}, fill={move_fill}, click_first={click_first}");
let b = bounds(&s, moved);
assert!(
close(b, Rect::new(bounds_before.x0 + 30.0, bounds_before.y0 + 15.0, bounds_before.x1 + 30.0, bounds_before.y1 + 15.0), 1e-6),
"moved leaf: {b:?}"
);
let layers_after_move = s.doc().unwrap().doc.layers.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, layers_before_move);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, layers_after_move);
}
}
}
}
/// #1590: an inset larger than the shape leaves nothing, and the error says so rather than asking
/// for paths that are selected.
#[test]
fn offset_path_that_leaves_nothing_says_so() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let e = s.execute("object.path.offsetPath", &json!({"offset": -20})).unwrap_err().to_string();
assert!(e.contains("leaves nothing") && !e.contains("select paths"), "{e}");
}
/// COLR glyphs become groups of their layers: real paths with their colours and gradients, the
/// composite's blend mode kept, every node with an id of the document's.
#[test]
fn create_outlines_turns_colr_glyphs_into_layer_groups() {
let _fonts = crate::adding_fonts();
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font};
vectorcraft_text::FontDb::global().add_font(colr_font(true).unwrap());
let mut s = session();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": format!("{COLOUR_CHAR}F"), "size": 32, "font": colr_family(true)})).unwrap();
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
let ch = g.children().unwrap();
assert!(matches!(ch[0].kind, NodeKind::Group { .. }), "the glyph's group: {:?}", ch[0].kind_label());
assert!(matches!(ch[1].kind, NodeKind::Path { .. } | NodeKind::Compound { .. }), "the `F` an outline");
let mut nodes = vec![];
ch[0].walk(&mut |n| nodes.push((n.id, n.blend, n.appearance.fill_paint())));
assert!(nodes.iter().any(|(_, _, p)| matches!(p, vectorcraft_color::Paint::Gradient(_))), "its gradients");
assert!(nodes.iter().any(|(_, b, _)| *b == vectorcraft_color::BlendMode::Multiply), "its multiply");
let d = &s.doc().unwrap().doc;
let mut seen = std::collections::HashSet::new();
assert!(nodes.iter().all(|(id, ..)| d.node(*id).is_some() && seen.insert(*id)), "ids of the document's, each once");
}
/// Pathfinder panel › Pathfinder Options: `object.pathfinder.options` reads and sets the options
/// (kept in the preferences as the `pathfinder` group) and refuses values out of range or of the
/// wrong type, changing nothing.
#[test]
fn pathfinder_options_round_trip_and_refuse_bad_values() {
let mut s = session();
let defaults = json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false});
assert_eq!(s.execute("object.pathfinder.options", &json!({})).unwrap(), defaults);
let set = json!({"precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true});
assert_eq!(s.execute("object.pathfinder.options", &set).unwrap(), set);
assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set);
let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap();
assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}");
for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] {
let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap();
assert_eq!(r["precision"], json!(want), "{given}");
}
s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap();
for bad in [
json!({"precision": 0}),
json!({"precision": 11}),
json!({"precision": "x"}),
json!({"precision": "1abc"}),
json!({"precision": "0.5 extra"}),
json!({"precision": -1}),
json!({"removeRedundantPoints": "yes"}),
json!({"removeUnpainted": 1}),
json!({"tolerance": 1}),
] {
assert!(s.execute("object.pathfinder.options", &bad).is_err(), "{bad}");
assert!(s.execute("prefs.set", &json!({"key": "pathfinder", "value": bad})).is_err(), "prefs.set {bad}");
assert_eq!(s.execute("object.pathfinder.options", &json!({})).unwrap(), set, "{bad} changes nothing");
}
s.execute("prefs.set", &json!({"key": "pathfinder", "value": {"removeUnpainted": false}})).unwrap();
assert!(!s.prefs.pathfinder.remove_unpainted);
assert!(s.prefs.pathfinder.remove_redundant_points, "a partial object keeps the rest");
s.execute("prefs.reset", &json!({})).unwrap();
assert_eq!(s.execute("object.pathfinder.options", &json!({})).unwrap(), defaults);
}
/// A filled square and, crossing it, a rectangle with no fill, selected.
fn filled_and_unfilled(s: &mut Session) {
let a = rect(s, 0.0, 0.0, 100.0, 100.0);
let b = rect(s, 50.0, 25.0, 100.0, 50.0);
set_fill(s, a, Color::rgb(1.0, 0.0, 0.0));
s.edit("t", |d, _| {
d.node_mut(b).unwrap().appearance.set_fill(Paint::None);
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
}
/// The fill of each piece of the group `op` makes from [`filled_and_unfilled`], and of each
/// piece's stroke.
fn pieces(s: &mut Session, op: &str) -> Vec<(Paint, Paint)> {
let r = ids(&s.execute(op, &json!({})).unwrap());
node(s, r[0]).children().unwrap().iter().map(|c| (c.appearance.fill_paint(), c.appearance.stroke_paint())).collect()
}
/// Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: off, Divide and Outline
/// keep the pieces of an object with no fill; on, they leave them out.
#[test]
fn divide_and_outline_remove_unpainted_artwork_when_asked() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
for on in [false, true] {
let mut s = session();
s.execute("object.pathfinder.options", &json!({"removeUnpainted": on})).unwrap();
filled_and_unfilled(&mut s);
let divided = pieces(&mut s, "object.pathfinder.divide");
let unfilled = divided.iter().filter(|(fill, _)| fill.is_none()).count();
// The overlap takes the paint of the rectangle in front, so it has no fill either.
assert_eq!(unfilled, if on { 0 } else { 2 }, "Divide, option {on}: {divided:?}");
assert_eq!(divided.len() - unfilled, 1, "the square's piece stays");
s.execute("edit.undo", &json!({})).unwrap();
let outlined = pieces(&mut s, "object.pathfinder.outline");
let from_unfilled = outlined.iter().filter(|(_, stroke)| *stroke != red).count();
assert_eq!(from_unfilled > 0, !on, "Outline, option {on}: {outlined:?}");
assert!(outlined.iter().any(|(_, stroke)| *stroke == red), "the square's edges stay");
}
}
/// Pathfinder Options › Remove Redundant Points: Unite of a square with an anchor in the middle of
/// its top edge and a square inside it keeps the extra anchor unless the option is on.
#[test]
fn remove_redundant_points_drops_anchors_that_shape_nothing() {
for on in [false, true] {
let mut s = session();
s.execute("object.pathfinder.options", &json!({"removeRedundantPoints": on})).unwrap();
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<Value> = 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 r = ids(&s.execute("object.pathfinder.unite", &json!({})).unwrap());
let anchors = path_of(&s, r[0]).0.anchor_count();
if on {
assert_eq!(anchors, 4, "option on");
} else {
assert!(anchors > 4, "option off keeps the anchor: {anchors}");
}
assert!((area_of(&s, r[0]) - 10_000.0).abs() < 1e-6);
}
}
/// Pathfinder Options › Precision: Divide drops a 0.5 pt overlap at a precision of 1 pt and keeps
/// it at the default.
#[test]
fn precision_decides_whether_a_thin_overlap_is_a_piece() {
for (precision, faces) in [(None, 3), (Some(1.0), 2)] {
let mut s = session();
if let Some(p) = precision {
s.execute("object.pathfinder.options", &json!({"precision": p})).unwrap();
}
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();
let r = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap());
assert_eq!(node(&s, r[0]).children().unwrap().len(), faces, "precision {precision:?}");
}
}
/// A hidden fill paints nothing: with Divide and Outline Will Remove Unpainted Artwork on, the
/// pieces of an object whose only fill is hidden go too.
#[test]
fn remove_unpainted_counts_a_hidden_fill_as_unpainted() {
let mut s = session();
s.execute("object.pathfinder.options", &json!({"removeUnpainted": true})).unwrap();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 25.0, 100.0, 50.0);
set_fill(&mut s, a, Color::rgb(1.0, 0.0, 0.0));
set_fill(&mut s, b, Color::rgb(0.0, 0.0, 1.0));
s.edit("t", |d, _| {
d.node_mut(b).unwrap().appearance.fill_mut().unwrap().visible = false;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let divided = pieces(&mut s, "object.pathfinder.divide");
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
assert_eq!(divided.len(), 1, "only the red square's piece: {divided:?}");
assert_eq!(divided[0].0, red);
}
/// Shape Modes unite a group selected with other objects first: at a fine precision a group
/// member thinner than the default precision (0.005 pt) is kept there too.
#[test]
fn a_thin_group_member_survives_the_group_union_at_a_fine_precision() {
for (precision, subpaths) in [(None, 2), (Some(0.001), 3)] {
let mut s = session();
if let Some(p) = precision {
s.execute("object.pathfinder.options", &json!({"precision": p})).unwrap();
}
let (a, thin) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 0.0, 100.0, 100.0, 0.005));
s.execute("select.set", &json!({"ids": [a.0, thin.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let other = rect(&mut s, 200.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [g, other.0]})).unwrap();
let r = ids(&s.execute("object.pathfinder.unite", &json!({})).unwrap());
assert_eq!(path_of(&s, r[0]).0.subpaths.len(), subpaths, "precision {precision:?}");
}
}
/// A Pathfinder operation records the options it used in its journal entry, so replaying the
/// journal with other preferences gives the same art.
#[test]
fn pathfinder_journal_entries_replay_with_the_options_they_used() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 99.5, "width": 100, "height": 50})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.prefs.pathfinder = PathfinderOptions { precision: 1.0, remove_redundant_points: true, remove_unpainted: true };
let r = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap());
assert_eq!(node(&s, r[0]).children().unwrap().len(), 1, "the thin overlap and the unfilled piece go");
let (id, p) = s.journal.last().unwrap().clone();
assert_eq!(id, "object.pathfinder.divide");
assert_eq!((&p["precision"], &p["removeRedundantPoints"], &p["removeUnpainted"]), (&json!(1.0), &json!(true), &json!(true)));
let mut replay = Session::new();
for (id, p) in &s.journal {
replay.execute(id, p).unwrap();
}
assert_eq!(replay.prefs.pathfinder, PathfinderOptions::default());
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
assert_eq!(doc(&replay), doc(&s));
// Options given as params are checked as object.pathfinder.options checks them.
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<vectorcraft_doc::Node>) {
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<vectorcraft_doc::Node> {
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 Pathfinder effect given some of its options in `params` journals every option it used, so
/// replaying the journal with other preferences gives the same effect and art.
#[test]
fn a_pathfinder_effect_given_some_options_journals_every_option_it_used() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 99.5, "width": 100, "height": 50})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.prefs.pathfinder = PathfinderOptions { precision: 1.0, remove_redundant_points: true, remove_unpainted: true };
s.execute("effect.apply", &json!({"effect": "pathfinder.divide", "params": {"precision": 0.25}})).unwrap();
let all = json!({"precision": 0.25, "removeRedundantPoints": true, "removeUnpainted": true});
assert_eq!(first_effect_params(&s), all);
let (id, p) = s.journal.last().unwrap().clone();
assert_eq!((id.as_str(), &p["params"]), ("effect.apply", &all), "the journal entry gives every option the effect used");
let mut replay = Session::new();
for (id, p) in &s.journal {
replay.execute(id, p).unwrap();
}
assert_eq!(replay.prefs.pathfinder, PathfinderOptions::default());
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
assert_eq!(doc(&replay), doc(&s));
}
/// 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<Value> = 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);
}
/// Soft Mix's Mixing Rate is compared by value: 50 over a stored 50.0 records no undo step, and 51
/// is an edit.
#[test]
fn a_soft_mix_rate_set_to_its_value_records_no_step() {
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.softMix", "params": {"mixingRate": 50.0}})).unwrap();
assert_eq!(first_effect_params(&s)["mixingRate"], json!(50.0));
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 50}})).unwrap(), json!({"ids": []}));
assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(50.0), before), "50 over 50.0: no step");
assert_ne!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 51}})).unwrap(), json!({"ids": []}));
assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(51), before + 1), "51 is an edit");
}
/// A single group containing multiple overlapping paths is accepted by Crop.
#[test]
fn crop_operates_on_a_single_selected_group_of_paths() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 50.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
assert_eq!(s.doc().unwrap().selection.len(), 1);
let out = s.execute("object.pathfinder.crop", &json!({})).unwrap();
let cropped_ids = ids(&out);
assert!(!cropped_ids.is_empty());
}