Merge main into feat/recolor-edit-base-color-menus

This commit is contained in:
dotCooCoo committed 2026-11-18 13:10:37 -08:00
commit f34f9e7bb8
292 files changed
+33860 -1444

No files matched your search

@@ -176,3 +176,61 @@ fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() {
.unwrap();
assert_eq!(undo_steps(&s), 1);
}
/// `path.setHandle` with `link` makes a corner smooth: the other handle turns in line at its own
/// length, a retracted one is pulled out to the moved handle's length where a segment leaves the
/// anchor on its side and stays retracted at an open end. A handle already in place on a corner
/// still links; a request that changes nothing records no undo step; `link` that is not a boolean
/// or goes with `independent` is refused.
#[test]
fn a_linked_handle_makes_the_anchor_smooth() {
let (mut s, id) = long_path(100);
let p = anchor(&s, id, 5).p;
let corner = Anchor { p, h_in: p + Vec2::new(-6.0, 8.0), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner };
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
path.subpaths[0].anchors[5] = corner;
let link = |x: f64, y: f64, ai: usize| json!({"id": id.0, "anchor": ai, "which": "out", "x": x, "y": y, "link": true});
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
// The out handle stays where it is; the corner becomes smooth, the in handle turned opposite it.
s.execute("path.setHandle", &link(corner.h_out.x, corner.h_out.y, 5)).unwrap();
assert_eq!(undo_steps(&s), 1);
let a = anchor(&s, id, 5);
assert_eq!((a.kind, a.h_out), (AnchorKind::Smooth, corner.h_out));
assert!(near(a.h_in, p + Vec2::new(-10.0, 0.0)), "{a:?}");
// Moved: the in handle keeps its length of 10.
let to = p + Vec2::new(4.0, 3.0);
s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap();
assert_eq!(undo_steps(&s), 2);
let a = anchor(&s, id, 5);
assert!(a.kind == AnchorKind::Smooth && a.h_out == to && near(a.h_in, p + Vec2::new(-8.0, -6.0)), "{a:?}");
// The same request again changes nothing.
s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap();
assert_eq!(undo_steps(&s), 2);
// A retracted in handle on an inner anchor is pulled out; at the open start it stays retracted.
let q = anchor(&s, id, 7).p;
s.execute("path.setHandle", &link(q.x, q.y + 5.0, 7)).unwrap();
let a = anchor(&s, id, 7);
assert!(a.kind == AnchorKind::Smooth && near(a.h_in, q + Vec2::new(0.0, -5.0)), "{a:?}");
let q = anchor(&s, id, 0).p;
s.execute("path.setHandle", &link(q.x, q.y + 5.0, 0)).unwrap();
let a = anchor(&s, id, 0);
assert!(a.kind == AnchorKind::Smooth && a.h_in == q && a.h_out == q + Vec2::new(0.0, 5.0), "{a:?}");
let before = s.doc().unwrap().doc.clone();
let undo = undo_steps(&s);
for bad in [
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": "yes"}),
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}),
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}),
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}),
json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}),
json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}),
json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}),
] {
assert!(s.execute("path.setHandle", &bad).is_err(), "{bad}");
}
assert!(s.doc().unwrap().doc == before, "a refused request changed the document");
assert_eq!(undo_steps(&s), undo);
}
+17
View File
@@ -90,6 +90,23 @@ fn values_that_differ_read_null_and_recent_urls_keep_the_newest_first() {
assert_eq!(info(&mut s, json!({"ids": [p.0, a.0]}))["showCenter"], Value::Null);
}
/// The recent URLs keep the 30 newest distinct URLs, the most the panel's URL menu can list, and
/// a URL given again moves to the front without taking a second place.
#[test]
fn recent_urls_keep_the_thirty_newest() {
let mut s = session();
rect(&mut s, 0.0);
for i in 0..35 {
run(&mut s, "attributes.set", json!({"url": format!("https://example.com/{i}")}));
}
let want: Vec<String> = (5..35).rev().map(|i| format!("https://example.com/{i}")).collect();
assert_eq!(info(&mut s, json!({}))["recentUrls"], json!(want));
run(&mut s, "attributes.set", json!({"url": "https://example.com/20"}));
let urls = info(&mut s, json!({}))["recentUrls"].as_array().unwrap().clone();
assert_eq!((urls.len(), urls[0].as_str(), urls[1].as_str()), (30, Some("https://example.com/20"), Some("https://example.com/34")));
assert_eq!(urls.iter().filter(|u| *u == "https://example.com/20").count(), 1);
}
/// A five-pointed star drawn as one self-intersecting path (its centre is wound twice).
fn star(s: &mut Session) -> NodeId {
let (c, r) = (50.0f64, 45.0f64);
+32
View File
@@ -431,3 +431,35 @@ fn a_spine_segment_bends_with_perpendicular_handles() {
use vectorcraft_geom::kurbo::ParamCurve;
assert!(sp.segment(0).eval(0.5).distance(Point::new(55.0, 45.0)) < 1e-9, "{sp:?}");
}
/// `link` with `handle` makes a spine point smooth, the other handle in line opposite the moved
/// one, without moving the keys; the same request again records no undo step, and `link` that is
/// not a boolean, goes with `independent` or comes without `handle` is refused.
#[test]
fn a_linked_spine_handle_makes_the_point_smooth() {
let mut s = session();
let (_, _, g) = blend(&mut s);
s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap();
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let link = json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true});
s.execute("object.blend.spine.moveAnchor", &link).unwrap();
let a = spec(&s, g).spine.unwrap().subpaths[0].anchors[1];
assert_eq!((a.kind, a.h_out), (vectorcraft_geom::AnchorKind::Smooth, Point::new(75.0, 25.0)));
let (din, dout) = (a.h_in - a.p, a.h_out - a.p);
assert!(din.hypot() > 1e-6 && (din.normalize() + dout.normalize()).hypot() < 1e-9, "{a:?}");
let st = steps(&s, g);
assert_eq!((center(&st[0]), center(&st[2])), (Point::new(5.0, 5.0), Point::new(105.0, 5.0)), "the keys stay put");
let done = undo(&s);
s.execute("object.blend.spine.moveAnchor", &link).unwrap();
assert_eq!(undo(&s), done, "an unchanged spine recorded an undo step");
let before = spec(&s, g);
for bad in [
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}),
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}),
json!({"anchor": 1, "x": 75, "y": 25, "link": true}),
] {
assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}");
}
assert_eq!(spec(&s, g), before);
assert_eq!(undo(&s), done);
}
+81 -1
View File
@@ -117,7 +117,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"game-trails",
"energy-beams",
"dry-media",
"tech-circuit"
"tech-circuit",
"arrows"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
@@ -145,6 +146,12 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
);
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"}));
assert_eq!(
arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
);
assert_eq!((libs[11]["name"].as_str(), libs[11]["count"].as_u64()), (Some("Arrows"), Some(5)));
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
@@ -162,6 +169,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("game-trails", "art"),
("energy-beams", "art"),
("dry-media", "art"),
("arrows", "art"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
@@ -220,6 +228,78 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
}
#[test]
fn arrows_library_lists_renders_and_applies_original_brushes() {
let mut s = session();
let listed = run(&mut s, "brush.libraries", json!({}));
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "arrows").unwrap();
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Arrows"), Some("builtIn"), Some(5)));
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
assert_eq!(
lib.brushes.iter().map(|b| (b.name.as_str(), b.kind.type_id())).collect::<Vec<_>>(),
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
);
for b in &lib.brushes {
for length in [2.0, 200.0] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name);
}
}
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Double Arrow", "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), ["Double Arrow"]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Double Arrow"));
run(&mut s, "edit.undo", json!({}));
assert!(vectorcraft_brush::find(doc(&s), "Double Arrow").is_none());
run(&mut s, "edit.redo", json!({}));
assert_eq!(brush(&s, "Double Arrow"), lib.brushes[2]);
}
#[test]
fn the_chevron_arrows_second_chevron_keeps_its_length_on_a_long_path() {
let s = session();
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
let b = lib.brush("Chevron Arrow").unwrap();
let widths = |length: f64| {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
let children = pieces[0].children().unwrap();
assert_eq!(children.len(), 3, "shaft, head and second chevron");
children[1..].iter().map(|n| n.geometric_bounds().unwrap().width()).collect::<Vec<_>>()
};
let short = widths(100.0);
for (long, short) in widths(400.0).into_iter().zip(short) {
assert!((long - short).abs() < 1e-6, "the heads keep their length: {long} on 400 pt, {short} on 100 pt");
}
}
#[test]
fn dashed_arrow_keeps_separate_dashes_and_survives_library_save() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
let b = lib.brush("Dashed Arrow").unwrap();
let mut curve = line_to(40.0);
curve.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0));
for path in [line_to(2.0), line_to(200.0), curve] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke());
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
}
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &black_stroke());
let children = pieces[0].children().unwrap();
assert_eq!(children.len(), 6, "five separate dashes and one head");
let bounds: Vec<_> = children.iter().map(|n| n.geometric_bounds().unwrap()).collect();
assert!(bounds.windows(2).all(|p| p[0].x1 < p[1].x0), "the dashes and head remain separated");
run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Dashed Arrow"}));
let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Dashed Arrow"]}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::find(&reopened, "Dashed Arrow").unwrap(), *b);
}
/// Original circuit art and repeat tiles survive adding, applying and saving a library.
#[test]
fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
+376
View File
@@ -5027,6 +5027,73 @@ fn live_paint_does_not_count_art_named_like_its_parts() {
}
}
/// A path drawn in an isolated Live Paint group can't be named Face or Edge, the names of the
/// group's faces and edges: `object.setProps` and `layer.setProps` return an error and rename
/// nothing, so Gap Options and a path dragged into the group keep the path. A face keeps its name.
#[test]
fn live_paint_refuses_part_names_for_paths_drawn_in_it() {
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces};
let mut s = session();
let g = live(&mut s);
let face = faces(&node(&s, g))[0].id;
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let a = line_across(&mut s, 50.0);
// Hidden, the path stays in the group as drawn when isolation mode ends.
s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap();
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
for name in [FACE_NAME, EDGE_NAME] {
let calls = [
("object.setProps", json!({"id": a.0, "name": name})),
("layer.setProps", json!({"id": a.0, "name": name})),
("layer.setProps", json!({"ids": [face.0, a.0], "name": name})),
];
for (c, p) in calls {
let err = s.execute(c, &p).unwrap_err().to_string();
assert!(err.contains("give the path another name"), "{c} {p}: {err}");
}
}
assert!(s.doc().unwrap().doc == before.0, "nothing was renamed");
assert_eq!(s.doc().unwrap().history.undo.len(), before.1);
s.execute("layer.setProps", &json!({"id": face.0, "name": FACE_NAME})).unwrap();
s.execute("object.exitIsolation", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the hidden path stays in the group");
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "Gap Options keeps the path");
let b = line_to_right_face(&mut s, 30.0);
s.execute("layer.move", &json!({"ids": [b.0], "target": g.0, "place": "inside"})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path dragged in keeps it");
assert_eq!(faces(&node(&s, g)).len(), 5);
}
/// A path pasted into an isolated Live Paint group under the name of a face or an edge loses the
/// name, so Gap Options keeps it and it joins the group's paths when isolation mode ends.
#[test]
fn live_paint_paste_clears_part_names() {
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces, sources};
for name in [FACE_NAME, EDGE_NAME] {
let mut s = session();
let g = live(&mut s);
let r = rect(&mut s, 20.0, 40.0, 60.0, 20.0);
s.execute("object.setProps", &json!({"id": r.0, "name": name})).unwrap();
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("edit.pasteInPlace", &json!({})).unwrap();
let pasted = s.doc().unwrap().selection.objects.clone();
assert_eq!(pasted.len(), 1);
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(pasted[0]), Some(g), "{name}: the paste goes into the group");
assert_eq!(d.node(pasted[0]).unwrap().name, None, "{name}: the paste loses the name");
assert_eq!(d.node(r).unwrap().name.as_deref(), Some(name), "the path outside keeps its name");
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(g), "{name}: Gap Options keeps the paste");
s.execute("object.exitIsolation", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(sources(&n).unwrap().id), "{name}: the paste joined");
assert!(faces(&n).len() > 3);
}
}
/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group
/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and
/// joins the group with the tile saved.
@@ -5098,6 +5165,315 @@ fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() {
}
}
/// With Live Paint group `inner` made in isolated Live Paint group `outer` and then isolated itself,
/// leaving both levels (`object.exitIsolation`, or `object.isolate` on the layer) adds the path drawn
/// in `inner` to it and then `inner` and the path drawn directly in `outer` to `outer`, one undo step
/// each. Isolating `outer` from `inner` adds only `inner`'s drawn path, and `outer` keeps its own.
#[test]
fn live_paint_isolation_merges_nested_live_paint_groups_it_leaves() {
use vectorcraft_tools::builder::{faces, sources};
for to in ["exit", "layer", "outer"] {
let mut s = session();
let outer = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(outer).unwrap();
s.execute("object.isolate", &json!({"id": outer.0})).unwrap();
let a = line_across(&mut s, 50.0);
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(outer));
let inner = live(&mut s);
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(outer), "the inner group is drawn in the outer one");
s.execute("object.isolate", &json!({"id": inner.0})).unwrap();
let b = line_across(&mut s, 30.0);
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(inner));
let steps = s.doc().unwrap().history.undo.len();
match to {
"exit" => s.execute("object.exitIsolation", &json!({})).unwrap(),
"layer" => s.execute("object.isolate", &json!({"id": layer.0})).unwrap(),
_ => s.execute("object.isolate", &json!({"id": outer.0})).unwrap(),
};
let d = &s.doc().unwrap().doc;
if to == "outer" {
assert_eq!(s.doc().unwrap().isolation, Some(outer));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the inner group's path joins");
let n = node(&s, inner);
assert_eq!(d.parent_of(b), Some(sources(&n).unwrap().id), "the path drawn in the inner group joined it");
assert_eq!(d.parent_of(inner), Some(outer), "the inner group stays drawn in the outer one");
assert_eq!(d.parent_of(a), Some(outer), "the path drawn in the outer group stays as drawn");
continue;
}
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{to}: one undo step for each group");
assert!(d.node(inner).is_none(), "{to}: the inner group joined the outer one");
let n = node(&s, outer);
let src = sources(&n).unwrap().id;
assert_eq!(d.parent_of(a), Some(src), "{to}: the path drawn in the outer group joined it");
assert!(d.ancestry(b).unwrap().contains(&src), "{to}: the path drawn in the inner group is among the outer group's paths");
assert!(n.children().unwrap().iter().all(|c| c.id == src || c.path_data().is_some()), "{to}: only parts are left in the outer group");
assert!(faces(&n).len() > 3, "{to}: the added paths cut the outer group's faces");
if to == "exit" {
assert_eq!(s.doc().unwrap().selection.objects, vec![outer]);
}
}
}
/// A line from left of the [`live`] group to its right face, so it cuts the two faces left of it.
fn line_to_right_face(s: &mut Session, y: f64) -> NodeId {
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
fn undo_label(s: &Session) -> Option<String> {
s.doc().unwrap().history.undo.last().map(|e| e.label.clone())
}
/// Paths dragged into a Live Paint group in the Layers panel join its paths as Live Paint › Merge
/// adds them: they go among its sources and cut the faces they cross, a painted face they do not
/// cross keeps its fill, and the drop is one "Merge Live Paint" undo step that selects the group.
#[test]
fn layers_drag_adds_paths_to_a_live_paint_group() {
use vectorcraft_tools::builder::{face_at, faces, sources};
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap();
let layer = s.doc().unwrap().doc.parent_of(g);
let (a, b) = (line_to_right_face(&mut s, 30.0), line_to_right_face(&mut s, 70.0));
assert_eq!(s.doc().unwrap().doc.parent_of(a), layer);
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute("layer.move", &json!({"ids": [a.0, b.0], "target": g.0, "place": "inside"})).unwrap();
assert_eq!(r["ids"], json!([g.0]), "the rows that joined are listed as the group");
let d = s.doc().unwrap();
assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step");
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"));
assert_eq!(s.doc().unwrap().selection.objects, vec![g]);
let n = node(&s, g);
let src = sources(&n).unwrap();
assert_eq!(src.children().unwrap().len(), 4);
for id in [a, b] {
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources");
}
assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three");
assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 3);
for id in [a, b] {
assert_eq!(s.doc().unwrap().doc.parent_of(id), layer, "Undo puts {id} back where it was");
}
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 7);
}
/// A path named like a Live Paint group's sources group joins the group when it is dragged in, in
/// front of the sources group or behind it: the group keeps its own sources group and the path
/// goes among its paths.
#[test]
fn layers_drag_of_a_path_named_like_the_sources_group_joins_a_live_paint_group() {
use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources};
for index in [0, 99] {
let mut s = session();
let g = live(&mut s);
let a = line_to_right_face(&mut s, 30.0);
s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap();
s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": index})).unwrap();
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"), "index {index}");
let n = node(&s, g);
let src = sources(&n).unwrap();
assert!(src.children().is_some(), "index {index}: the sources group is a group");
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(src.id), "index {index}: the path joined the sources");
assert_eq!(faces(&n).len(), 5, "index {index}");
}
}
/// An object drawn in a Live Paint group and named like its sources group can be moved ahead of the
/// sources group: the group keeps its own sources group and stays a Live Paint group.
#[test]
fn layers_reorder_of_an_object_named_like_the_sources_group_keeps_the_live_paint_group() {
use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint, sources};
let mut s = session();
let g = live(&mut s);
let real = sources(&node(&s, g)).unwrap().id;
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let a = line_across(&mut s, 50.0);
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap();
s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 0})).unwrap();
let n = node(&s, g);
assert!(is_live_paint(&n));
assert_eq!(sources(&n).unwrap().id, real);
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the object stays where it was drawn");
}
/// A path named `Face` that is dragged into a Live Paint group is not one of its faces: the face it
/// covers keeps its own fill.
#[test]
fn layers_drag_of_a_path_named_face_does_not_repaint_the_group() {
use vectorcraft_tools::builder::{face_at, faces};
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap();
let a = rect(&mut s, 0.0, 0.0, 50.0, 100.0);
set_fill(&mut s, a, Color::rgb(0.0, 0.0, 1.0));
s.execute("object.setProps", &json!({"id": a.0, "name": "Face"})).unwrap();
s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 99})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 3);
assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green);
}
/// An Alt-drag into a Live Paint group adds a copy and leaves the path where it was; a drop above
/// one of the group's faces, and `node.move` into the group, add the path the same way.
#[test]
fn layers_drag_copy_and_drop_beside_a_part_add_to_a_live_paint_group() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(g);
let a = line_to_right_face(&mut s, 30.0);
s.execute("layer.move", &json!({"ids": [a.0], "target": g.0, "copy": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), layer, "the path itself stays");
let n = node(&s, g);
assert_eq!(faces(&n).len(), 5);
let src = sources(&n).unwrap().children().unwrap().clone();
assert_eq!(src.len(), 3);
assert!(src.iter().all(|c| c.id != a), "a copy joined");
let (face, other_face) = (faces(&n)[0].id, faces(&n)[1].id);
let b = line_to_right_face(&mut s, 70.0);
// A face dragged along is made again with the others, so only the group is listed.
let r = s.execute("layer.move", &json!({"ids": [b.0, other_face.0], "target": face.0, "place": "above"})).unwrap();
assert_eq!(r["ids"], json!([g.0]));
assert_eq!(s.doc().unwrap().layer_rows, vec![g]);
let n = node(&s, g);
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(sources(&n).unwrap().id), "a drop beside a face joins");
assert_eq!(faces(&n).len(), 7);
let c = line_to_right_face(&mut s, 50.0);
s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 0})).unwrap();
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"));
let n = node(&s, g);
assert_eq!(s.doc().unwrap().doc.parent_of(c), Some(sources(&n).unwrap().id), "node.move into the group joins");
assert_eq!(faces(&n).len(), 9);
}
/// Dragging type, or type with a path, into a Live Paint group is refused with Make's message and
/// moves nothing, as Merge refuses it; a drop beside the group is an ordinary move.
#[test]
fn layers_drag_refuses_type_into_a_live_paint_group() {
use vectorcraft_tools::builder::faces;
let mut s = session();
let g = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(g);
let a = line_to_right_face(&mut s, 30.0);
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
for p in [json!({"ids": [a.0, text.0], "target": g.0}), json!({"ids": [text.0], "target": g.0, "copy": true})] {
let err = s.execute("layer.move", &p).unwrap_err().to_string();
assert!(err.contains("Live Paint takes paths and compound paths"), "{err}");
}
assert!(s.execute("node.move", &json!({"id": text.0, "parent": g.0, "index": 0})).is_err());
assert!(s.doc().unwrap().doc == before.0, "nothing moved");
assert_eq!(s.doc().unwrap().history.undo.len(), before.1);
s.execute("layer.move", &json!({"ids": [a.0, text.0], "target": g.0, "place": "above"})).unwrap();
assert_eq!(undo_label(&s).as_deref(), Some("Move Rows"));
assert_eq!(s.doc().unwrap().doc.parent_of(text), layer);
assert_eq!(faces(&node(&s, g)).len(), 3);
}
/// A path dragged out of a Live Paint group's sources leaves its faces and edges: the group makes
/// them again from the paths left, and with none left it has no faces until a path joins it again.
/// Reordering the sources, or the group's own faces, makes nothing again.
#[test]
fn layers_drag_out_of_a_live_paint_group_makes_its_faces_again() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
let n = node(&s, g);
let src: Vec<NodeId> = sources(&n).unwrap().children().unwrap().iter().map(|c| c.id).collect();
let face_ids: Vec<NodeId> = faces(&n).iter().map(|f| f.id).collect();
s.execute("layer.move", &json!({"ids": [src[0].0], "target": src[1].0, "place": "above"})).unwrap();
s.execute("layer.move", &json!({"ids": [face_ids[0].0], "target": face_ids[2].0, "place": "above"})).unwrap();
let n = node(&s, g);
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2, "a reorder keeps the sources");
let mut now: Vec<NodeId> = faces(&n).iter().map(|f| f.id).collect();
now.sort();
let mut was = face_ids.clone();
was.sort();
assert_eq!(now, was, "and the faces");
s.execute("layer.move", &json!({"ids": [src[0].0], "target": layer.0})).unwrap();
assert_eq!(undo_label(&s).as_deref(), Some("Move Rows"));
let n = node(&s, g);
assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(layer));
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 1);
assert_eq!(faces(&n).len(), 1, "one rectangle left");
s.execute("node.move", &json!({"id": src[1].0, "parent": layer.0, "index": 0})).unwrap();
let n = node(&s, g);
assert!(vectorcraft_tools::builder::is_live_paint(&n), "the group stays a Live Paint group");
assert!(sources(&n).unwrap().children().unwrap().is_empty());
assert!(faces(&n).is_empty() && vectorcraft_tools::builder::edges(&n).is_empty());
s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 1, "a path joins the empty group");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 1);
}
/// A path dragged from a Live Paint group's sources into the group itself stays among its paths,
/// and the faces it bounds keep their paint, also when it is the group's only path.
#[test]
fn layers_drag_a_source_path_into_its_own_live_paint_group_keeps_the_paint() {
use vectorcraft_tools::builder::{face_at, faces, sources};
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
let mut s = session();
let g = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap();
let src: Vec<NodeId> = sources(&node(&s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect();
s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap();
let n = node(&s, g);
assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(sources(&n).unwrap().id), "the path stays among the group's paths");
assert_eq!(faces(&n).len(), 3);
assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face it bounds keeps its fill");
s.execute("layer.move", &json!({"ids": [src[1].0], "target": layer.0})).unwrap();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [50, 50], "color": "#0000ff"})).unwrap();
s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 1);
assert_eq!(face_at(&n, Point::new(50.0, 50.0)).unwrap().appearance.fill_paint(), blue, "the only path's face keeps its fill");
}
/// A Live Paint group among another Live Paint group's paths gives it faces and edges: a path
/// dragged into or out of the inner group's paths, or from the outer group's paths into the inner
/// group's, makes the inner group's faces and edges again and then the outer group's.
#[test]
fn layers_drag_into_a_nested_live_paint_group_makes_the_outer_group_again() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let outer = live(&mut s);
let inner = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(outer).unwrap();
let first_source = |s: &Session, g: NodeId| sources(&node(s, g)).unwrap().children().unwrap()[0].id;
let into = |s: &mut Session, row: NodeId, g: NodeId| {
let target = first_source(s, g);
s.execute("layer.move", &json!({"ids": [row.0], "target": target.0, "place": "above"})).unwrap();
};
into(&mut s, inner, outer);
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources(&node(&s, outer)).unwrap().id));
let plain = faces(&node(&s, outer)).len();
let a = line_to_right_face(&mut s, 30.0);
into(&mut s, a, inner);
assert_eq!(faces(&node(&s, inner)).len(), 5);
let cut = faces(&node(&s, outer)).len();
assert!(cut > plain, "a path joining the inner group cuts the outer group's faces: {cut} faces, {plain} before");
s.execute("layer.move", &json!({"ids": [a.0], "target": layer.0})).unwrap();
assert_eq!(faces(&node(&s, inner)).len(), 3);
assert_eq!(faces(&node(&s, outer)).len(), plain, "a path leaving the inner group leaves the outer group's faces");
into(&mut s, a, outer);
assert_eq!(faces(&node(&s, outer)).len(), cut);
into(&mut s, a, inner);
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, inner)).unwrap().id));
assert_eq!(faces(&node(&s, inner)).len(), 5);
assert_eq!(faces(&node(&s, outer)).len(), cut, "the outer group is made after the inner one");
}
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
/// graphic style link, and return it as it then is.
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
+105
View File
@@ -696,3 +696,108 @@ fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() {
assert!(selected(&s).is_empty(), "{prop}: nor by a marquee");
}
}
/// A straight line, closed as a compound shape closes open paths, encloses no area, so it
/// contributes no area to the shape: Make Compound Shape still makes it, in any mode and at any
/// place in the stack, and its reply carries a warning that names Outline Stroke. The shape draws
/// the area the other members make in that mode: the square alone in Add, or on top in Subtract,
/// and nothing in Intersect or when the line is the backmost member in Subtract. A line in a group,
/// beside a closed path too, an open evenodd square traced twice, and open evenodd subpaths that cancel one another or a closed
/// subpath of the same path are the same. An open path that encloses an area once closed (a bow tie
/// whose lobes cancel in signed area included) and closed shapes alone give no warning (#7849).
#[test]
fn lines_that_add_no_area_are_reported() {
use crate::cmd::OPEN_PATHS_ADD_NO_AREA;
fn line_of(s: &mut Session) -> NodeId {
NodeId(run(s, "shape.line", json!({"x1": 20, "y1": 50, "x2": 180, "y2": 50}))["id"].as_u64().unwrap())
}
fn vee_of(s: &mut Session) -> NodeId {
let anchors = json!([{"x": 20, "y": 50}, {"x": 100, "y": 150}, {"x": 180, "y": 50}]);
NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap())
}
fn bow_tie_of(s: &mut Session) -> NodeId {
let anchors = json!([{"x": 20, "y": 0}, {"x": 180, "y": 100}, {"x": 180, "y": 0}, {"x": 20, "y": 100}]);
NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().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 = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap());
run(s, "path.setFillRule", json!({"rule": "evenOdd"}));
id
}
fn evenodd_of(s: &mut Session, d: &str) -> NodeId {
let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap());
run(s, "path.setFillRule", json!({"rule": "evenOdd"}));
id
}
fn two_open_squares_of(s: &mut Session) -> NodeId {
evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 M20 20 L80 20 L80 80 L20 80")
}
fn open_over_closed_of(s: &mut Session) -> NodeId {
evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 Z M20 20 L80 20 L80 80 L20 80")
}
fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId {
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap())
}
type Build = fn(&mut Session) -> NodeId;
// (case, mode, the other member, 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; 13] = [
("an open evenodd square traced twice", "add", twice_around_of, false, true, Some(10_000.0)),
("two open evenodd squares on one another", "add", two_open_squares_of, false, true, Some(10_000.0)),
("an open evenodd square on the same closed square", "add", open_over_closed_of, false, true, Some(10_000.0)),
("a line", "add", line_of, false, true, Some(10_000.0)),
("a line, subtracting", "subtract", line_of, false, true, Some(10_000.0)),
("a line, intersecting", "intersect", line_of, false, true, Some(0.0)),
("a line behind, subtracting", "subtract", line_of, true, true, Some(0.0)),
(
"a group of lines",
"add",
|s| {
let ids = [line_of(s), line_of(s)];
group_of(s, &ids)
},
false,
true,
Some(10_000.0),
),
(
"a group of a line and a square",
"add",
|s| {
let ids = [line_of(s), square(s, 200.0, "#00ff00")];
group_of(s, &ids)
},
false,
true,
Some(20_000.0),
),
("an open path that encloses an area", "add", vee_of, false, false, None),
("an open bow tie, whose signed area is zero", "add", bow_tie_of, false, false, None),
("a square", "add", |s| square(s, 50.0, "#0000ff"), false, false, Some(15_000.0)),
("a square, subtracting", "subtract", |s| square(s, 50.0, "#0000ff"), false, false, Some(5_000.0)),
];
for (what, mode, build, behind, warned, want) in cases {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
let (back, front) = if behind {
let other = build(&mut s);
(other, square(&mut s, 0.0, "#ff0000"))
} else {
let sq = square(&mut s, 0.0, "#ff0000");
(sq, build(&mut s))
};
run(&mut s, "select.set", json!({"ids": [back.0, front.0]}));
let r = run(&mut s, "object.compoundShape.make", json!({ "mode": mode }));
let id = NodeId(r["id"].as_u64().unwrap_or_else(|| panic!("{what}: {r}")));
assert_eq!(node(&s, id).children().unwrap().len(), 2, "{what}: both are members");
assert_eq!(r.get("warning").and_then(Value::as_str), warned.then_some(OPEN_PATHS_ADD_NO_AREA), "{what}: {r}");
if let Some(want) = want {
let d = &s.doc().unwrap().doc;
let hook = |c: &Node| effects::outline_object(Some(d), c);
let got = effects::compound_shape_area(None, &node(&s, id), Some(&hook)).map_or(0.0, |p| area(&p));
assert!((got - want).abs() < 0.5, "{what}: draws {got}, not {want}");
}
}
}
@@ -377,7 +377,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse
("addon.color.filter", "ids", json!({"effect": "addon.color.invert"}), Selected),
("addon.color.applyNearestSwatch", "ids", json!({}), Selected),
("edit.colors.overprintBlack", "ids", json!({}), Selected),
("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1}))),
("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1, "replaced": 1}))),
("layer.highlight", "ids", json!({}), Fails("missing ids")),
("layer.move", "ids", json!({ "target": d }), Fails("missing ids")),
("library.add", "ids", json!({"kind": "graphic"}), Selected),
+214
View File
@@ -167,6 +167,183 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() {
assert_eq!(document_rows(&s), vec![g.0, c.0], "document.inspect lists the rows");
}
/// Run `layer.highlight` with `ids` and `mode` → (the rows it returned, the current layer), after
/// checking that the call counted one revision and left the rows it returned highlighted.
fn highlight_rows(s: &mut Session, ids: &[NodeId], mode: &str) -> (Vec<NodeId>, Option<NodeId>) {
let revision = s.doc().unwrap().revision;
let r = run(s, "layer.highlight", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "mode": mode}));
let st = s.doc().unwrap();
assert_eq!(st.revision, revision + 1, "{mode} {ids:?}");
let rows: Vec<NodeId> = r["rows"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(rows, st.layer_rows, "{mode} {ids:?}");
(rows, st.active_layer)
}
/// `layer.highlight` keeps the rows in highlight order: `set` and `add` take a repeated id once,
/// `toggle` takes an id listed twice off and on again (or on and off, and its layer becomes the
/// current one), unknown ids and ids after the first 100,000 are dropped, rows highlighted twice
/// stay as they are on `add`, and `toggle` takes every copy off.
#[test]
fn highlighting_rows_keeps_their_order_with_repeated_unknown_and_excess_ids() {
let mut s = session();
let (layer, sub, a, g, b, c) = tree(&mut s);
let unknown = NodeId(9999);
assert_eq!(highlight_rows(&mut s, &[a, g, a, unknown, c], "set"), (vec![a, g, c], Some(layer)));
assert_eq!(highlight_rows(&mut s, &[g, b, a, b], "add"), (vec![a, g, c, b], Some(sub)));
assert_eq!(highlight_rows(&mut s, &[c, c], "toggle"), (vec![a, g, b, c], Some(layer)));
// `sub` goes on and off again; it was the last row added, so its layer is the current one.
assert_eq!(highlight_rows(&mut s, &[sub, sub], "toggle"), (vec![a, g, b, c], Some(sub)));
assert_eq!(highlight_rows(&mut s, &[a, unknown], "toggle"), (vec![g, b, c], Some(layer)));
assert_eq!(highlight_rows(&mut s, &[], "add"), (vec![g, b, c], Some(layer)));
assert_eq!(highlight_rows(&mut s, &[], "toggle"), (vec![g, b, c], Some(layer)));
s.doc_mut().unwrap().active_layer = Some(sub);
assert_eq!(highlight_rows(&mut s, &[], "set"), (vec![], Some(sub)), "no rows: the current layer stays");
let mut excess = vec![unknown; 100_000];
excess.push(a);
assert_eq!(highlight_rows(&mut s, &excess, "set"), (vec![], Some(sub)), "only the first 100,000 ids count");
s.doc_mut().unwrap().layer_rows = vec![a, a, g];
assert_eq!(highlight_rows(&mut s, &[a, c], "add"), (vec![a, a, g, c], Some(layer)));
assert_eq!(highlight_rows(&mut s, &[a], "toggle"), (vec![g, c], Some(layer)));
// The same with more than 8 ids.
s.doc_mut().unwrap().layer_rows = vec![a, a, g];
assert_eq!(highlight_rows(&mut s, &[a, c, c, c, c, c, c, c, c], "add"), (vec![a, a, g, c], Some(layer)));
s.doc_mut().unwrap().layer_rows = vec![a, a, g];
assert_eq!(highlight_rows(&mut s, &[a, b, b, b, b, b, b, b, b], "toggle"), (vec![g], Some(sub)), "`b` goes on and off 4 times");
assert_eq!(highlight_rows(&mut s, &[c, g, sub, g, sub, a, unknown, a, c, layer], "toggle"), (vec![g, layer], Some(layer)));
let revision = s.doc().unwrap().revision;
assert!(s.execute("layer.highlight", &json!({"ids": [b.0], "mode": "nope"})).is_err());
let st = s.doc().unwrap();
assert_eq!((st.revision, st.layer_rows.clone()), (revision, vec![g, layer]), "a bad mode changes nothing");
}
/// `layer.highlight`'s rule as a search of the highlighted rows for each id in `p`. The tests
/// compare the command with it.
fn highlight_by_search(st: &mut DocState, p: &Value) -> Value {
let mut ids: Vec<NodeId> = p["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
ids.truncate(crate::cmd::layer::MAX_ROWS);
let mode = p["mode"].as_str().unwrap_or("set");
ids.retain(|id| st.doc.node(*id).is_some());
let mut rows = st.highlighted_rows();
if mode == "set" {
rows.clear();
}
let mut last = None;
for id in ids {
if mode == "toggle" && rows.contains(&id) {
rows.retain(|r| *r != id);
} else if !rows.contains(&id) {
rows.push(id);
last = Some(id);
}
}
if let Some(layer) = last.or(rows.last().copied()).and_then(|id| st.doc.layer_containing(id)) {
st.active_layer = Some(layer);
}
st.layer_rows = rows;
st.revision += 1;
json!({ "rows": st.layer_rows.iter().map(|i| i.0).collect::<Vec<_>>() })
}
/// Two sessions with `n` squares on a layer and a sublayer after them, and the squares' ids.
fn highlight_pair(n: usize) -> (Session, Session, Vec<NodeId>, NodeId) {
let make = || {
let mut s = super::large_edits::session(n, super::large_edits::square);
let sub = id(&run(&mut s, "layer.newSublayer", json!({"name": "Sub"})));
(s, sub)
};
let ((cmd, sub), (search, other)) = (make(), make());
assert_eq!(sub, other);
let squares = super::large_edits::layer(&cmd, 0).into_iter().filter(|i| *i != sub).collect();
(cmd, search, squares, sub)
}
/// `p` for `layer.highlight` with `ids` and `mode`.
fn highlight_params(ids: impl IntoIterator<Item = NodeId>, mode: &str) -> Value {
json!({"ids": ids.into_iter().map(|i| i.0).collect::<Vec<_>>(), "mode": mode})
}
/// On 3,000 rows `layer.highlight` gives what [`highlight_by_search`] gives: the same rows in the
/// same order, the same current layer and the same returned rows, with repeated, unknown and
/// toggled ids.
#[test]
fn layer_highlight_matches_a_search_of_the_rows_for_each_id() {
let (mut cmd, mut search, sq, sub) = highlight_pair(3_000);
let unknown = NodeId(u64::MAX);
let steps = [
highlight_params(sq[..2_000].iter().copied(), "set"),
highlight_params(sq[1_000..].iter().copied().chain([sub, sq[0]]), "add"),
highlight_params([sq[5], sq[5], sub, sq[2_999], unknown, sub, sub], "toggle"),
highlight_params(sq[500..520].iter().chain(&sq[510..515]).copied(), "toggle"),
highlight_params(sq.iter().rev().step_by(7).copied(), "add"),
highlight_params(sq.iter().step_by(3).copied().chain([sub]), "toggle"),
highlight_params(Vec::new(), "add"),
highlight_params(sq.iter().rev().step_by(2).chain(&sq[..10]).copied(), "set"),
highlight_params(Vec::new(), "set"),
];
for p in &steps {
let r = run(&mut cmd, "layer.highlight", p.clone());
let expected = highlight_by_search(search.doc_mut().unwrap(), p);
let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap());
assert_eq!(r, expected, "{}", p["mode"]);
assert_eq!((&a.layer_rows, a.active_layer, a.revision), (&b.layer_rows, b.active_layer, b.revision), "{}", p["mode"]);
}
}
/// Time `layer.highlight` against [`highlight_by_search`] on one layer of 20,000 paths: `set` of
/// all of them, `add` of 10,000 already highlighted and `toggle` of one, 7 runs each, both checked
/// to give the same rows and current layer.
/// Run with `cargo test --release -p vectorcraft-engine --lib layer_highlight_timing -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn layer_highlight_timing() {
let (mut cmd, mut search, sq, _) = highlight_pair(20_000);
let steps = [
("set of 20,000", highlight_params(sq.iter().copied(), "set")),
("add of 10,000", highlight_params(sq[5_000..15_000].iter().copied(), "add")),
("toggle of 1", highlight_params([sq[10_000]], "toggle")),
];
let mut ms = vec![(Vec::new(), Vec::new()); steps.len()];
for run_no in 0..7 {
for (i, (_, p)) in steps.iter().enumerate() {
let mut time_cmd = || {
let start = std::time::Instant::now();
let r = cmd.execute("layer.highlight", p).unwrap();
(start.elapsed().as_secs_f64() * 1000.0, r)
};
let mut time_search = || {
let start = std::time::Instant::now();
let r = highlight_by_search(search.doc_mut().unwrap(), p);
(start.elapsed().as_secs_f64() * 1000.0, r)
};
// Alternate which goes first.
let ((tc, rc), (ts, rs)) = if run_no % 2 == 0 {
let c = time_cmd();
(c, time_search())
} else {
let s = time_search();
(time_cmd(), s)
};
assert_eq!(rc, rs);
let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap());
assert_eq!((&a.layer_rows, a.active_layer), (&b.layer_rows, b.active_layer));
ms[i].0.push(ts);
ms[i].1.push(tc);
}
}
let median = |v: &[f64]| {
let mut v = v.to_vec();
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
for ((name, _), (search_ms, cmd_ms)) in steps.iter().zip(&ms) {
println!(
"{name}: search {:.3} ms, command {:.3} ms (median of 7); search runs {search_ms:.3?}, command runs {cmd_ms:.3?}",
median(search_ms),
median(cmd_ms)
);
}
}
fn document_rows(s: &Session) -> Vec<u64> {
crate::inspect::document(s)["layerRows"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()
}
@@ -1102,6 +1279,43 @@ fn locate_object_highlights_its_row() {
assert!(s.execute("layer.locate", &json!({})).is_err());
}
/// With several objects selected, Locate Object finds the frontmost one in the stacking order,
/// whatever order they were selected in; an `id` still wins.
#[test]
fn locate_object_finds_the_frontmost_selected_object() {
let mut s = session();
let (_, sub, a, g, b, c) = tree(&mut s);
let top = id(&run(&mut s, "layer.new", json!({"top": true})));
let d = rect(&mut s, 400.0);
let locate = |s: &mut Session, ids: &[NodeId]| {
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
assert_eq!(s.doc().unwrap().selection.objects.last(), ids.last(), "selected in this order");
run(s, "layer.locate", json!({}))["id"].clone()
};
// In one sublayer, the group in front of the rectangle selected last.
assert_eq!(locate(&mut s, &[g, a]), json!(g.0));
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g]);
// The sublayer sits in front of the art directly in its layer.
assert_eq!(locate(&mut s, &[a, c]), json!(a.0));
// A higher layer wins over everything below it.
assert_eq!(locate(&mut s, &[d, b, c]), json!(d.0));
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![d]);
// A group and its member: the member paints after the group it is in.
assert_eq!(locate(&mut s, &[b, g]), json!(b.0));
// Added one at a time, as by Shift-clicks.
run(&mut s, "select.set", json!({"ids": [d.0]}));
run(&mut s, "select.add", json!({"ids": [a.0]}));
assert_eq!(run(&mut s, "layer.locate", json!({}))["id"], d.0);
// An id still locates that object, behind the selection or not.
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0}))["id"], c.0);
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![c]);
// Locate Layer takes the layer of the frontmost selected object.
run(&mut s, "select.set", json!({"ids": [d.0, a.0]}));
assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true})), json!({"id": top.0, "objectId": d.0, "ancestry": [top.0]}));
run(&mut s, "select.set", json!({"ids": [a.0, c.0]}));
assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true}))["id"], sub.0);
}
/// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer
/// or sublayer holding the object, through any groups; a layer locates itself.
#[test]
+183 -4
View File
@@ -2377,7 +2377,8 @@ fn find_and_replace_leaves_type_on_a_locked_artboard() {
/// Find and Replace that replaces each match with the text it is (`CAT` found in `cat`, ignoring
/// case, and replaced by `cat`) records no undo step: the step to redo stays and the document stays
/// unmodified. It still replies with the count. A replacement that changes the text is one undo step.
/// unmodified. It still replies with the count, and with no match replaced. A replacement that
/// changes the text is one undo step.
#[test]
fn find_and_replace_that_changes_nothing_records_no_undo_step() {
let mut s = session();
@@ -2385,9 +2386,9 @@ fn find_and_replace_that_changes_nothing_records_no_undo_step() {
select_with_a_step_to_redo(&mut s, &[a]);
let before = history(&s);
assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved");
assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2}));
assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2, "replaced": 0}));
assert_eq!((history(&s), plain(&s, a)), (before, "cat cat".to_string()));
assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2}));
assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2, "replaced": 2}));
assert_eq!((history(&s), plain(&s, a)), ((before.0 + 1, 0, true), "dog dog".to_string()));
}
@@ -2424,12 +2425,190 @@ fn find_next_cycles_through_text_objects() {
let _ = text(&mut s, "banana");
let c = text(&mut s, "pineapple");
s.execute("select.none", &json!({})).unwrap();
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), a);
// From the top of the stacking order down, then round again.
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), c);
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a);
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), c);
// A selection that starts with a shape goes on after its first type object.
let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
sel(&mut s, &[shape, c]);
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a);
assert!(s.execute("edit.findNext", &json!({"find": "zzz"})).unwrap()["id"].is_null());
}
/// The match `r` (an `edit.findNext` result) as (object, start, end, index, count).
fn found(r: &Value) -> (u64, u64, u64, u64, u64) {
let n = |k: &str| r[k].as_u64().unwrap_or_else(|| panic!("no `{k}` in {r}"));
(n("id"), n("start"), n("end"), n("index"), n("count"))
}
/// Find Next steps through the matches one by one when each call is given the match before it:
/// the objects from the top of the stacking order down, each object's matches in reading order,
/// and round again after the last. Search Backwards visits them the other way. Each match is
/// returned with its bytes and its object is selected; nothing is recorded for undo.
#[test]
fn find_next_steps_through_the_matches_in_both_directions() {
let mut s = session();
let bottom = text(&mut s, "cat éa cat");
let _ = text(&mut s, "dog");
let top = text(&mut s, "a cat");
s.execute("select.none", &json!({})).unwrap();
let before = history(&s);
let step = |s: &mut Session, from: &Value, backwards: bool| {
let from = if from.is_null() { Value::Null } else { json!({"id": from["id"], "start": from["start"], "end": from["end"]}) };
s.execute("edit.findNext", &json!({"find": "cat", "from": from, "backwards": backwards})).unwrap()
};
// "é" is two bytes, so the second match of the bottom object is at bytes 8..11.
let forward = [(top.0, 2, 5, 1, 3), (bottom.0, 0, 3, 2, 3), (bottom.0, 8, 11, 3, 3), (top.0, 2, 5, 1, 3)];
let mut at = Value::Null;
for want in forward {
at = step(&mut s, &at, false);
assert_eq!((found(&at), selected(&s), at["selected"].clone()), (want, vec![NodeId(want.0)], json!(true)));
}
let backward = [(bottom.0, 8, 11, 3, 3), (bottom.0, 0, 3, 2, 3), (top.0, 2, 5, 1, 3), (bottom.0, 8, 11, 3, 3)];
s.execute("select.none", &json!({})).unwrap();
let mut at = Value::Null;
for want in backward {
at = step(&mut s, &at, true);
assert_eq!((found(&at), selected(&s)), (want, vec![NodeId(want.0)]));
}
assert_eq!(history(&s), before, "finding is no undo step");
// A `from` in an object the search does not visit starts at the first match.
let r = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": 999_999, "start": 0, "end": 0}})).unwrap();
assert_eq!(found(&r), (top.0, 2, 5, 1, 3));
// So does a null `from`, with a type object selected.
sel(&mut s, &[top]);
let r = s.execute("edit.findNext", &json!({"find": "cat", "from": null})).unwrap();
assert_eq!(found(&r), (top.0, 2, 5, 1, 3));
// Nothing found: no match, and the selection stays.
let r = s.execute("edit.findNext", &json!({"find": "zebra"})).unwrap();
assert_eq!((r, selected(&s)), (json!({"id": null, "count": 0}), vec![top]));
}
/// Check Hidden Layers and Check Locked Layers: Find Next and Find and Replace leave the type of
/// a hidden layer and of a locked layer alone unless the switch for it is on. A match on such a
/// layer is returned without being selected. A hidden or locked object keeps its type out with
/// the switches on.
#[test]
fn find_and_replace_reach_hidden_and_locked_layers_only_when_asked() {
for (prop, switch, other) in [("visible", "hiddenLayers", "lockedLayers"), ("locked", "lockedLayers", "hiddenLayers")] {
let mut s = session();
let open = text(&mut s, "cat one");
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let closed = text(&mut s, "cat two");
let object = text(&mut s, "cat three");
let off = |id: NodeId| if prop == "visible" { json!({"id": id.0, "visible": false}) } else { json!({"id": id.0, "locked": true}) };
s.execute("object.setProps", &off(object)).unwrap();
s.execute("layer.setProps", &off(layer)).unwrap();
sel(&mut s, &[open]);
// Without the switch, and with only the other one, the one reachable match is found.
for p in [json!({"find": "cat"}), json!({"find": "cat", other: true})] {
let r = s.execute("edit.findNext", &p).unwrap();
assert_eq!(found(&r), (open.0, 0, 3, 1, 1), "{prop} {p}");
}
// With it, the layer's type is searched (it is above, so it comes first) and not selected.
s.execute("select.none", &json!({})).unwrap();
let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true})).unwrap();
assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((closed.0, 0, 3, 1, 2), json!(false), vec![]), "{prop}");
let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true, "from": {"id": closed.0, "start": 0, "end": 3}})).unwrap();
assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((open.0, 0, 3, 2, 2), json!(true), vec![open]), "{prop}");
// Replace All: the same reach.
let n = undo_len(&s);
assert_eq!(
s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", other: true})).unwrap(),
json!({"count": 1, "replaced": 1}),
"{prop}"
);
assert_eq!((plain(&s, open), plain(&s, closed), plain(&s, object)), ("dog one".into(), "cat two".into(), "cat three".into()), "{prop}");
assert_eq!(
s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", switch: true})).unwrap(),
json!({"count": 1, "replaced": 1}),
"{prop}"
);
assert_eq!((plain(&s, closed), plain(&s, object), undo_len(&s)), ("dog two".into(), "cat three".into(), n + 2), "{prop}");
}
}
/// Replace changes one match, the bytes Find Next returned, as one undo step, and returns the
/// replacement's bytes to go on from. Bytes that are no match are refused, and a match that
/// already reads as the replacement is left with no undo step.
#[test]
fn replace_match_replaces_the_one_match_found() {
let mut s = session();
let t = text(&mut s, "cat cat Cat");
s.execute("select.none", &json!({})).unwrap();
let first = s.execute("edit.findNext", &json!({"find": "cat"})).unwrap();
assert_eq!(found(&first), (t.0, 0, 3, 1, 3));
let n = undo_len(&s);
let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "horse", "id": t.0, "start": 0, "end": 3})).unwrap();
assert_eq!(r, json!({"id": t.0, "start": 0, "end": 5, "replaced": true}));
assert_eq!((plain(&s, t), undo_len(&s)), ("horse cat Cat".to_string(), n + 1));
// Replace & Find: on from the replacement, so text put in is not searched again.
let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "a cat", "id": t.0, "start": 6, "end": 9})).unwrap();
let next = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": r["id"], "start": r["start"], "end": r["end"]}})).unwrap();
assert_eq!((plain(&s, t), found(&next)), ("horse a cat Cat".to_string(), (t.0, 12, 15, 2, 2)));
// Match Case decides what a match is.
let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
s.execute("select.none", &json!({})).unwrap();
let before = (history(&s), plain(&s, t));
for (p, want) in [
(json!({"find": "cat", "replace": "x", "matchCase": true, "id": t.0, "start": 12, "end": 15}), "at bytes 12..15 of object"),
(json!({"find": "cat", "replace": "x", "id": t.0, "start": 1, "end": 4}), "at bytes 1..4 of object"),
(json!({"find": "cat", "replace": "x", "id": t.0, "start": 4, "end": 1}), "at bytes 1..4 of object"),
(json!({"find": "cat", "replace": "x", "id": t.0, "start": 0}), "missing `end`"),
(json!({"find": "cat", "replace": "x", "start": 0, "end": 3}), "missing `id`"),
(json!({"find": "cat", "replace": "x", "id": t.0, "start": "0", "end": 3}), "`start` must be a whole number"),
(json!({"find": "", "replace": "x", "id": t.0, "start": 0, "end": 3}), "missing `find`"),
(json!({"find": "cat", "replace": 5, "id": t.0, "start": 8, "end": 11}), "`replace` must be a string"),
(json!({"find": "cat", "replace": "x", "id": shape.0, "start": 0, "end": 3}), "is not text"),
] {
let r = s.execute("edit.replaceMatch", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}");
assert_eq!((history(&s), plain(&s, t)), before, "{p}");
}
let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "x", "id": 999_999, "start": 0, "end": 3}));
assert!(matches!(r, Err(EngineError::NoNode(NodeId(999_999)))), "{r:?}");
// A match that already reads as the replacement: nothing to undo.
let r = s.execute("edit.replaceMatch", &json!({"find": "CAT", "replace": "Cat", "id": t.0, "start": 12, "end": 15})).unwrap();
assert_eq!((r, history(&s)), (json!({"id": t.0, "start": 12, "end": 15, "replaced": false}), before.0));
// Find Next refuses a `from` that is not a match.
for (from, want) in [
(json!(5), "missing `id`"),
(json!({"id": t.0, "start": 2}), "missing `end`"),
(json!({"id": "x", "start": 0, "end": 1}), "`id` must be a whole number"),
] {
let r = s.execute("edit.findNext", &json!({"find": "cat", "from": from}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{from}: {r:?}");
}
for key in ["backwards", "hiddenLayers", "lockedLayers"] {
let r = s.execute("edit.findNext", &json!({"find": "cat", key: "yes"}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}");
}
for key in ["hiddenLayers", "lockedLayers"] {
let r = s.execute("edit.findReplace", &json!({"find": "cat", key: 1}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}");
}
}
/// Ruby over text after a replaced match moves with the text, for Replace and for Replace All, as
/// it does when the text is typed.
#[test]
fn find_and_replace_moves_the_ruby_after_a_match() {
for all in [false, true] {
let mut s = session();
let t = text(&mut s, "ab 漢字");
sel(&mut s, &[t]);
s.execute("type.ruby", &json!({"text": "かんじ", "start": 3, "end": 9})).unwrap();
if all {
s.execute("edit.findReplace", &json!({"find": "ab", "replace": "abcd"})).unwrap();
} else {
s.execute("edit.replaceMatch", &json!({"find": "ab", "replace": "abcd", "id": t.0, "start": 0, "end": 2})).unwrap();
}
let NodeKind::Text(tt) = &node(&s, t).kind else { panic!() };
assert_eq!((tt.plain_text().as_str(), tt.ruby.first().map(|r| (r.start, r.end))), ("abcd 漢字", Some((5, 11))), "all: {all}");
}
}
/// The Type menu's commands and Find and Replace and Find Next refuse a param of the wrong type, or
/// `ids` that name no object, with an error naming the param, and leave the text, the selection and
/// the undo history as they were, even when Insert Character is also given a source it would use
+9 -4
View File
@@ -326,9 +326,11 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() {
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap()
};
// Reopened existing links use native separators; missing links keep their stored path.
let red = dir.0.join("art").join("red.png").to_string_lossy().into_owned();
let person = report(&run(&mut s, "file.package", json!({})));
assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}");
assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}");
assert!(person.contains(&format!("{red} → Links/red.png")), "{person}");
assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}");
let in_root = dir.0.join("in");
@@ -339,16 +341,19 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() {
assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}");
let base = dir.0.to_string_lossy().into_owned();
assert!(!text.contains(&base), "{text}");
// Compare serialized JSON with the path encoded the same way, without its outer quotes.
let json_base = serde_json::to_string(&base).unwrap();
let json_base = &json_base[1..json_base.len() - 1];
for key in ["missingLinks", "warnings", "files"] {
assert!(!client[key].to_string().contains(&base), "{key}: {client}");
assert!(!client[key].to_string().contains(json_base), "{key}: {client}");
}
// Document Info, whose report the package holds, gives no link either.
for p in [json!({}), json!({"format": "text"})] {
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone()));
assert!(!info.to_string().contains(&base), "{p}: {info}");
assert!(!info.to_string().contains(json_base), "{p}: {info}");
}
let info = run(&mut s, "document.info", json!({"format": "text"}));
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
assert!(info["text"].as_str().unwrap().contains(&red), "the person's: {info}");
}
/// A confined request packages no document that links, or places a native document or a PDF with
+4
View File
@@ -1121,6 +1121,10 @@ fn path_commands_refuse_a_param_of_the_wrong_type() {
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);
+21
View File
@@ -176,3 +176,24 @@ fn a_file_over_the_limit_is_refused_before_it_is_parsed() {
assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err());
assert_eq!(s.prefs.to_json().to_string(), before);
}
/// Hold Shortcuts is off by default. The Hold Shortcut Delay takes 0.2 to 1.0 s and refuses other
/// values; a value from a settings file outside the range is brought inside it.
#[test]
fn hold_shortcut_preferences() {
let mut s = Session::new();
assert!(!s.prefs.hold_shortcuts);
assert_eq!(s.prefs.key_hold_delay(), 0.35);
for ok in [0.2, 1.0] {
s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": ok})).unwrap();
assert_eq!(s.prefs.key_hold_delay(), ok);
}
for bad in [0.1, 1.5] {
assert!(is_bad_params(s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": bad}))), "{bad}");
}
s.execute("prefs.set", &json!({"key": "holdShortcuts", "value": true})).unwrap();
assert!(s.prefs.hold_shortcuts);
let restored: Prefs = serde_json::from_value(json!({"keyHoldDelay": 5.0})).unwrap();
assert_eq!(restored.key_hold_delay(), 1.0);
assert!(!restored.hold_shortcuts);
}
+43
View File
@@ -851,6 +851,49 @@ fn keep_in_group_colors_leaves_that_swatch_as_it_is() {
assert_ne!(g[1], "#00ff00", "the other new color takes it");
}
/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply`
/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color
/// swatches in order.
#[test]
fn apply_with_a_group_keeps_its_gradient_swatch() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff"]}));
let fade = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default())));
s.edit("test", |d, _| {
let w = vectorcraft_color::Swatch { name: "Fade".into(), paint: fade.clone(), global: false, spot: false };
d.swatch_groups.iter_mut().find(|g| g.name == "Brand").unwrap().swatches.insert(1, w);
Ok(())
})
.unwrap();
let group = |s: &Session| -> Vec<(String, Option<String>)> {
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone();
g.iter().map(|w| (w.name.clone(), w.paint.color().map(|c| c.to_hex()))).collect()
};
let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect();
rect(&mut s, json!("#ff0000"));
rect(&mut s, json!("#0000ff"));
select_all(&mut s);
// The rows' new colors go to the red and blue swatches; the gradient stays between them.
let map = json!([{"from": ["#ff0000"], "to": "#00ff00"}, {"from": ["#0000ff"], "to": "#ffff00"}]);
run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand"}));
let want = |a: &str, b: &str| vec![(names[0].clone(), Some(a.to_string())), (names[1].clone(), None), (names[2].clone(), Some(b.to_string()))];
assert_eq!(group(&s), want("#00ff00", "#ffff00"));
assert_eq!(gradient_at(&s, 1), fade, "the gradient swatch keeps its paint");
// `groupColors` counts the color swatches only: "keep" is the first, and the second color is
// the blue swatch's.
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["keep", "#123456"]}));
assert_eq!(group(&s), want("#00ff00", "#123456"));
// A null removes the color swatch at its place and leaves the gradient.
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": [null, "#123456"]}));
assert_eq!(group(&s), [(names[1].clone(), None), (names[2].clone(), Some("#123456".into()))]);
assert_eq!(gradient_at(&s, 0), fade);
}
/// The paint of the swatch at place `i` of the group "Brand".
fn gradient_at(s: &Session, i: usize) -> vectorcraft_color::Paint {
s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches[i].paint.clone()
}
/// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of
/// the group, which the rewrite gives another color, loses the link instead of following it.
#[test]
+25
View File
@@ -77,6 +77,31 @@ fn script_missing_include_reports_origin() {
assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}");
assert_eq!(report["log"], json!([]), "nothing ran before the include was read");
assert!(report.get("file").is_none(), "the line is the script's own");
assert_eq!(report["messageOrigin"], "built-in");
let _ = std::fs::remove_dir_all(base);
}
/// An error in an included file keeps where its message came from: a value the file threw is the
/// script's own text, and an error the app raised for it, or for a file `$.evalFile` could not run, is not.
#[test]
fn script_include_errors_keep_their_message_origin() {
let base = folder("origin");
write(&base.join("main/lib.jsxinc"), "var a = 1;\n throw new RangeError('invalid array length');");
write(&base.join("main/native.jsxinc"), "var a = 1;\n new Array(-1);");
for (text, message, origin) in [
("#include \"lib.jsxinc\"", "RangeError: invalid array length", "script"),
("#include \"native.jsxinc\"", "RangeError: invalid array length", "built-in"),
("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e; }", "RangeError: invalid array length", "built-in"),
("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e.message; }", "invalid array length", "script"),
] {
let report = failed(&base, text);
assert_eq!((report["message"].as_str(), report["messageOrigin"].as_str()), (Some(message), Some(origin)), "{text}: {report}");
}
let report = failed(&base, "#include \"lib.jsxinc\"");
let file = report["file"].as_str().map(|f| Path::new(f).ends_with("lib.jsxinc"));
assert_eq!((file, report["line"].as_u64(), report["column"].as_u64()), (Some(true), Some(2), Some(3)), "{report}");
let report = failed(&base, "$.evalFile('nope.jsx');");
assert_eq!(report["messageOrigin"], "built-in", "{report}");
let _ = std::fs::remove_dir_all(base);
}
+52
View File
@@ -170,6 +170,58 @@ fn an_error_names_the_script_its_place_and_kind() {
assert_eq!(s.script_report().unwrap()["line"], 1);
}
/// A failed run's report keeps its message and kind and says where the message came from: text the
/// script supplied, or one of the app's own errors. The status text and the console line read the
/// same either way, and only the app's own errors get advice about other applications' objects.
#[test]
fn failed_script_report_keeps_message_and_adds_origin() {
let mut s = two_docs();
for (source, kind, message, origin) in [
("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"),
("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"),
("throw 'invalid array length';", "thrown", "invalid array length", "script"),
("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"),
("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"),
("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"),
("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"),
("vc.run();", "thrown", "TypeError: vc.run: give a command id, as a string", "built-in"),
] {
let e = run(&mut s, source).unwrap_err().to_string();
let report = s.script_report().unwrap().clone();
assert_eq!(
(report["kind"].as_str(), report["message"].as_str(), report["messageOrigin"].as_str()),
(Some(kind), Some(message), Some(origin)),
"{source}"
);
let (line, column) = (&report["line"], &report["column"]);
let before = format!("t.js: line {line}, column {column}: ");
assert_eq!(e, format!("{before}{message} ({kind})"), "{source}");
assert_eq!(s.script_failure_text().as_deref(), Some(e.as_str()));
let authored = s.script_authored_failure();
assert_eq!(authored, (origin == "script").then(|| (before.clone(), message, format!(" ({kind})"))), "{source}");
let console = s.execute("script.console", &json!({})).unwrap();
let error = console["lines"].as_array().unwrap().iter().rev().find(|l| l["kind"] == "error").map(|l| l["text"].clone());
assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}");
}
// The app's own reference error names the `vc` object; the same text a script threw does not.
run(&mut s, "app.activeDocument;").unwrap_err();
assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`"));
assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in");
// An error in code `eval` compiled keeps where its message came from.
let e = run(&mut s, "eval(\"throw new Error('invalid array length')\");").unwrap_err().to_string();
assert_eq!(e, "t.js: Error: invalid array length (thrown)");
assert_eq!(s.script_authored_failure(), Some(("t.js: ".to_string(), "Error: invalid array length", " (thrown)".to_string())));
// Syntax errors and limits are the app's own.
run(&mut s, "var = 1;").unwrap_err();
assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_authored_failure()), (Some("syntax"), None));
s.execute("script.run", &json!({"source": "while (true) {}", "name": "t.js", "maxFuel": 100_000})).unwrap_err();
assert_eq!((s.script_report().unwrap()["messageOrigin"].as_str(), s.script_authored_failure()), (Some("built-in"), None));
// A run that completes has no failure to split.
run(&mut s, "throw 'x';").unwrap_err();
run(&mut s, "1").unwrap();
assert_eq!(s.script_authored_failure(), None);
}
/// An error raised where the run has no place for it, such as in code `eval` compiled, is named
/// with the script and its kind alone, with one colon after the script's name.
#[test]