Merge main into perf/layer-highlight-set

This commit is contained in:
dotCooCoo committed 2026-11-18 07:39:22 -08:00
commit bf2ca2cf80
680 files changed
+65906 -4204

No files matched your search

+106
View File
@@ -227,6 +227,112 @@ fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() {
assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0));
}
/// `brushed_strokes_profiled` reads the strokes `stroke.set` edits: a group's own stroke when it
/// has one, else its members'. It answers only while each of them draws with a brush, and not
/// while an object has no stroke row, which `stroke.set` would give a plain stroke.
#[test]
fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false), "both draw with a brush, neither has a profile");
run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(true), "one has a profile");
let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(true), "a group without its own stroke: its members'");
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(s.brushed_strokes_profiled(), None, "the group's own plain stroke takes the profile");
let c = rect(&mut s, 400.0);
run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1}));
assert!(node(&s, c).appearance.stroke().is_none());
run(&mut s, "select.set", json!({"ids": [a.0, c.0]}));
assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke");
}
/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count.
#[test]
fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 120.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let c = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "add"}))["id"].as_u64().unwrap());
assert!(node(&s, c).appearance.stroke().is_some_and(|st| st.brush.is_none()), "the compound shape's own plain stroke");
s.edit("Brush", |d, _| {
for id in [a, b] {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some("3 pt. Round".into());
}
}
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(s.brushed_strokes_profiled(), None);
s.edit("Brush", |d, _| {
d.node_mut(c).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false));
}
/// A targeted layer with its own plain Stroke row active: `stroke.set` edits that row, so the
/// brushed path inside the layer does not count.
#[test]
fn brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row() {
let mut s = session();
let a = rect(&mut s, 100.0);
run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"}));
let layer = s.doc().unwrap().doc.layers[0].id;
run(&mut s, "layer.target", json!({"id": layer.0}));
run(&mut s, "appearance.addStroke", json!({}));
let rows = &node(&s, layer).appearance.items;
let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_none())).expect("the layer's own stroke row");
run(&mut s, "appearance.setActiveItem", json!({"index": index}));
assert_eq!(s.brushed_strokes_profiled(), None, "the layer's plain stroke takes the profile");
run(&mut s, "stroke.set", json!({"profile": "lens"}));
assert!(node(&s, layer).appearance.items.get(index).is_some_and(|it| matches!(it, AppearanceItem::Stroke(st) if st.profile.is_some())));
assert!(node(&s, a).appearance.stroke().is_some_and(|st| st.profile.is_none()), "the brushed path is left as it was");
}
/// A symbol instance selected with a brushed path takes no stroke from `stroke.set`, so it does
/// not count; the brushed path alone decides.
#[test]
fn brushed_strokes_profiled_leaves_out_symbol_instances() {
let mut s = session();
let a = rect(&mut s, 100.0);
run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"}));
let r = rect(&mut s, 300.0);
run(&mut s, "select.set", json!({"ids": [r.0]}));
let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap());
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }));
run(&mut s, "select.set", json!({"ids": [a.0, inst.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false));
}
/// With the active row a stroke of the first object that another selected object has no equal
/// row for, `stroke.set` edits that object's top stroke, so its top stroke decides.
#[test]
fn brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "appearance.addStroke", json!({}));
run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"}));
run(&mut s, "stroke.set", json!({"ids": [b.0], "weight": 5}));
let rows = &node(&s, a).appearance.items;
let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_some())).expect("a's brushed stroke");
assert!(index >= node(&s, b).appearance.items.len() || node(&s, b).appearance.items[index].is_fill(), "{rows:?}");
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
run(&mut s, "appearance.setActiveItem", json!({"index": index}));
assert_eq!(s.brushed_strokes_profiled(), Some(false), "b's top stroke has the brush too");
}
#[test]
fn text_items_take_item_paint() {
let mut s = session();
+17
View File
@@ -302,6 +302,23 @@ fn the_shared_settings_drive_the_export_and_arent_an_undo_step() {
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["formats"][0]["format"], "jpg");
}
/// The shared settings are not an undo step, so undo and redo of the steps before them leave them
/// as they are.
#[test]
fn undo_and_redo_keep_the_shared_settings() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
run(&mut s, "assets.add", json!({"ids": [a]}));
run(&mut s, "assets.settings.set", json!({"formats": [{"format": "svg"}], "prefix": "ic_"}));
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
run(&mut s, "edit.undo", json!({}));
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings);
run(&mut s, "assets.settings.set", json!({"formats": [{"format": "jpg"}], "prefix": ""}));
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
run(&mut s, "edit.redo", json!({}));
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings);
}
/// An export preset sets the shared settings as the Asset Export panel applies one: its rows (or
/// mobile/density), its format settings over the saved ones, its prefix and its sub-folders.
#[test]
+151
View File
@@ -579,6 +579,157 @@ fn reset_bounding_box_squares_the_turned_members_of_a_square_group() {
assert_eq!(selection_box(&s).angle, 0.0);
}
#[test]
fn rotate_bounding_box_turns_the_box_and_leaves_the_art() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a]);
let art = anchors(&s, a);
let n = undo_len(&s);
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 90})).unwrap();
assert_eq!((r["changed"].as_u64(), r["angle"].as_f64()), (Some(1), Some(90.0)));
assert_eq!(undo_len(&s), n + 1);
assert_eq!(anchors(&s, a), art, "the art stays where it is");
// The box is at 90°, so its width runs along the rectangle's 50 pt side.
let b = selection_box(&s);
assert!(near(b.angle, 90.0));
assert!(near(b.rect.width(), 50.0) && near(b.rect.height(), 100.0), "{b:?}");
// By an angle from the box's angle; absolute sets it; the result wraps to (-180, 180].
s.execute("object.rotateBoundingBox", &json!({"angle": 20})).unwrap();
assert!(near(angle(&s, a), 110.0));
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 200, "absolute": true})).unwrap();
assert!(near(r["angle"].as_f64().unwrap(), -160.0) && near(angle(&s, a), -160.0));
// A box already at the angle changes nothing and adds no step.
let n = undo_len(&s);
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -160, "absolute": true})).unwrap();
assert_eq!(r["changed"], 0);
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 360})).unwrap();
assert_eq!(r["changed"], 0);
assert_eq!(undo_len(&s), n);
// Undo turns the box back; Reset Bounding Box squares it.
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, a), 110.0));
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
assert_eq!(anchors(&s, a), art);
}
/// Turns that add up to 0 within the tolerance leave the box at exactly 0, so the box measures
/// square to the page and Reset Bounding Box has nothing to square.
#[test]
fn rotate_bounding_box_back_to_zero_stores_zero() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a]);
for by in [0.3, -0.1] {
s.execute("object.rotateBoundingBox", &json!({"angle": by})).unwrap();
}
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.2})).unwrap();
assert_eq!((r["angle"].as_f64(), angle(&s, a)), (Some(0.0), 0.0), "{r}");
assert_eq!(selection_box(&s).angle, 0.0);
let n = undo_len(&s);
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0);
assert_eq!(undo_len(&s), n);
// A negative zero is reported and stored as 0.
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.0, "absolute": true})).unwrap();
let got = r["angle"].as_f64().unwrap();
assert!(got == 0.0 && got.is_sign_positive(), "{r}");
assert_eq!(r["changed"], 0);
}
#[test]
fn rotate_bounding_box_gives_a_mixed_selection_one_angle() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = turned_rect(&mut s);
sel(&mut s, &[a, b]);
// The objects share no angle, so the box is square to the page and turns from 0.
assert_eq!(selection_box(&s).angle, 0.0);
let n = undo_len(&s);
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 2);
assert_eq!(undo_len(&s), n + 1, "one step for both");
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
assert!(near(selection_box(&s).angle, 10.0));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, a), 0.0) && near(angle(&s, b), 45.0));
s.execute("edit.redo", &json!({})).unwrap();
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
}
#[test]
fn rotate_bounding_box_turns_the_objects_inside_a_group_with_it() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let art = (anchors(&s, a), anchors(&s, b));
// The group and both members, as Reset Bounding Box counts them.
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 3);
// The members keep their 20° relative to the group's box.
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
assert_eq!((anchors(&s, a), anchors(&s, b)), art);
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, g), 0.0) && near(angle(&s, a), 20.0) && near(angle(&s, b), 20.0));
s.execute("edit.redo", &json!({})).unwrap();
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
// After Ungroup the members still share a turned box.
s.execute("object.ungroup", &json!({})).unwrap();
assert!(near(selection_box(&s).angle, 50.0));
}
/// The art of a linked opacity mask turns with its object; an unlinked mask's art keeps its angle.
#[test]
fn rotate_bounding_box_turns_a_linked_masks_art_only() {
let mask_angle = |s: &Session, a: NodeId| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.bbox_angle;
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 2);
assert!(near(angle(&s, a), 30.0) && near(mask_angle(&s, a), 30.0));
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 1);
assert!(near(angle(&s, a), 40.0) && near(mask_angle(&s, a), 30.0));
}
/// Rotate Bounding Box and Reset Bounding Box act on the same boxes: after a turn of a group that
/// holds an object with a linked opacity mask, Reset squares every box it turned.
#[test]
fn reset_bounding_box_squares_every_box_rotate_bounding_box_turned() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let c = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a, c]);
s.execute("object.group", &json!({})).unwrap();
let art = (anchors(&s, a), anchors(&s, c));
// The group, the masked object, its mask's art and the other rectangle.
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 25})).unwrap()["changed"], 4);
assert!(object_angles(&s).iter().all(|x| near(*x, 25.0)), "{:?}", object_angles(&s));
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 4);
assert!(object_angles(&s).iter().all(|x| *x == 0.0), "{:?}", object_angles(&s));
assert_eq!((anchors(&s, a), anchors(&s, c)), art);
}
#[test]
fn rotate_bounding_box_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a]);
let n = undo_len(&s);
for p in [json!({}), json!({"angle": null}), json!({"angle": "30"}), json!({"angle": 30, "absolute": "yes"})] {
assert!(s.execute("object.rotateBoundingBox", &p).is_err(), "{p}");
}
assert_eq!((angle(&s, a), undo_len(&s)), (0.0, n));
// Nothing selected: the command is not enabled.
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).is_err());
}
/// Two rectangles turned 20°, put in a container by `make`, turned 10° with it and reset, then
/// released by `release`: nothing stands at an angle before or after the release.
fn reset_then_release(make: &str, release: &str) -> Session {
+20 -8
View File
@@ -120,8 +120,9 @@ fn a_blend_and_an_object_make_one_blend_with_more_keys() {
}
/// Choosing the Blend tool again (its button, W, `tool.select`) finishes the blend: the first
/// pick and the chain are dropped, and the document and the selection stay. Choosing another
/// tool again keeps its work: the Pen's open path stays open.
/// pick and the chain are dropped, and the document and the selection stay. The Pen chosen again
/// ends the path it is drawing, as Escape does: the path stays open and the next click starts a
/// new one.
#[test]
fn choosing_the_blend_tool_again_finishes_the_blend() {
let mut s = session();
@@ -148,7 +149,7 @@ fn choosing_the_blend_tool_again_finishes_the_blend() {
click(&mut s, 20.0, 20.0);
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
assert_eq!(spec(&s, g).0, vec![b, c], "a was not added");
// The Pen chosen again goes on drawing its open path.
// The Pen chosen again ends its open path; the next click starts a new one.
s.select_tool("pen", v).unwrap();
s.execute("select.none", &json!({})).unwrap();
let pen = |s: &mut Session, x: f64, y: f64| {
@@ -156,16 +157,27 @@ fn choosing_the_blend_tool_again_finishes_the_blend() {
s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap();
}
};
let anchors = |s: &Session, id| match node(s, id).kind {
NodeKind::Path { path, .. } => path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(),
_ => vec![],
};
// With no path being drawn, choosing the Pen again changes nothing.
let depth = s.doc().unwrap().history.undo.len();
s.select_tool("pen", v).unwrap();
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().selection.objects.len()), (depth, 0));
pen(&mut s, 100.0, 300.0);
pen(&mut s, 200.0, 300.0);
let p = s.doc().unwrap().selection.objects[0];
let depth = s.doc().unwrap().history.undo.len();
s.select_tool("pen", v).unwrap();
assert_eq!(s.tool_id(), "pen", "the Pen stays chosen");
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "ending the path adds no undo step");
assert_eq!(s.doc().unwrap().selection.objects, vec![p], "the path stays selected");
pen(&mut s, 300.0, 300.0);
let anchors = match node(&s, p).kind {
NodeKind::Path { path, .. } => path.subpaths[0].anchors.len(),
_ => 0,
};
assert_eq!(anchors, 3, "the Pen keeps drawing the same path");
assert_eq!(anchors(&s, p), vec![(2, false)], "the path stays open with its two anchors");
let q = s.doc().unwrap().selection.objects[0];
assert_ne!(q, p, "the click starts a new path");
assert_eq!(anchors(&s, q), vec![(1, false)]);
}
#[test]
+52 -4
View File
@@ -110,6 +110,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"art-ribbons",
"ink-and-wash",
"calligraphic-nibs",
"pressure-sensitive",
"bristle-brushes",
"pattern-borders",
"scatter-shapes",
@@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"]
);
assert_eq!(libs[6]["count"].as_u64(), Some(4));
assert_eq!(libs[7]["count"].as_u64(), Some(4));
let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"}));
assert_eq!(
beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"]
);
assert_eq!(libs[7]["count"].as_u64(), Some(4));
assert_eq!(libs[8]["count"].as_u64(), Some(4));
let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"}));
assert_eq!(
dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
);
assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4)));
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
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]}));
@@ -154,6 +155,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("art-ribbons", "art"),
("ink-and-wash", "art"),
("calligraphic-nibs", "calligraphic"),
("pressure-sensitive", "art"),
("bristle-brushes", "bristle"),
("pattern-borders", "pattern"),
("scatter-shapes", "scatter"),
@@ -164,7 +166,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
for b in &lib.brushes {
let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind };
let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind };
assert_eq!(b.kind.type_id(), kind, "{}", b.name);
let mut line = vectorcraft_geom::BezPath::new();
line.move_to((0.0, 0.0));
@@ -299,6 +301,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap();
let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut curve = line_to(20.0);
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
for b in &lib.brushes {
let width_at = |pressure| {
let stroke = vectorcraft_doc::StrokeLayer {
pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }),
..black_stroke()
};
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke);
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name);
let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max);
max - min
};
let light = width_at(0.0);
let heavy = width_at(1.0);
for width in [light, heavy] {
assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name);
}
assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name);
for line in [line_to(2.0), curve.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
/// translucent washes, with names of their own and a few paths of art each.
#[test]
+549
View File
@@ -81,6 +81,224 @@ fn apply_and_remove_brush_with_undo() {
assert!(s.execute("brush.apply", &json!({"name": "Nope"})).is_err());
}
/// The own brush settings of the first stroke of `id`.
fn own_options(s: &Session, id: NodeId) -> Value {
Value::Object(node(s, id).appearance.stroke().map(|st| st.brush_options.clone()).unwrap_or_default())
}
/// The height of the brush art of `id`, drawn along a level line.
fn art_height(s: &Session, id: NodeId) -> f64 {
let d = &s.doc().unwrap().doc;
vectorcraft_brush::pieces_bounds(&vectorcraft_brush::node_pieces(d, &node(s, id)).unwrap()).unwrap().height()
}
#[test]
fn options_of_selected_object_change_one_path_and_leave_the_brush() {
let mut s = session();
let a = line(&mut s);
let b = line(&mut s);
select(&mut s, &[a, b]);
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
let width = s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"].clone();
select(&mut s, &[a]);
let steps = undo_steps(&s);
let r = s.execute("brush.objectOptions", &json!({"params": {"width": 50, "flip_along": false}})).unwrap();
assert_eq!(r["changed"], json!([a.0]));
assert_eq!(own_options(&s, a), json!({"width": 50.0}), "flip_along equals the brush's own value and is dropped");
assert_eq!(own_options(&s, b), json!({}));
assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"], width, "the brush keeps its width");
assert_eq!(undo_steps(&s), steps + 1);
assert!((art_height(&s, a) * 2.0 - art_height(&s, b)).abs() < 1e-6, "{} vs {}", art_height(&s, a), art_height(&s, b));
// The same settings again, and a call without params, change nothing and add no undo step.
assert_eq!(s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap()["changed"], json!([]));
assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"width": 50.0}));
assert_eq!(undo_steps(&s), steps + 1);
// An edit of the brush reaches the settings the path does not set.
s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 200, "flip_across": true}})).unwrap();
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
// The settings are saved in the native file.
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let st = back.node(a).and_then(|n| n.appearance.stroke().cloned()).unwrap();
assert_eq!(Value::Object(st.brush_options), json!({"width": 50.0}));
// Undo puts the path back on the brush's settings.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(own_options(&s, a), json!({}));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
// Reset clears them, and so do applying a brush and removing it.
s.execute("brush.objectOptions", &json!({"reset": true})).unwrap();
assert_eq!(own_options(&s, a), json!({}));
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
assert_eq!(own_options(&s, a), json!({}));
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
s.execute("brush.remove", &json!({})).unwrap();
assert_eq!(own_options(&s, a), json!({}));
// Stroke Options' brush change clears them as well, and keeping the same brush keeps them.
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
s.execute("stroke.setAdvanced", &json!({"brush": "Arrow"})).unwrap();
assert_eq!(own_options(&s, a), json!({"overlap": true}));
s.execute("stroke.setAdvanced", &json!({"brush": null})).unwrap();
assert_eq!(own_options(&s, a), json!({}));
// Asking for the settings changes nothing, even when the brush has come to equal them.
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
s.execute("brush.options", &json!({"name": "Arrow", "params": {"overlap": true}})).unwrap();
let steps = undo_steps(&s);
assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"overlap": true}));
assert_eq!(own_options(&s, a), json!({"overlap": true}));
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn options_of_selected_object_null_items_keep_each_paths_own() {
let mut s = session();
let a = line(&mut s);
let b = line(&mut s);
s.execute("brush.apply", &json!({"name": "Confetti", "ids": [a.0, b.0]})).unwrap();
let brush_size = s.execute("brush.get", &json!({"name": "Confetti"})).unwrap()["size"].clone();
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"size": [50, 80]}})).unwrap();
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"size": [60, 120]}})).unwrap();
let steps = undo_steps(&s);
// Only the smallest size changes: each path keeps its own largest size.
let r = s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"size": [40, null]}})).unwrap();
assert_eq!(r["changed"], json!([a.0, b.0]));
assert_eq!(own_options(&s, a)["size"], json!([40.0, 80.0]));
assert_eq!(own_options(&s, b)["size"], json!([40.0, 120.0]));
assert_eq!(undo_steps(&s), steps + 1, "one undo step for both paths");
// A path without its own value keeps the brush's item.
let c = line(&mut s);
s.execute("brush.apply", &json!({"name": "Confetti", "ids": [c.0]})).unwrap();
s.execute("brush.objectOptions", &json!({"ids": [c.0], "params": {"size": [null, 150]}})).unwrap();
assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}");
}
/// The size mode the first stroke of `id`, painted with Confetti, draws with.
fn confetti_size_mode(s: &Session, id: NodeId) -> vectorcraft_brush::Variation {
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
let b = lib.iter().find(|b| b.name == "Confetti").unwrap();
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
vectorcraft_brush::BrushKind::Scatter(sc) => sc.modes()[0],
k => panic!("not a scatter brush: {k:?}"),
}
}
#[test]
fn options_of_selected_object_keep_the_modes_each_path_draws_with() {
use vectorcraft_brush::Variation;
let mut s = session();
let a = line(&mut s);
let b = line(&mut s);
select(&mut s, &[a, b]);
s.execute("brush.apply", &json!({"name": "Confetti"})).unwrap();
// Confetti's sizes vary at random from 60% to 140%; the second path's follow the pressure.
select(&mut s, &[b]);
s.execute("brush.objectOptions", &json!({"params": {"modes": ["pressure", null, null, null]}})).unwrap();
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure));
// One size with no mode keeps each path's mode.
select(&mut s, &[a, b]);
s.execute("brush.objectOptions", &json!({"params": {"size": [80, 80]}})).unwrap();
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure));
assert_eq!(own_options(&s, a)["size"], json!([80.0, 80.0]));
// A mode the params give is set on each path.
s.execute("brush.objectOptions", &json!({"params": {"size": [70, 90], "modes": ["fixed", null, null, null]}})).unwrap();
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Fixed, Variation::Fixed));
}
/// The widths (%) the first stroke of `id`, painted with Arrow, draws with at the lightest and the
/// heaviest pressure.
fn arrow_width_range(s: &Session, id: NodeId) -> (f64, f64) {
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
let b = lib.iter().find(|b| b.name == "Arrow").unwrap();
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
vectorcraft_brush::BrushKind::Art(a) => a.width_range(),
k => panic!("not an art brush: {k:?}"),
}
}
#[test]
fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_changes() {
let mut s = session();
let a = line(&mut s);
let b = line(&mut s);
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0]})).unwrap();
// Both widths follow the pressure; the first path's largest width is its width, the second
// path's is its own.
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100, "width_mode": "pressure"}})).unwrap();
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 100, "width_mode": "pressure", "width_max": 150}})).unwrap();
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((100.0, 100.0), (100.0, 150.0)));
// The width the path has already changes nothing.
let steps = undo_steps(&s);
assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100}})).unwrap()["changed"], json!([]));
assert_eq!(own_options(&s, a), json!({"width_mode": "pressure"}));
assert_eq!(undo_steps(&s), steps);
// A new smallest width leaves each path's largest width as it was.
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 50}})).unwrap();
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((50.0, 100.0), (50.0, 150.0)));
// A largest width the params give is set on each path.
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 40, "width_max": 120}})).unwrap();
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
}
#[test]
fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() {
let mut s = session();
let a = line(&mut s);
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 50}})).unwrap();
let extend = |s: &mut Session, brush: &str, points: Value| {
s.execute("brush.freehand", &json!({"points": points, "style": "brush", "brush": brush, "extend": {"id": a.0}})).unwrap();
};
// Continuing the path with its own brush keeps the settings.
extend(&mut s, "Arrow", json!([[0, 0], [40, 30], [80, 10]]));
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
// Another brush, with a stroke or with only the brush changing, clears them.
extend(&mut s, "Diamonds", json!([[0, 0]]));
assert_eq!(brush_of(&s, a).as_deref(), Some("Diamonds"));
assert_eq!(own_options(&s, a), json!({}));
}
#[test]
fn options_of_selected_object_keys_convert_with_the_document() {
let mut s = session();
let a = line(&mut s);
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
let key = json!({"model": "rgb", "r": 0.2, "g": 0.6, "b": 0.3});
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"colorization": {"method": "hueShift", "key": key}}})).unwrap();
assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("rgb"));
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("cmyk"), "{}", own_options(&s, a));
}
#[test]
fn options_of_selected_object_refuse_what_they_cannot_set() {
let mut s = session();
let a = line(&mut s);
let c = line(&mut s);
let plain = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
s.execute("brush.apply", &json!({"name": "3 pt. Round", "ids": [c.0]})).unwrap();
let steps = undo_steps(&s);
let err = |s: &mut Session, p: Value| s.execute("brush.objectOptions", &p).unwrap_err().to_string();
assert!(err(&mut s, json!({"ids": [plain.0], "params": {"width": 50}})).contains("brush"));
assert!(err(&mut s, json!({"ids": [a.0, c.0], "params": {"width": 50}})).contains("different types"));
assert!(err(&mut s, json!({"ids": [a.0], "params": {"angle": 10}})).contains("angle"));
assert!(!err(&mut s, json!({"ids": [a.0], "params": {"width": "wide"}})).is_empty());
assert!(!err(&mut s, json!({"ids": [a.0], "params": [1]})).is_empty());
assert!(err(&mut s, json!({"ids": [a.0], "params": {"width": 50}, "reset": true})).contains("reset"));
assert!(err(&mut s, json!({"ids": [a.0], "reset": "yes"})).contains("reset"));
s.execute("brush.apply", &json!({"name": "Bristle Round", "ids": [c.0]})).unwrap();
let steps_bristle = undo_steps(&s);
assert!(err(&mut s, json!({"ids": [c.0], "params": {"size": 2}})).contains("bristle"));
assert_eq!(undo_steps(&s), steps_bristle);
assert_eq!(steps + 1, steps_bristle, "only the bristle brush's apply added a step");
// Values outside their ranges are clamped, as brush.options clamps them.
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 1e308}})).unwrap();
assert_eq!(own_options(&s, a), json!({"width": 1000.0}));
}
#[test]
fn apply_adds_a_stroke_when_missing_and_reaches_into_groups() {
let mut s = session();
@@ -1071,6 +1289,29 @@ fn brush_freehand_continued_by_one_point_follows_keep_selected() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step");
}
/// A `brush.freehand` call that continues a path by one point with a bad `connect` is refused
/// before the path's brush changes: the brush, the selection and the undo history stay as they were.
#[test]
fn brush_freehand_continued_by_one_point_refuses_a_bad_connect() {
let mut s = session();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
select(&mut s, &[a]);
let undo = undo_steps(&s);
let one = json!({"points": [[120, 10]], "extend": {"id": p.0, "end": "end"}, "brush": "Dots"});
for connect in
[json!({"id": p.0, "end": "end"}), json!({"id": a.0, "end": "middle"}), json!({"end": "end"}), json!({"id": 999_999, "end": "end"})]
{
let mut params = one.clone();
params["connect"] = connect;
assert!(s.execute("brush.freehand", &params).is_err(), "{params}");
assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "{params}: the brush stays");
assert_eq!(selected(&s), [a], "{params}: the selection stays");
assert_eq!(undo_steps(&s), undo, "{params}: no undo step");
}
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
@@ -1182,6 +1423,40 @@ fn paintbrush_tool_uses_the_current_brush() {
assert!(s.execute("brush.setCurrent", &json!({"name": "Nope"})).is_err());
}
/// The current brush and symbol are not undo steps, so undo and redo of other steps leave them as
/// they are. With nothing else changed outside the history, undo back to the saved document leaves
/// it saved.
#[test]
fn undo_and_redo_keep_the_current_brush_and_symbol() {
let mut s = session();
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "A"})).unwrap();
rect(&mut s, 40.0, 10.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "B"})).unwrap();
s.doc_mut().unwrap().mark_saved();
rect(&mut s, 70.0, 10.0, 20.0, 20.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty(), "back at the saved document");
s.execute("edit.redo", &json!({})).unwrap();
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
s.execute("symbol.setCurrent", &json!({"name": "A"})).unwrap();
let current = |s: &mut Session| {
let brush = s.execute("brush.list", &json!({})).unwrap()["current"].clone();
(brush, s.execute("symbol.list", &json!({})).unwrap()["current"].clone())
};
let want = (json!("Arrow"), json!("A"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(current(&mut s), want);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(current(&mut s), want);
// A symbol made current between undoing and redoing its deletion is not kept as current.
s.execute("symbol.delete", &json!({"name": "B"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("currentSymbol"), Some(&json!("A")));
}
/// A Size: Pressure variant of "3 pt. Round" (3 ± 3 pt).
fn pressure_round(s: &mut Session) {
let params = json!({"variation": [0, 0, 3], "modes": ["fixed", "fixed", "pressure"]});
@@ -1351,6 +1626,34 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() {
assert_eq!(back.node(pen).unwrap().appearance.stroke(), doc.node(pen).unwrap().appearance.stroke());
}
/// A Bristle path made from pen samples keeps its input when saved and uses it when exported.
#[test]
fn bristle_path_keeps_and_draws_its_pen_pose() {
let mut s = session();
let id = NodeId(
s.execute(
"brush.freehand",
&json!({"points": [[20, 60, 0.1, 10, 0, 0], [200, 60, 0.9, 35, 0, 90]], "style": "brush", "brush": "Bristle Round"}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let doc: Document = (*s.doc().unwrap().doc).clone();
let st = doc.node(id).unwrap().appearance.stroke().unwrap();
assert!(st.pressure.is_some() && st.tilt.is_some() && st.bearing.is_some() && st.rotation.is_some());
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(back.node(id).unwrap().appearance.stroke(), Some(st));
let mut neutral = doc.clone();
let st = neutral.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
st.pressure = None;
st.tilt = None;
st.bearing = None;
st.rotation = None;
assert_ne!(vectorcraft_svg::export(&doc, &Default::default()), vectorcraft_svg::export(&neutral, &Default::default()));
}
/// Pen pressure belongs to its path: new art, graphic styles and Brush Options' edits leave it.
#[test]
fn pressure_stays_with_its_own_path() {
@@ -1394,6 +1697,46 @@ fn brush_options_set_variation_modes() {
assert_eq!(s.execute("brush.get", &json!({"name": "Dots"})).unwrap()["modes"], modes);
}
/// The fill colors of the copies brushed path `id` draws in `doc`, as `#rrggbb`.
fn piece_fills(doc: &Document, id: NodeId) -> Vec<String> {
let pieces = vectorcraft_brush::node_pieces(doc, doc.node(id).unwrap()).expect("brushed");
pieces.iter().map(|n| n.appearance.fill_paint().color().unwrap().to_hex()).collect()
}
/// Scatter Brush Options' `hue_jitter`: shown by `brush.get`, set by `brush.options`, saved with the
/// document, and the turned colors drawn the same after Open and written by SVG export.
#[test]
fn scatter_hue_jitter_saves_and_exports() {
let mut s = session();
let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string();
let id = line(&mut s);
select(&mut s, &[id]);
s.execute("brush.apply", &json!({ "name": name })).unwrap();
let plain = piece_fills(&s.doc().unwrap().doc, id);
assert!(plain.len() > 10 && plain.iter().all(|c| c == "#ff0000"), "{plain:?}");
assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(0.0), "brush.get shows the option at 0");
s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 120}})).unwrap();
assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(120.0));
let doc = s.doc().unwrap().doc.clone();
let turned = piece_fills(&doc, id);
assert_eq!(turned.len(), plain.len());
let distinct: std::collections::HashSet<&String> = turned.iter().collect();
assert!(distinct.len() > 5, "{turned:?}");
// Saved and opened again, the stroke draws the same colors.
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(piece_fills(&back, id), turned);
// SVG export writes each copy's turned color.
let svg = vectorcraft_svg::export(&doc, &Default::default());
for c in &distinct {
assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG");
}
// Back to 0, the copies draw the art's own color.
s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 0}})).unwrap();
assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain);
}
/// The bounds of the brush art `id`'s strokes draw.
fn brushed_bounds(s: &Session, id: NodeId) -> Rect {
let st = s.doc().unwrap();
@@ -1856,6 +2199,212 @@ fn break_link_then_update_redefines_all_instances() {
assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6);
}
/// Redefine Symbol with `keepArt: true` updates the symbol and its instances from the selection,
/// and the selected art stays ordinary art in its place, with its ids, still selected; the result
/// has no instance id. One undo step takes the definition back. Without `keepArt`, or with false,
/// the art becomes an instance.
#[test]
fn redefine_with_keep_art_leaves_the_art_as_ordinary_art() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
let symbol_art = |s: &Session| s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap();
let old_art = symbol_art(&s);
let steps = s.doc().unwrap().history.undo.len();
select(&mut s, &[a, b]);
let r = s.execute("symbol.update", &json!({"name": name, "keepArt": true})).unwrap();
assert_eq!(r, json!({"name": name, "id": null}));
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
let instances = |s: &Session| {
let mut n = 0;
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
n
};
assert_eq!(instances(&s), 1, "no new instance");
// The instance shows the new art: the 120 × 50 pair.
let w = bounds(&s, inst);
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(symbol_art(&s), old_art, "undo takes the definition back");
s.execute("edit.redo", &json!({})).unwrap();
assert!((bounds(&s, inst).width() - 120.0).abs() < 1e-6, "{:?}", bounds(&s, inst));
// false, like no keepArt, makes the art an instance.
for p in [json!({"name": name, "ids": [a.0], "keepArt": false}), json!({"name": name, "ids": [b.0]})] {
let r = s.execute("symbol.update", &p).unwrap();
let id = NodeId(r["id"].as_u64().expect("an instance id"));
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
}
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
}
/// Redefine Symbol with `keepArt: true` and explicit ids keeps the named art selected only where
/// it can be selected: locked or hidden art is left out. A `keepArt` that is not true or false is
/// refused, with no change and no undo step.
#[test]
fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
let mut s = session();
let (_, name, _) = make_symbol(&mut s);
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
{
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(locked).unwrap().locked = true;
doc.node_mut(hidden).unwrap().visible = false;
}
for bad in [json!("true"), json!(1), json!([true])] {
let before = s.doc().unwrap().doc.clone();
let steps = s.doc().unwrap().history.undo.len();
let e = s.execute("symbol.update", &json!({"name": name, "ids": [a.0], "keepArt": bad})).unwrap_err();
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
}
select(&mut s, &[]);
s.execute("symbol.update", &json!({"name": name, "ids": [a.0, locked.0, hidden.0], "keepArt": true})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "only the selectable art is selected");
for id in [a, locked, hidden] {
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
}
}
/// The number of symbol instances in the document.
fn instance_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
n
}
/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current
/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the
/// result has no instance id and nothing places the symbol. One undo step takes the symbol away
/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance.
#[test]
fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() {
let mut s = session();
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
let steps = s.doc().unwrap().history.undo.len();
select(&mut s, &[a, b]);
let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap();
assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}");
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
assert_eq!(instance_count(&s), 0, "no instance");
let list = s.execute("symbol.list", &json!({})).unwrap();
assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0)));
// The symbol's art is the pair: an instance placed from it is 120 × 50.
let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap());
let w = bounds(&s, placed);
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away");
assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo");
assert_eq!(instance_count(&s), 0, "redo places no instance");
// false, like no keepArt, makes the art an instance.
for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] {
let r = s.execute("symbol.new", &p).unwrap();
let id = NodeId(r["id"].as_u64().expect("an instance id"));
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
}
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
}
/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it
/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the
/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and
/// no undo step.
#[test]
fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
let mut s = session();
let (inst, _, _) = make_symbol(&mut s);
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
{
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(locked).unwrap().locked = true;
doc.node_mut(hidden).unwrap().visible = false;
}
for bad in [json!("true"), json!(1), json!([true])] {
let before = s.doc().unwrap().doc.clone();
let steps = s.doc().unwrap().history.undo.len();
let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err();
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
}
select(&mut s, &[]);
let symbols = s.doc().unwrap().doc.symbols.len();
let ids = [a.0, locked.0, hidden.0, inst.0];
s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1);
let selected = &s.doc().unwrap().selection.objects;
assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}");
for id in [a, locked, hidden] {
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
}
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance");
assert_eq!(instance_count(&s), 1, "no new instance");
}
/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a
/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and
/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines
/// it.
#[test]
fn redefine_refuses_art_holding_an_instance_of_the_symbol() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
// Ring's art is an instance of Box.
let ring = NodeId(s.execute("symbol.new", &json!({"name": "Ring", "ids": [inst.0]})).unwrap()["id"].as_u64().unwrap());
let place =
|s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()["id"].as_u64().unwrap());
let direct = place(&mut s, 300.0);
let plain = rect(&mut s, 20.0, 220.0, 30.0, 30.0);
let grouped = place(&mut s, 100.0);
// A rectangle whose opacity mask is a Box instance.
let masked = rect(&mut s, 60.0, 260.0, 30.0, 30.0);
let mut mask_art = node(&s, direct);
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
mask_art.id = doc.alloc_id();
doc.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true)));
let cases = [
("a Box instance", vec![direct.0]),
("Ring, whose art holds Box", vec![ring.0]),
("art with a Box instance", vec![plain.0, grouped.0]),
("art masked by a Box instance", vec![masked.0]),
];
for (case, ids) in cases {
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute("symbol.update", &json!({"name": name, "ids": ids})).unwrap_err();
assert!(e.to_string().contains("can't hold an instance of itself"), "{case}: {e}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{case}: the document is unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{case}: no undo step");
}
// An instance of a symbol that does not hold Box redefines it.
let dot = rect(&mut s, 200.0, 20.0, 10.0, 10.0);
let dot = NodeId(s.execute("symbol.new", &json!({"name": "Dot", "ids": [dot.0]})).unwrap()["id"].as_u64().unwrap());
let r = s.execute("symbol.update", &json!({"name": name, "ids": [dot.0]})).unwrap();
assert_eq!(r["name"], json!(name));
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap();
assert!(matches!(&art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot"), "{}", art.kind_label());
}
/// A linked opacity mask of a 10 × 10 square at (100, 50).
fn square_mask(s: &mut Session) -> Box<vectorcraft_doc::OpacityMask> {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+63
View File
@@ -582,6 +582,39 @@ fn shape_builder_tool_drives_the_command() {
assert_eq!(layer_children(&s), 1);
}
/// A Shape Builder click that builds nothing puts the reason in the status bar and leaves the
/// document, its undo history and the selection as they were; a click that merges shows no status.
#[test]
fn shape_builder_click_that_builds_nothing_shows_why() {
use vectorcraft_tools::builder::{NO_REGION, SELECT_ALL_PATHS, SELECT_PATHS};
let mut s = session();
let (a, _) = two(&mut s);
let v = ViewInfo::default();
s.select_tool("shapeBuilder", v).unwrap();
let click = |s: &mut Session, x: f64, y: f64| {
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap()
};
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone(), st.is_dirty())
};
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let before = state(&s);
assert_eq!(click(&mut s, 125.0, 50.0), vec![UiRequest::Status(SELECT_ALL_PATHS.into())]);
assert_eq!(click(&mut s, 400.0, 400.0), vec![UiRequest::Status(NO_REGION.into())]);
assert_eq!(state(&s), before, "nothing changed");
s.execute("select.none", &json!({})).unwrap();
let before = state(&s);
assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(SELECT_PATHS.into())]);
assert_eq!(state(&s), before, "nothing changed");
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(String::new())], "a click that merges clears the status");
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
assert!(click(&mut s, 25.0, 50.0).is_empty(), "the next merge shows no status");
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
}
/// A click of the Shape Builder merges over the map the tool built for the hover, as does the
/// command over the same inputs with the same gap; another gap needs a map of its own.
#[test]
@@ -1050,6 +1083,36 @@ fn shape_builder_drops_a_press_held_during_a_merge() {
}
}
/// When `tool.setOption` names no tool, the option is set on the tool that was active when the
/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that
/// switches to the Selection tool.
#[test]
fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() {
let v = ViewInfo::default();
let mut s = session();
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap();
square_row(&mut s);
click_row(&mut s, v);
s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap();
assert!(s.tool_editing(), "the press is held");
let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap();
assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool");
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder"));
assert_eq!(out["pickColorFrom"], json!("artwork"));
assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork")));
// Named while it waits, the Shape Builder is read where it waits, not made afresh from the
// preferences.
s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches"));
let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap();
assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool");
// A value set on it counts as set on the tool chosen.
s.tool_set_since_reset = false;
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap();
assert!(s.tool_set_since_reset(), "the tool chosen was set");
assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false)));
}
/// A new revision of the document made outside a command while a merge is computed on another
/// thread keeps the merge when the selected art is as it was (the next poll applies it, as the
/// command computes it), and drops it when the art changed.
+44 -10
View File
@@ -1,5 +1,6 @@
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
//! `shape.circleThroughPoints`: a circle through two or three given points, or through the two or
//! three anchor points selected with Direct Selection, the Ellipse tool's three Shift-clicks that
//! run it, and the Circle tool.
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
@@ -95,13 +96,42 @@ fn coincident_or_collinear_points_are_refused() {
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
}
/// Points that are not three pairs of finite numbers are an error, not a fallback.
/// Two points are the ends of a diameter: (20, 40) and (100, 100) give the circle centered at
/// (60, 70) with radius 50, through both points, in one undo step. Two points that are the same
/// are refused, and so is a circle that would reach past the canvas, from two points or from three
/// nearly on one line; nothing is drawn and no undo step is recorded.
#[test]
fn two_points_are_the_ends_of_a_diameter() {
let mut s = session();
let undo = undo_len(&s);
let out = s.execute(C, &json!({"points": [[20, 40], [100, 100]]})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(60.0), Some(70.0), Some(50.0)), "{out}");
let id = id_of(&out);
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(10.0, 20.0, 110.0, 120.0)));
assert!(farthest_from_path(&s, id, &[Point::new(20.0, 40.0), Point::new(100.0, 100.0)]) < 50.0 * 3e-4);
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
let (undo, count) = (undo_len(&s), object_count(&s));
let e = s.execute(C, &json!({"points": [[30, 30], [30, 30]]})).unwrap_err().to_string();
assert!(e.contains("no circle passes through these points"), "{e}");
// 4,100,000 pt across, past the canvas's 4,000,000 pt from the origin; and three points 0.001 pt
// off a chord 200 pt long, whose circle has a radius of about 5,000,000 pt.
for points in [json!([[0, 0], [4_100_000, 0]]), json!([[0, 0], [200, 0], [100, 0.001]])] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("result would exceed the canvas"), "{points}: {e}");
}
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Points that are not two or three pairs of finite numbers are an error, not a fallback.
#[test]
fn malformed_points_are_refused() {
let mut s = session();
let undo = undo_len(&s);
for points in [
json!([[0, 0], [10, 0]]),
json!([[0, 0]]),
json!([]),
json!([[0, 0], [10]]),
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
json!([[0, 0], [10, 0], [0]]),
json!([[0, 0], [10, 0], ["0", 10]]),
@@ -109,12 +139,12 @@ fn malformed_points_are_refused() {
json!([[0, 0], [10, 0], [0, 10, 3]]),
] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
assert!(e.contains("`points` must be two or three [x, y] pairs of numbers"), "{points}: {e}");
}
assert_eq!(undo_len(&s), undo);
}
/// With `points` left out, the three anchor points selected with Direct Selection give the
/// With `points` left out, the two or three anchor points selected with Direct Selection give the
/// circle, from one path or several; any other number of them is an error.
#[test]
fn three_direct_selected_anchor_points_give_the_circle() {
@@ -130,11 +160,15 @@ fn three_direct_selected_anchor_points_give_the_circle() {
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
let out = s.execute(C, &json!({"points": null})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
// Two or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
// Two anchors are the ends of a diameter: (0, 0) and (80, 0).
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
let out = s.execute(C, &json!({})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
// One or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{picked}: {e}");
}
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
assert!(s.execute(C, &json!({})).is_err());
@@ -153,7 +187,7 @@ fn three_direct_selected_anchor_points_give_the_circle() {
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{e}");
assert_eq!(undo_len(&s), undo);
}
+72
View File
@@ -594,6 +594,78 @@ fn separations_preview_compares_the_visible_plates_as_a_set() {
assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}");
}
/// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order.
fn visible_plates(r: &Value) -> Vec<bool> {
r["plates"].as_array().unwrap().iter().map(|p| p["visible"].as_bool().unwrap()).collect()
}
/// A session whose document has the process plates and the spot plate `Brand Orange`.
fn session_with_spot_plate() -> Session {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Brand Orange", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap();
s.execute("swatch.setSpot", &json!({"name": "Brand Orange"})).unwrap();
let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Brand Orange"})).unwrap();
s
}
/// `soloToggle` (the panel's Alt-click on a plate's eye) shows that plate alone, and every plate
/// when it already shows alone. A hidden plate, a plate among others, another solo plate and an
/// empty set of plates all give the named plate alone. It leaves the document's undo list and
/// modified state alone.
#[test]
fn separations_preview_solo_toggle_shows_every_plate_the_second_time() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session_with_spot_plate();
let undo = s.doc().unwrap().history.undo.len();
let dirty = s.doc().unwrap().is_dirty();
let solo = |s: &mut Session, n: &str| visible_plates(&s.execute("view.separationsPreview", &json!({"soloToggle": n})).unwrap());
// Off: the preview turns on with the plate alone.
assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]);
assert_eq!(vectorcraft_render::proof::view().separations, Some(vec!["Cyan".to_string()]));
// The same plate again: every plate, the spot plate included, and the preview stays on.
assert_eq!(solo(&mut s, "Cyan"), [true; 5]);
assert!(vectorcraft_render::proof::view().separations.is_some(), "the preview stays on");
// A plate shown among others, then another plate while one shows alone.
assert_eq!(solo(&mut s, "Magenta"), [false, true, false, false, false]);
assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]);
// A hidden plate.
s.execute("view.separationsPreview", &json!({"toggle": "Black"})).unwrap();
assert_eq!(solo(&mut s, "Yellow"), [false, false, true, false, false]);
// No plate shown.
s.execute("view.separationsPreview", &json!({"plates": []})).unwrap();
assert_eq!(solo(&mut s, "Black"), [false, false, false, true, false]);
// The spot plate alone, then every plate.
assert_eq!(solo(&mut s, "Brand Orange"), [false, false, false, false, true]);
assert_eq!(solo(&mut s, "Brand Orange"), [true; 5]);
// A plate the document doesn't have is an error and leaves the view as it is.
let before = vectorcraft_render::proof::view();
assert!(s.execute("view.separationsPreview", &json!({"soloToggle": "Mauve"})).is_err());
assert_eq!(vectorcraft_render::proof::view(), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(s.doc().unwrap().is_dirty(), dirty, "not marked modified");
// `only` stays a setter: the same plate again keeps it alone.
s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap();
let r = s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap();
assert_eq!(visible_plates(&r), [true, false, false, false, false]);
}
/// A plate counts as shown alone when no other plate of the active document shows: names left in
/// the visible set by another document's plates don't count.
#[test]
fn separations_preview_solo_toggle_counts_the_active_documents_plates() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session_with_spot_plate();
s.execute("view.separationsPreview", &json!({"plates": ["Cyan", "Brand Orange"]})).unwrap();
// A new document without the spot plate: Cyan is the only one of its plates shown.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert_eq!(visible_plates(&s.execute("color.plates", &json!({})).unwrap()), [true, false, false, false]);
let r = s.execute("view.separationsPreview", &json!({"soloToggle": "Cyan"})).unwrap();
assert_eq!(visible_plates(&r), [true; 4]);
}
#[test]
fn proof_setup_simulates_tritanopia() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+90 -5
View File
@@ -414,6 +414,61 @@ fn pencil_refuses_an_unknown_style_or_extend_end() {
assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}");
}
/// `path.freehand` refuses a `connect` without `extend`, and checks a `connect` given with `extend`
/// before a stroke of one point returns, so a bad one is refused there too; a refused call changes
/// neither the document nor the undo history. A `connect` of null is a key left out.
#[test]
fn pencil_refuses_connect_without_extend_and_a_bad_connect_for_one_point() {
let mut s = session();
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
let b = line(&mut s, 300.0, 200.0, 400.0, 200.0);
let closed = NodeId(s.execute("path.create", &json!({"d": "M0 500 L50 500 L50 550 Z"})).unwrap()["id"].as_u64().unwrap());
let inner = NodeId(s.execute("path.create", &json!({"d": "M600 500 L650 500"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let stroke = json!({"points": [[200, 100], [250, 150], [300, 200]]});
for connect in [json!({"id": b.0, "end": "start"}), json!({"id": b.0, "end": "middle"}), json!({"id": b.0}), json!({})] {
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "connect": connect })), "connect needs extend");
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({"extend": null, "connect": connect})), "connect needs extend");
}
let refused = |s: &mut Session, p: &serde_json::Value| {
let before = s.doc().unwrap().doc.clone();
let undo = undo_steps(s);
assert!(s.execute("path.freehand", p).is_err(), "{p}");
assert!(s.doc().unwrap().doc == before, "{p} changed the document");
assert_eq!(undo_steps(s), undo, "{p} left an undo step");
};
refused(&mut s, &with(&stroke, json!({"connect": "b"})));
let one = json!({"points": [[200, 100]], "extend": {"id": a.0, "end": "end"}});
let end = "connect end must be \"start\" or \"end\"";
for e in [json!("middle"), json!(1), json!(null)] {
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0, "end": e}})), end);
}
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0}})), end);
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"end": "end"}})), "connect needs id");
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": "b", "end": "end"}})), "`id` must be a whole number");
let other = "connect needs a path other than the one extended";
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": a.0, "end": "end"}})), other);
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": closed.0, "end": "end"}})), "connect path has no open end");
for p in [
with(&one, json!({"connect": "b"})),
with(&one, json!({"connect": {"id": 999_999, "end": "end"}})),
with(&one, json!({"connect": {"id": group.0, "end": "end"}})),
] {
refused(&mut s, &p);
}
assert_eq!((paths(&s).len(), path(&s, a).anchor_count(), path(&s, b).anchor_count()), (4, 2, 2), "refused: nothing changed");
// A good `connect`, or a null one, on a stroke of one point leaves the path as it was.
let undo = undo_steps(&s);
for connect in [json!({"id": b.0, "end": "start"}), json!(null)] {
assert_eq!(s.execute("path.freehand", &with(&one, json!({ "connect": connect }))).unwrap()["id"], json!(a.0));
}
assert_eq!((path(&s, a).anchor_count(), undo_steps(&s)), (2, undo));
// Null without `extend`, `connect` is left out, and the stroke draws a new path.
s.execute("path.freehand", &with(&stroke, json!({"connect": null}))).unwrap();
assert_eq!(paths(&s).len(), 5);
}
/// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath
/// that connect joins on is no longer selected, and Delete then has nothing to delete.
#[test]
@@ -3225,6 +3280,30 @@ fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() {
}
}
/// `path.eraseSegments` refuses a `width` outside 0.001 to 1000 pt, and nothing changes. The ends of
/// the range and null still erase.
#[test]
fn path_eraser_width_outside_its_range_is_refused() {
let mut s = session();
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let drag = json!({"points": [[150, 90], [150, 110]]});
for x in [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)] {
let sel = s.doc().unwrap().selection.clone();
refuses_with(&mut s, "path.eraseSegments", &with(&drag, json!({"width": x})), "`width` must be from 0.001 to 1000");
assert_eq!(s.doc().unwrap().selection, sel, "width {x} changed the selection");
}
for x in [json!(0.001), json!(1000), json!(null)] {
let before = s.doc().unwrap().doc.clone();
let undo = undo_steps(&s);
s.execute("path.eraseSegments", &with(&drag, json!({"width": x}))).unwrap_or_else(|e| panic!("width {x}: {e}"));
assert!(s.doc().unwrap().doc != before, "width {x} erased nothing");
assert_eq!(undo_steps(&s), undo + 1, "width {x}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
}
}
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
/// nothing; null is read as the key left out.
@@ -6268,14 +6347,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() {
}
}
/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more.
/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is
/// an error that leaves the option as it was.
#[test]
fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() {
let mut s = session();
for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] {
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap();
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}");
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap();
for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] {
let before = s.tool_options_of(tool)["fidelity"].clone();
let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err();
assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100"));
assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}");
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap();
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}");
let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}}));
assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}");
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}");
}
}
+270
View File
@@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}");
assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke");
}
/// What a click at (`x`, 100) with `opt` hits.
fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option<NodeId> {
vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf)
}
/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square.
fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) {
square(s);
let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap());
run(s, "select.set", json!({"ids": [inner.0]}));
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
run(s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(s, id).appearance.items.len() - 1;
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
(id, row)
}
/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance
/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the
/// instance, in a symbol placed inside another symbol too.
#[test]
fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() {
for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] {
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", fill);
offset_row(&mut s, id, row, 10.0);
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
let r = render(&s);
assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100));
assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100));
}
// An effect of the instance's own reshapes the art as well.
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
offset_row(&mut s, id, row, 10.0);
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100));
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100));
}
/// A click where the effect on a symbol instance's fill or stroke paints its art outside the
/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by
/// Path Only and outline mode do not.
#[test]
fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
assert_eq!(hit_at(&s, 44.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill");
assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance");
assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill");
assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out");
assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "outline mode draws the art as it is");
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", false);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke");
assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill");
assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke");
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art");
// A path in the art with an Offset Path of its own: both offsets grow what it draws.
let mut s = session();
let art = square(&mut s);
run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art");
}
/// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what
@@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}");
assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill");
let before = render(&s);
run(&mut s, "effect.expandAppearance", json!({}));
@@ -292,6 +387,181 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
}
/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115;
/// the fill's shape is 9 pt larger on each side.
fn image_with_shaped_fill(s: &mut Session) -> NodeId {
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
let im = NodeId(r["ids"][0].as_u64().unwrap());
run(s, "select.set", json!({"ids": [im.0]}));
run(s, "appearance.addFill", json!({}));
run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
im
}
/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in
/// outline with `outline`.
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false)
}
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
/// art outside its box, as a click there selects it, except in outline.
#[test]
fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
assert_eq!(marquee_at(&s, 38.0, 45.0, false), []);
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill");
assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill");
assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is");
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", false);
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke");
assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill");
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art");
}
/// A marquee touches an image where the shape of its own fill lies outside its frame, and an
/// instance of a symbol made of that image where the instance's fill effect grows that shape, as
/// clicks there select them, except in outline.
#[test]
fn a_marquee_on_the_shape_of_an_image_fill_selects_it() {
let mut s = session();
let im = image_with_shaped_fill(&mut s);
assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame");
assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape");
assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame");
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill");
assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill");
}
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
/// effect grows what that fill paints, and a click there selects the instance.
#[test]
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
let mut s = session();
image_with_shaped_fill(&mut s);
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 70.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100));
assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill");
assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill");
}
/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect
/// grows the result, and a click past both shapes where only the subtracted shape would grow does
/// not select the instance.
#[test]
fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() {
let mut s = session();
// The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80.
let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"weight": 4}));
let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 45.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100));
assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100));
assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill");
assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow");
}
/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a
/// click where only its original shapes would grow does not select the instance.
#[test]
fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
assert!(node(&s, g).extras().shaper.is_some());
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 57.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape");
}
/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the
/// instance's stroke effect moves what that stroke paints, and a click selects the instance where
/// the canvas draws the moved stroke, not inside the original shapes.
#[test]
fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble removes the front rectangle's face; the group's stroke outlines both rectangles.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
let stroke = node(&s, g).appearance.items.len() - 1;
run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4}));
run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1}));
assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row");
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape");
}
/// Of several fills, only the topmost one's effects reach the art, and only while it is visible.
#[test]
fn only_the_topmost_visible_instance_fill_reshapes_the_art() {
+18
View File
@@ -454,6 +454,24 @@ fn a_stroke_weight_change_leaves_each_members_own_fill_and_stroke_colour() {
assert_eq!((fill(&s, a), fill(&s, c)), (a_fill, c_fill));
}
#[test]
fn a_brush_change_clears_each_members_own_brush_settings_and_other_changes_keep_them() {
let mut s = session();
let [a, b, c, ..] = squares(&mut s);
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0, c.0]})).unwrap();
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 50}})).unwrap();
let own = |s: &Session, id: NodeId| Value::Object(node(s, id).appearance.stroke().unwrap().brush_options.clone());
assert_eq!(own(&s, b), json!({"width": 50.0}));
start(&mut s, a, json!({}));
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
assert_eq!(own(&s, b), json!({"width": 50.0}), "a weight change keeps the copy's own settings");
s.execute("brush.apply", &json!({"name": "Diamonds"})).unwrap();
for id in [a, b, c] {
assert_eq!(node(&s, id).appearance.stroke().unwrap().brush.as_deref(), Some("Diamonds"));
assert_eq!(own(&s, id), json!({}), "the settings for the old brush go with it");
}
}
#[test]
fn a_fill_colour_change_reaches_the_fills_and_not_the_strokes() {
let mut s = session();
+264
View File
@@ -146,6 +146,31 @@ fn type_tool_inserts_at_its_caret_and_deletes_the_graphic_whole() {
assert_eq!(inline_count(&obj(&s, id)), 1);
}
/// With Performance › Real-time Drawing and Editing off, the typing waits for its session to end:
/// a graphic inserted while typing applies it first, as a step of its own, and goes in at the
/// caret after it.
#[test]
fn inserting_while_deferred_typing_keeps_the_typing() {
let mut s = session();
s.prefs.real_time_drawing = false;
// The new type starts empty: the caret after "Pay " is past the end of the text until the
// typing is applied.
s.prefs.placeholder_text = false;
circle_symbol(&mut s, "Mana", 10.0);
s.execute("symbol.setCurrent", &json!({"name": "Mana"})).unwrap();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap();
}
let id = s.doc().unwrap().selection.objects[0];
s.tool_text("Pay ", v).unwrap();
s.execute("text.insertInline", &json!({})).unwrap();
assert_eq!(obj(&s, id).plain_text(), format!("Pay {INLINE_CHAR}"));
let labels: Vec<String> = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect();
assert_eq!(labels[labels.len() - 2..], ["Typing", "Insert Inline Symbol"], "{labels:?}");
}
#[test]
fn inline_graphics_follow_their_symbol() {
let mut s = session();
@@ -504,6 +529,245 @@ fn saved_documents_keep_inline_graphics() {
assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds);
}
/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns
/// the ids of each group's rectangles.
fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec<Vec<NodeId>> {
s.edit("Rectangles", |d, _| {
let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut ids = vec![];
let mut made = vec![];
for g in 0..groups {
let kids: Vec<Arc<Node>> = (0..each)
.map(|i| {
let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone()))
})
.collect();
ids.push(kids.iter().map(|k| k.id).collect());
made.push(Arc::new(Node::group(d.alloc_id(), kids)));
}
match Arc::make_mut(&mut d.layers[0]).children_mut() {
Some(kids) => kids.extend(made),
None => panic!("the first layer holds art"),
}
Ok(ids)
})
.unwrap()
}
/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on
/// `fast`; checks that both leave the same document and that each refresh returned the same changed
/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees.
fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec<bool> {
let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut()));
take();
cmd::inline::FULL_PASS.set(true);
step(full);
cmd::inline::FULL_PASS.set(false);
let want = take();
step(fast);
let got = take();
assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc);
let ids = |passes: &[(bool, Vec<NodeId>)]| passes.iter().map(|(_, ids)| ids.clone()).collect::<Vec<_>>();
assert_eq!(ids(&got), ids(&want));
assert!(want.iter().all(|(partial, _)| !partial));
got.iter().map(|(partial, _)| *partial).collect()
}
/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and
/// the document and the changed texts are those of the full pass; a change to a symbol's art, its
/// natural size or anything else a symbol is measured with checks them all.
#[test]
fn refreshing_only_changed_trees_matches_the_full_pass() {
let setup = |s: &mut Session| {
circle_symbol(s, "Tap", 10.0);
circle_symbol(s, "Dot", 6.0);
let groups = rect_groups(s, 20, 10);
let id = text(s, "Tap here");
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap();
// Type showing Dot inline becomes the opacity mask of a rectangle.
let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone();
let mask = text(s, "Dot");
s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap();
(groups, id)
};
let (mut full, mut fast) = (session(), session());
let (groups, id) = setup(&mut full);
assert_eq!(setup(&mut fast), (groups.clone(), id));
let rect = groups[3][4].0;
let len = obj(&fast, id).plain_text().len();
let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p);
let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p);
// A rectangle beside 19 unchanged groups moves.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
});
assert!(only_changed(&passes), "{passes:?}");
// Type with an inline graphic is edited, gets a second one, and loses it again.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap();
s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap();
s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap();
});
assert!(only_changed(&passes), "{passes:?}");
// Dot's art is redefined: the type in the opacity mask follows it.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot"));
assert!(passes.contains(&false), "{passes:?}");
// Tap's natural size changes, its art unchanged.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.edit("Size", |d, _| {
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] }));
Ok(())
})
.unwrap();
});
assert!(all(&passes), "{passes:?}");
let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap"));
assert!(b.is_some() && b == want, "{b:?} {want:?}");
// 9-slice guides for Tap, its art unchanged.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap();
});
assert!(all(&passes), "{passes:?}");
// Symbol editing mode, entered and left, a rectangle moved inside it.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();
s.execute("symbol.exitEditing", &json!({})).unwrap();
});
// Undo and redo, then edits after them.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap();
});
// Fonts scanned again, then another move.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("text.rescanFonts", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap();
});
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
}
/// The time `f` takes in milliseconds: this thread's CPU time where Linux reports it, otherwise the
/// wall clock.
fn time_ms(f: impl FnOnce()) -> f64 {
let d = match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
};
d.as_secs_f64() * 1000.0
}
/// The median, fastest and slowest of `runs`, as text.
fn spread(runs: &mut [f64]) -> String {
runs.sort_by(f64::total_cmp);
format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1])
}
/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with
/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100
/// groups, with three symbols and one line of type showing one of them inline: the refresh alone,
/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going
/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on
/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn inline_refresh_perf() {
const RUNS: usize = 7;
eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)");
for n in [5_000, 50_000, 200_000] {
let mut s = session();
for name in ["A", "B", "C"] {
circle_symbol(&mut s, name, 10.0);
}
let groups = rect_groups(&mut s, 100, n / 100);
let id = text(&mut s, "Type");
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap();
let rect = groups[50][7];
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap();
// The refresh alone, after the same move made on a copy of the resolved document.
let resolved = s.doc().unwrap().inline_resolved.clone().unwrap();
let before = resolved.0.clone();
// The rectangle and the group and layer above it become new nodes, as a move makes them.
let mut after = (*before).clone();
assert!(after.node_mut(rect).is_some());
// Each run times EACH refreshes, or EACH commands, and gives the time of one.
const EACH: usize = 20;
let (mut full, mut partial) = (vec![], vec![]);
for run in 0..RUNS {
let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]);
let mut go_full = || {
cmd::inline::FULL_PASS.set(true);
full.push(
time_ms(|| {
for d in &mut a {
cmd::inline::refresh(Some(&resolved), &before, d);
}
}) / EACH as f64,
);
cmd::inline::FULL_PASS.set(false);
};
let mut go_partial = || {
partial.push(
time_ms(|| {
for d in &mut b {
cmd::inline::refresh(Some(&resolved), &before, d);
}
}) / EACH as f64,
);
};
if run % 2 == 0 {
go_full();
go_partial();
} else {
go_partial();
go_full();
}
assert_eq!(a, b);
}
eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial));
// The whole command, moving the rectangle back and forth.
let (mut full, mut partial) = (vec![], vec![]);
for run in 0..2 * RUNS {
let take_full = (run / 2) % 2 == run % 2;
cmd::inline::FULL_PASS.set(take_full);
let ms = time_ms(|| {
for i in 0..EACH {
let dx = if i % 2 == 0 { -1 } else { 1 };
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
}
}) / EACH as f64;
cmd::inline::FULL_PASS.set(false);
if take_full { full.push(ms) } else { partial.push(ms) }
}
eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial));
cmd::inline::PASSES.with(|p| p.borrow_mut().clear());
}
}
#[test]
fn create_outlines_turns_inline_graphics_into_symbol_instances() {
let mut s = session();
@@ -0,0 +1,522 @@
//! #7832: General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`).
//! With it on, a Direct Selection drag or an arrow-key nudge of selected anchors re-maps the
//! handles of each segment with one moved end, so the segment keeps its shape relative to its
//! ends. Off (the default), the handles of a moved anchor move with it and the others stay.
use serde_json::json;
use vectorcraft_geom::{Anchor, PathData, Point};
use vectorcraft_tools::{PointerEvent, PointerKind};
use super::history;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn interpolate(s: &mut Session, on: bool) {
s.execute("prefs.set", &json!({"key": "interpolateControlPoints", "value": on})).unwrap();
}
fn path_of(s: &Session, id: NodeId) -> PathData {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
}
fn anchor(s: &Session, id: NodeId, ai: usize) -> Anchor {
path_of(s, id).subpaths[0].anchors[ai]
}
fn create(s: &mut Session, anchors: serde_json::Value) -> NodeId {
NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap())
}
/// A curve from (100, 100) to (300, 100) whose handles lie on its chord.
fn curve(s: &mut Session) -> NodeId {
create(s, json!([{"x": 100, "y": 100, "out": [150, 100]}, {"x": 300, "y": 100, "in": [250, 100]}]))
}
fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value) {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": "set"})).unwrap();
}
/// A Direct Selection click on (`x`, `y`), then a drag from there to (`to_x`, `to_y`).
fn drag(s: &mut Session, (x, y): (f64, f64), (to_x, to_y): (f64, f64)) {
let v = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("directSelection", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to_x, to_y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to_x, to_y), v).unwrap();
}
#[test]
fn the_preference_is_off_by_default_and_the_handles_then_move_rigidly() {
let mut s = session();
assert!(!s.prefs.interpolate_control_points);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0));
assert_eq!(a.h_out, Point::new(170.0, 108.0), "the moved anchor's handle moves with it");
assert_eq!(b.h_in, Point::new(250.0, 100.0), "the other end's handle stays");
}
#[test]
fn a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let before = history(&s).0;
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
assert_eq!(history(&s).0, before + 1, "one undo step");
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
// The chord goes from (200, 0) to (180, -8): a scale by 0.9 and a turn, so the handles a
// quarter of the way from each end stay on the new chord, a quarter of the way along it.
assert_eq!(a.p, Point::new(120.0, 108.0));
assert_eq!(a.h_in, a.p, "a retracted handle stays retracted");
assert_eq!(a.h_out, Point::new(165.0, 106.0));
assert_eq!(b.p, Point::new(300.0, 100.0));
assert_eq!(b.h_in, Point::new(255.0, 102.0));
assert_eq!(b.h_out, b.p);
}
#[test]
fn a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
let original = path_of(&s, id);
drag(&mut s, (100.0, 100.0), (120.0, 108.0));
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0));
assert_eq!(a.h_out, Point::new(165.0, 106.0));
assert_eq!(b.h_in, Point::new(255.0, 102.0));
// One undo step puts the path back as it was before the drag.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id), original);
}
#[test]
fn a_direct_selection_drag_with_the_preference_off_keeps_the_rigid_move() {
let mut s = session();
let id = curve(&mut s);
drag(&mut s, (100.0, 100.0), (120.0, 108.0));
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.h_out, Point::new(170.0, 108.0));
assert_eq!(b.h_in, Point::new(250.0, 100.0));
}
#[test]
fn a_segment_with_both_ends_moved_moves_rigidly() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 60]},
{"x": 300, "y": 100, "in": [250, 60], "out": [350, 150]},
{"x": 500, "y": 100, "in": [450, 140]},
]),
);
select(&mut s, id, json!([[0, 0], [0, 1]]));
s.execute("object.nudge", &json!({"dx": 10, "dy": 5})).unwrap();
let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2));
assert_eq!((a.p, a.h_out), (Point::new(110.0, 105.0), Point::new(160.0, 65.0)));
assert_eq!((b.p, b.h_in), (Point::new(310.0, 105.0), Point::new(260.0, 65.0)));
// The segment to the unmoved third anchor is re-mapped: its chord goes from (200, 0) to
// (190, -5), a scale by 0.95 with a turn of -0.025 per unit.
close(b.h_out, Point::new(358.75, 151.25));
close(c.h_in, Point::new(453.5, 139.25));
assert_eq!(c.p, Point::new(500.0, 100.0));
}
fn close(p: Point, q: Point) {
assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} is not {q:?}");
}
/// A closed square from (100, 100) to (300, 300) whose handles lie on its sides, a quarter of
/// the way along.
fn square(s: &mut Session) -> NodeId {
let anchors = json!([
{"x": 100, "y": 100, "in": [100, 150], "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [300, 150]},
{"x": 300, "y": 300, "in": [300, 250], "out": [250, 300]},
{"x": 100, "y": 300, "in": [150, 300], "out": [100, 250]},
]);
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap())
}
#[test]
fn moving_the_first_anchor_of_a_closed_path_re_maps_the_closing_segment_too() {
let mut s = session();
interpolate(&mut s, true);
let id = square(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": -200})).unwrap();
let (a, b, c, d) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2), anchor(&s, id, 3));
assert_eq!(a.p, Point::new(100.0, -100.0));
// The segment to the second anchor: its chord goes from (200, 0) to (200, 200).
close(a.h_out, Point::new(150.0, -50.0));
close(b.h_in, Point::new(250.0, 50.0));
// The closing segment from the fourth anchor: its chord goes from (0, -200) to (0, -400).
close(d.h_out, Point::new(100.0, 200.0));
close(a.h_in, Point::new(100.0, 0.0));
// The segment between the third and fourth anchors is not beside the moved anchor.
assert_eq!((c.h_out, d.h_in), (Point::new(250.0, 300.0), Point::new(150.0, 300.0)));
assert_eq!((b.h_out, c.h_in), (Point::new(300.0, 150.0), Point::new(300.0, 250.0)));
}
#[test]
fn moving_the_last_anchor_of_an_open_path_re_maps_only_the_segment_before_it() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 50]},
{"x": 500, "y": 100, "in": [450, 100], "out": [550, 50]},
]),
);
select(&mut s, id, json!([[0, 2]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": 200})).unwrap();
let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2));
assert_eq!(c.p, Point::new(500.0, 300.0));
// The chord from the second (corner) anchor goes from (200, 0) to (200, 200).
close(b.h_out, Point::new(400.0, 100.0));
close(c.h_in, Point::new(450.0, 250.0));
// The last anchor's own outgoing handle leads to no segment and moves with it.
assert_eq!(c.h_out, Point::new(550.0, 250.0));
assert_eq!((a.h_out, b.h_in), (Point::new(150.0, 100.0), Point::new(250.0, 100.0)));
}
#[test]
fn move_and_transform_of_anchors_re_map_the_handles_in_one_undo_step() {
for (cmd, params) in [("object.move", json!({"dx": 20, "dy": 8})), ("object.transform", json!({"matrix": [1, 0, 0, 1, 20, 8], "anchors": true}))]
{
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let (before, original) = (history(&s).0, path_of(&s, id));
s.execute(cmd, &params).unwrap();
assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step");
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}");
close(a.h_out, Point::new(165.0, 106.0));
close(b.h_in, Point::new(255.0, 102.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id), original, "{cmd}: undone");
}
}
#[test]
fn set_bounds_and_guide_move_of_anchors_follow_the_preference_and_the_param() {
for (pref, param, re_mapped) in [(false, None, false), (true, None, true), (true, Some(false), false), (false, Some(true), true)] {
for cmd in ["object.setBounds", "guide.move"] {
let mut s = session();
interpolate(&mut s, pref);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let mut params = if cmd == "object.setBounds" {
json!({"x": 120, "y": 108})
} else {
let g = s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap()["index"].as_u64().unwrap();
s.execute("guide.select", &json!({"indexes": [g], "toggle": true})).unwrap();
json!({"dx": 20, "dy": 8})
};
if let Some(on) = param {
params["interpolate"] = json!(on);
}
let (before, original) = (history(&s).0, path_of(&s, id));
s.execute(cmd, &params).unwrap();
assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step");
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}");
if re_mapped {
close(a.h_out, Point::new(165.0, 106.0));
close(b.h_in, Point::new(255.0, 102.0));
} else {
assert_eq!((a.h_out, b.h_in), (Point::new(170.0, 108.0), Point::new(250.0, 100.0)), "{cmd}, pref {pref}, param {param:?}");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id), original, "{cmd}: undone");
}
}
let mut s = session();
let id = curve(&mut s);
// Both anchors, so that a new width scales them and does not only move them.
select(&mut s, id, json!([[0, 0], [0, 1]]));
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
let original = path_of(&s, id);
for (cmd, params) in [
("object.setBounds", json!({"x": 120, "interpolate": "yes"})),
("object.setBounds", json!({"width": 50, "interpolate": 1})),
("guide.move", json!({"dx": 1, "interpolate": "yes"})),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}");
}
assert_eq!(path_of(&s, id), original);
// With only guides selected, guide.move rejects the value too and leaves the guide.
s.execute("select.none", &json!({})).unwrap();
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
let e = s.execute("guide.move", &json!({"dx": 1, "interpolate": "yes"})).unwrap_err().to_string();
assert!(e.contains("`interpolate` must be true or false"), "guide.move: {e}");
assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 50.0);
}
#[test]
fn the_interpolate_param_overrides_the_preference_and_rejects_other_values() {
for (pref, param, re_mapped) in [(true, false, false), (false, true, true)] {
let mut s = session();
interpolate(&mut s, pref);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("path.moveAnchors", &json!({"dx": 20, "dy": 8, "interpolate": param})).unwrap();
let b = anchor(&s, id, 1);
assert_eq!(b.h_in != Point::new(250.0, 100.0), re_mapped, "pref {pref}, param {param}: {:?}", b.h_in);
}
let mut s = session();
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let original = path_of(&s, id);
for (cmd, params) in [
("path.moveAnchors", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
("object.nudge", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
("object.move", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
("object.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "anchors": true, "interpolate": 1})),
("object.transformAgain", json!({"interpolate": "yes"})),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}");
}
assert_eq!(path_of(&s, id), original);
}
#[test]
fn a_replayed_move_re_maps_the_handles_as_it_did_whatever_the_preference_is_then() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let start = s.journal.len();
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
let moved = path_of(&s, id);
let (cmd, params) = s.journal.since(start).last().cloned().unwrap();
assert_eq!(params["interpolate"], json!(true), "{cmd}: journaled");
// Undo, turn the preference off and play the journal entry again.
s.execute("edit.undo", &json!({})).unwrap();
interpolate(&mut s, false);
select(&mut s, id, json!([[0, 0]]));
s.replay(&cmd, &params).unwrap();
assert_eq!(path_of(&s, id), moved);
}
#[test]
fn a_saved_step_without_interpolate_moves_the_handles_rigidly_whatever_the_preference() {
// A step recorded before the preference existed has no `interpolate`; with the preference on,
// it still plays as it did when it was recorded.
for cmd in ["path.moveAnchors", "object.nudge", "object.move"] {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.replay(cmd, &json!({"dx": 1, "dy": 1})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_ne!(a.p, Point::new(100.0, 100.0), "{cmd}: the anchor moves");
assert_eq!((a.h_out.x - a.p.x, a.h_out.y - a.p.y), (50.0, 0.0), "{cmd}: the moved anchor's handle moves with it");
assert_eq!(b.h_in, Point::new(250.0, 100.0), "{cmd}: the other end's handle stays");
// Run directly, the same params follow the preference.
s.execute(cmd, &json!({"dx": 1, "dy": 1})).unwrap();
assert_ne!(anchor(&s, id, 1).h_in, Point::new(250.0, 100.0), "{cmd}: executed, the handles are re-mapped");
}
}
#[test]
fn transform_again_keeps_the_setting_its_move_used() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
interpolate(&mut s, false);
s.execute("object.transformAgain", &json!({})).unwrap();
let mut t = session();
interpolate(&mut t, true);
let other = curve(&mut t);
select(&mut t, other, json!([[0, 0]]));
t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
assert_eq!(path_of(&s, id), path_of(&t, other));
}
#[test]
fn a_segment_whose_ends_are_at_the_same_place_moves_rigidly() {
let mut s = session();
interpolate(&mut s, true);
let id = create(&mut s, json!([{"x": 100, "y": 100, "out": [150, 50]}, {"x": 100, "y": 100, "in": [50, 150]}]));
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 10, "dy": 0})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!((a.p, a.h_out), (Point::new(110.0, 100.0), Point::new(160.0, 50.0)));
assert_eq!((b.p, b.h_in), (Point::new(100.0, 100.0), Point::new(50.0, 150.0)));
}
#[test]
fn a_move_onto_the_other_end_moves_the_handles_rigidly() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 200, "dy": 0})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!((a.p, a.h_out), (Point::new(300.0, 100.0), Point::new(350.0, 100.0)));
assert_eq!(b.h_in, Point::new(250.0, 100.0));
}
#[test]
fn a_nudge_of_zero_with_the_preference_on_records_no_undo_step() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let (before, original) = (history(&s), path_of(&s, id));
s.execute("object.nudge", &json!({"dx": 0, "dy": 0})).unwrap();
assert_eq!(history(&s), before);
assert_eq!(path_of(&s, id), original);
}
#[test]
fn a_smooth_anchor_keeps_its_handles_in_line() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
{"x": 500, "y": 100, "in": [450, 100]},
]),
);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap();
let b = anchor(&s, id, 1);
assert_eq!(b.p, Point::new(300.0, 100.0));
// The segment to the third anchor did not move, so its handle stays where it was.
assert_eq!(b.h_out, Point::new(350.0, 100.0));
// The incoming handle grows with the chord from the moved anchor (from 200 to 100√5) and
// turns back in line with the outgoing one.
assert_eq!(b.h_in.y, 100.0, "in line: {:?}", b.h_in);
assert!((300.0 - b.h_in.x - 25.0 * 5f64.sqrt()).abs() < 1e-9, "{:?}", b.h_in);
}
#[test]
fn a_moved_smooth_anchor_keeps_a_retracted_handle_exactly_retracted() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 0, "y": 100, "out": [50, 100]},
{"x": 200, "y": 100, "in": [200, 100], "out": [250, 150], "smooth": true},
{"x": 400, "y": 100, "in": [350, 100]},
]),
);
select(&mut s, id, json!([[0, 1]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8.1})).unwrap();
let b = anchor(&s, id, 1);
assert_eq!(b.p, Point::new(220.0, 108.1));
// Re-mapping the retracted handle by its segment's map would leave it a rounding error away
// from the anchor, and lining the handles up would then turn the outgoing one by that error.
assert_eq!(b.h_in, b.p, "the retracted handle stays retracted");
// The chord to the third anchor goes from (200, 0) to (180, -8.1).
close(b.h_out, Point::new(267.025, 151.075));
}
#[test]
fn transform_again_repeats_a_move_with_the_handles_re_mapped() {
let twice = |again: bool| {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
if again {
s.execute("object.transformAgain", &json!({})).unwrap();
} else {
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
}
path_of(&s, id)
};
let (repeated, nudged) = (twice(true), twice(false));
assert_eq!(repeated.subpaths[0].anchors[0].p, Point::new(140.0, 116.0));
assert_eq!(repeated, nudged);
}
#[test]
fn a_transform_that_scales_by_a_hair_still_scales_the_anchors() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let k = 1.000_000_000_5;
s.execute("object.transform", &json!({"matrix": [k, 0, 0, 1, 0, 0], "anchors": true})).unwrap();
let a = anchor(&s, id, 0);
assert_eq!(a.p, Point::new(100.0 * k, 100.0));
assert_eq!(a.h_out, Point::new(150.0 * k, 100.0));
}
#[test]
fn a_smooth_anchor_whose_re_mapped_handles_point_the_same_way_moves_them_with_it() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
{"x": 500, "y": 100, "in": [450, 100]},
]),
);
select(&mut s, id, json!([[0, 1]]));
s.execute("object.nudge", &json!({"dx": 300, "dy": 0})).unwrap();
// Both chords re-map their handle to the left of the anchor, which has no direction between
// them: both handles move with the anchor, as with the preference off.
let b = anchor(&s, id, 1);
assert_eq!(b.p, Point::new(600.0, 100.0));
assert_eq!(b.h_out, Point::new(650.0, 100.0));
assert_eq!(b.h_in, Point::new(550.0, 100.0));
}
#[test]
fn a_smooth_anchor_between_two_re_mapped_segments_keeps_its_handles_in_line() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
{"x": 500, "y": 100, "in": [450, 100]},
]),
);
select(&mut s, id, json!([[0, 1]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap();
let b = anchor(&s, id, 1);
let (v_in, v_out) = (b.h_in - b.p, b.h_out - b.p);
assert_eq!(b.p, Point::new(300.0, 0.0));
// The two chords turn by the same angle in opposite directions, so the handles point along
// the mean of the two: across, at the length each chord gives them.
assert!(v_in.cross(v_out).abs() < 1e-9, "the handles stay in line: {:?} {:?}", b.h_in, b.h_out);
assert!(v_in.dot(v_out) < 0.0, "on opposite sides of the anchor");
assert!(v_out.y.abs() < 1e-9 && v_out.x > 0.0, "{:?}", b.h_out);
assert!((v_out.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9 && (v_in.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9);
}
+230
View File
@@ -390,6 +390,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() {
assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]);
}
/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty
/// third layer `e`.
#[derive(Clone, Copy)]
struct Column {
layer: NodeId,
sub: NodeId,
a: NodeId,
g: NodeId,
b: NodeId,
c: NodeId,
o: NodeId,
e: NodeId,
}
fn column_start() -> (Session, Column) {
let mut s = session();
let (layer, sub, a, g, b, c) = tree(&mut s);
run(&mut s, "layer.setCurrent", json!({"id": layer.0}));
let other = id(&run(&mut s, "layer.new", json!({})));
let o = rect(&mut s, 200.0);
let e = id(&run(&mut s, "layer.new", json!({})));
run(&mut s, "select.none", json!({}));
let top: Vec<NodeId> = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect();
assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}");
(s, Column { layer, sub, a, g, b, c, o, e })
}
type Prep = dyn Fn(&mut Session, Column);
/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the
/// same selection, reply, current layer, highlighted rows and revision as removing or adding each
/// id of `art` one at a time. Returns the session the click ran in.
fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec<NodeId>) -> (Session, Column) {
let (mut new, t) = column_start();
prep(&mut new, t);
let row = row(t);
let before = new.doc().unwrap().selection.clone();
let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true}));
let (mut old, t) = column_start();
prep(&mut old, t);
let ids = art(t);
let st = old.doc().unwrap();
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let rows = st.layer_rows.clone();
old.select(|_, sel| {
for i in &ids {
if all_selected { sel.remove(*i) } else { sel.add(*i) }
}
})
.unwrap();
old.doc_mut().unwrap().layer_rows = rows;
let (n, o) = (new.doc().unwrap(), old.doc().unwrap());
assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}");
assert_eq!(ids_sel(&reply), o.selection.objects);
assert_eq!(n.active_layer, o.active_layer);
assert_eq!(n.highlighted_rows(), o.highlighted_rows());
assert_eq!(n.revision, o.revision);
assert_eq!(undos(&new), undos(&old));
(new, t)
}
#[test]
fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() {
// `o` outside the layer is selected first and is the key object and the target; `a` is
// selected by one anchor, which is the key anchor.
let partly: &Prep = &|s, t| {
run(s, "layer.setCurrent", json!({"id": t.sub.0}));
let sel = &mut s.doc_mut().unwrap().selection;
sel.objects = vec![t.o, t.a];
sel.anchors.insert(t.a, [(0, 1)].into());
sel.key = Some(t.o);
sel.key_anchor = Some((t.a, (0, 1)));
sel.target = Some(t.o);
};
let layer_art = |t: Column| vec![t.c, t.a, t.g];
// Some of the layer's art is selected: the rest is added after what was selected.
let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]);
assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked");
assert!(sel.target.is_none());
// All of it is selected, `a` as the key object: it is removed, with its anchors, key and key
// anchor.
let all: &Prep = &|s, t| {
partly(s, t);
let sel = &mut s.doc_mut().unwrap().selection;
sel.objects.extend([t.c, t.g]);
sel.key = Some(t.a);
};
let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![t.o]);
assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none());
// An object row, a group row and an empty layer's row.
shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]);
shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]);
shift_column_matches_each_id(partly, |t| t.e, |_| vec![]);
// A locked sublayer's row, and rows outside and inside the isolated group.
let locked: &Prep = &|s, t| {
partly(s, t);
run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true}));
};
shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]);
let isolated: &Prep = &|s, t| {
partly(s, t);
s.doc_mut().unwrap().isolation = Some(t.g);
};
shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]);
shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]);
}
fn ids_sel(v: &Value) -> Vec<NodeId> {
v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
@@ -658,6 +769,54 @@ fn new_layers_go_below_the_current_one_and_sublayers_under_the_contents() {
assert_eq!(children(&s, layer), vec![front, under, back]);
}
/// In Draw Behind a new layer goes directly below the current layer, at its level, in one undo
/// step; `top` and `below` keep their meaning, Draw Inside and Draw Normal keep it above, and new
/// sublayers are not affected.
#[test]
fn new_layers_go_below_the_current_one_in_draw_behind() {
let mut s = session();
let (layer, sub, a, g, _, c) = tree(&mut s);
run(&mut s, "view.drawMode", json!({"mode": "behind"}));
run(&mut s, "layer.setCurrent", json!({"id": sub.0}));
let before = undos(&s);
let n = id(&run(&mut s, "layer.new", json!({})));
assert_eq!(children(&s, layer), vec![c, n, sub], "a sublayer directly below the current sublayer");
assert_eq!(undos(&s), before + 1);
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![n]);
assert_eq!(s.doc().unwrap().current_layer(), Some(n));
run(&mut s, "edit.undo", json!({}));
assert_eq!(children(&s, layer), vec![c, sub]);
// The Create New Layer button sends `top: false` for a plain click: still below.
run(&mut s, "layer.setCurrent", json!({"id": sub.0}));
let n = id(&run(&mut s, "layer.new", json!({"top": false})));
assert_eq!(children(&s, layer), vec![c, n, sub]);
run(&mut s, "edit.undo", json!({}));
// At the top level, and with options.
run(&mut s, "layer.setCurrent", json!({"id": layer.0}));
let back = id(&run(&mut s, "layer.new", json!({"name": "Back", "locked": true})));
let order = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
assert_eq!(order(&s), vec![back, layer]);
assert!(node(&s, back).locked);
// `top` and `below` win over the drawing mode.
let top = id(&run(&mut s, "layer.new", json!({"top": true})));
assert_eq!(order(&s), vec![back, layer, top]);
let below = id(&run(&mut s, "layer.new", json!({"below": true})));
assert_eq!(order(&s), vec![back, layer, below, top]);
assert!(s.execute("layer.new", &json!({"top": true, "below": true})).is_err());
// New sublayers still go on top of the parent's contents.
let inner = id(&run(&mut s, "layer.newSublayer", json!({"parent": sub.0})));
assert_eq!(children(&s, sub), vec![a, g, inner]);
// Draw Inside and Draw Normal put it above.
run(&mut s, "select.set", json!({"ids": [c.0]}));
for mode in ["inside", "normal"] {
run(&mut s, "view.drawMode", json!({"mode": mode}));
assert_eq!(s.draw_mode, if mode == "inside" { DrawMode::Inside } else { DrawMode::Normal });
run(&mut s, "layer.setCurrent", json!({"id": back.0}));
let n = id(&run(&mut s, "layer.new", json!({})));
assert_eq!(s.doc().unwrap().doc.layers[1].id, n, "{mode}");
}
}
#[test]
fn rows_move_above_below_and_into_layers_and_groups() {
let mut s = session();
@@ -820,6 +979,45 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() {
assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected");
}
/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up
/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still
/// refused.
#[test]
fn a_copy_goes_above_or_below_a_row_it_copies() {
let mut s = session();
let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [only] = layers(&s)[..] else { panic!("one layer") };
for place in ["above", "below", "inside"] {
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself");
}
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err());
assert_eq!(layers(&s), vec![only], "nothing changed");
let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true})));
assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original");
let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true})));
assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it");
run(&mut s, "edit.undo", json!({}));
assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step");
}
/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a
/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused,
/// and nothing changes.
#[test]
fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() {
let mut s = session();
let bottom = s.doc().unwrap().doc.layers[0].id;
let other = id(&run(&mut s, "layer.new", json!({})));
let r = rect(&mut s, 0.0);
assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer");
let count = s.doc().unwrap().doc.node_count();
for place in ["above", "below"] {
let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true});
assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it");
}
assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied");
}
/// The selected art in rows dragged into a hidden layer or group is deselected, the key object
/// included. Undo puts the rows back and selects the art again.
#[test]
@@ -1081,6 +1279,38 @@ fn locate_object_highlights_its_row() {
assert!(s.execute("layer.locate", &json!({})).is_err());
}
/// 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]
fn locate_layer_highlights_the_layer_holding_the_object() {
let mut s = session();
let (layer, sub, _, g, b, c) = tree(&mut s);
run(&mut s, "select.set", json!({"ids": [b.0]}));
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
s.doc_mut().unwrap().locate_reveal = None;
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true}));
assert_eq!((r["id"].clone(), r["objectId"].clone()), (json!(sub.0), json!(sub.0)), "a sublayer locates itself");
// Off, the object's own row is highlighted, as before.
assert_eq!(run(&mut s, "layer.locate", json!({"id": g.0, "layersOnly": false})), json!({"id": g.0, "ancestry": [layer.0, sub.0, g.0]}));
// Bad input changes nothing.
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
}
run(&mut s, "select.none", json!({}));
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
}
#[test]
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
let mut s = session();
+221
View File
@@ -2377,6 +2377,227 @@ fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_ro
every(&mut s, true, Some(&inside));
}
/// The native document a file of `format` carries: the file itself, a PDF's or `.ai` file's
/// editing data, or an EPS file's.
fn carried_document(format: &str, bytes: &[u8]) -> Document {
let native = if bytes.starts_with(b"%PDF") {
vectorcraft_pdf::editing(bytes).expect("editing data").data
} else if format == "eps" {
vectorcraft_eps::native(bytes).expect("native document")
} else {
bytes.to_vec()
};
vectorcraft_format::load(&native).unwrap()
}
/// A confined caller: every output that carries the native document (a native file or template, a
/// `.ai` or EPS file, a PDF with Preserve Editing) of a document that links an image
/// file outside the read roots is refused before a file or folder is written, with an error that
/// names no file or folder, and the document keeps the link.
#[test]
fn confined_native_output_refuses_a_linked_image_file_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("native-image-away");
let home = Folder::new("native-image-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let a = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("assets.add", &json!({"ids": [a.0]})).unwrap();
let own = home.file("own.vectorcraft");
s.execute("file.saveAs", &json!({"path": own})).unwrap();
let before = std::fs::read(&own).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()];
let refused = |s: &mut Session, cmd: &str, p: Value| {
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd);
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
let e = e.to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
for h in &hidden {
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
}
};
let file = |name: &str| home.file(name);
let out = file("out");
refused(&mut s, "document.serialize", json!({}));
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
refused(&mut s, "document.serialize", json!({"format": format}));
refused(&mut s, "document.export", json!({"format": format}));
refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true}));
refused(&mut s, "document.exportSelection", json!({"format": format}));
}
refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")}));
refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")}));
refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")}));
refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")}));
refused(&mut s, "document.exportPdf", json!({}));
refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")}));
refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")}));
refused(&mut s, "document.save", json!({}));
refused(&mut s, "document.save", json!({"path": file("save.pdf")}));
refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")}));
// A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says.
refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false}));
refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")}));
refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")}));
refused(&mut s, "file.saveAsTemplate", json!({}));
refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"}));
refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]}));
refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]}));
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]}));
assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was");
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(written, ["own.vectorcraft"]);
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
}
/// A confined caller's native outputs are refused when the document they carry names a file
/// outside the read roots only as a data set's image, or holds stored brushes that cannot be read.
/// Outputs that carry no native document (a PDF without Preserve Editing, a PDF or `.ai` file of
/// some artboards or of the art's bounds, a legacy `.ai` file, an image, an SVG without Preserve
/// Editing) are written, and so is a native file whose data set image is inside the read roots, or
/// any data set image without roots.
#[test]
fn confined_native_output_refuses_a_data_set_image_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("native-dataset-away");
let home = Folder::new("native-dataset-home");
let outside = away.file("photo.png");
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 100, "height": 100})).unwrap();
let set_image = |s: &mut Session, path: &str| {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect();
doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }];
};
set_image(&mut s, &outside);
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let refused = |s: &mut Session, cmd: &str, p: Value| {
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{cmd} {p}: {e}");
};
let written = |s: &mut Session, p: Value| {
confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap_or_else(|e| panic!("{p}: {e}"));
};
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
refused(&mut s, "document.serialize", json!({"format": format}));
}
refused(&mut s, "document.serialize", json!({"format": "svg", "preserveEditing": true}));
refused(&mut s, "document.exportPdf", json!({}));
for p in [
json!({"format": "pdf", "preserveEditing": false}),
json!({"format": "pdf", "useArtboards": false}),
json!({"format": "pdf", "range": "2"}),
json!({"format": "ai", "artboards": [1]}),
json!({"format": "ai", "useArtboards": false}),
json!({"format": "ai", "aiVersion": "7"}),
json!({"format": "png"}),
json!({"format": "svg"}),
] {
written(&mut s, p);
}
// Without roots, the native document keeps the data set's image as stored.
let r = s.execute("document.serialize", &json!({})).unwrap();
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let carried = carried_document("vectorcraft", &bytes);
assert_eq!(carried.variables.datasets[0].values["Photo"], vectorcraft_doc::DataValue::Image(outside.clone()));
// An image inside the read roots.
set_image(&mut s, &home.file("photo.png"));
written(&mut s, json!({"format": "vectorcraft"}));
// Stored brushes that cannot be read: their links cannot be checked.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert(vectorcraft_brush::DOC_KEY.into(), json!(["not a brush"]));
refused(&mut s, "document.serialize", json!({"format": "vectorcraft"}));
written(&mut s, json!({"format": "png"}));
}
/// A confined caller's Export for Screens rows that write an artboard alone (native, `.ai` and EPS
/// files) are checked against that artboard's document: an image linked outside the read roots
/// on another artboard does not refuse them, and one on the artboard does.
#[test]
fn confined_screens_rows_check_the_artboard_each_file_holds() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("screens-board-away");
let home = Folder::new("screens-board-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
place(&mut s, &photo);
s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2010, "y": 10, "width": 50, "height": 20})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
for format in ["vectorcraft", "ai", "eps"] {
let p = |range: &str| json!({"range": range, "formats": [{"format": format}]});
let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("2"))).unwrap_or_else(|e| panic!("{format}: {e}"));
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{format}: {r}");
let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("1"))).expect_err(format).to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{format}: {e}");
}
}
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
/// Preserve Editing, a package's document) carry the document without the Export for Screens
/// folder when it is outside the read roots, with the other export settings and the art; the open
/// document keeps the folder. A folder inside the roots, and any folder without roots, stays.
#[test]
fn confined_native_output_leaves_out_an_export_folder_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("native-export-folder-away");
let home = Folder::new("native-export-folder-home");
let outside = away.0.to_string_lossy().into_owned();
let inside = home.file("screens");
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
s.execute("file.saveAs", &json!({"path": home.file("own.vectorcraft")})).unwrap();
let set_folder = |s: &mut Session, folder: &str| {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap();
};
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let check = |d: &Document, folder: Option<&str>, what: &str| {
assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}");
assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}");
assert!(d.node(rect).is_some(), "{what}: no art");
};
let package = home.file("package");
let every = |s: &mut Session, confined: bool, folder: Option<&str>| {
let run = |s: &mut Session, cmd: &str, p: Value| {
let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) };
r.unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
};
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
let r = run(s, "document.serialize", json!({"format": format}));
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
check(&carried_document(format, &bytes), folder, &format!("{format} serialize"));
}
let pdf = home.file("direct.pdf");
run(s, "document.exportPdf", json!({"path": pdf}));
check(&carried_document("pdf", &std::fs::read(&pdf).unwrap()), folder, "exportPdf");
let eps = home.file("copy.eps");
run(s, "file.saveCopy", json!({"path": eps}));
check(&carried_document("eps", &std::fs::read(&eps).unwrap()), folder, "eps copy");
let _ = std::fs::remove_dir_all(&package);
run(s, "file.package", json!({"folder": package, "report": false, "copyFonts": false}));
let packaged = std::fs::read(Path::new(&package).join("own Folder").join("own.vectorcraft")).unwrap();
check(&vectorcraft_format::load_file(&packaged).unwrap().doc, folder, "package");
};
set_folder(&mut s, &outside);
every(&mut s, true, None);
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str()));
every(&mut s, false, Some(&outside));
set_folder(&mut s, &inside);
every(&mut s, true, Some(&inside));
}
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
/// written. Any output that names no file is written.
+134
View File
@@ -203,6 +203,140 @@ fn unembed_of_pixels_that_cant_be_read_writes_no_file() {
assert!(image(&s, id).link.is_none());
}
/// The files of folder `dir`, sorted by name.
fn files_in(dir: &str) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
/// The path of the file `name` in folder `dir`.
fn file_in(dir: &str, name: &str) -> String {
std::path::Path::new(dir).join(name).to_string_lossy().into_owned()
}
/// Several images unembed into one folder: each gets a new file named after it (a taken name
/// numbered, a file already there never replaced), links to it and keeps its bounds, linked images
/// are skipped, and one undo step makes them embedded again while the files stay.
#[test]
fn unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step() {
let dir = Folder::new("unembed-folder");
let out = dir.file("out");
for sub in ["a", "b", "out"] {
std::fs::create_dir_all(dir.file(sub)).unwrap();
}
let (red, blue) = (png(60, 30, RED), png(40, 20, BLUE));
write(&dir.file("a/photo.png"), &red);
write(&dir.file("b/photo.png"), &blue);
write(&dir.file("a/linked.png"), &red);
let kept = b"not an image".to_vec();
write(&file_in(&out, "photo.png"), &kept);
let mut s = session();
let a = place_embedded(&mut s, &dir.file("a/photo.png"));
let b = place_embedded(&mut s, &dir.file("b/photo.png"));
let linked = place(&mut s, &dir.file("a/linked.png"));
let linked_path = image(&s, linked).link.unwrap().path;
let (bounds_a, bounds_b) = (bounds(&s, a), bounds(&s, b));
let undo_before = s.doc().unwrap().history.undo.len();
let r = run(&mut s, "links.unembed", json!({"ids": [a.0, linked.0, b.0], "folder": out}));
let (path_a, path_b) = (file_in(&out, "photo 2.png"), file_in(&out, "photo 3.png"));
assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": path_a}, {"id": b.0, "path": path_b}], "skipped": [linked.0]}));
assert_eq!(files_in(&out), ["photo 2.png", "photo 3.png", "photo.png"]);
assert_eq!(std::fs::read(file_in(&out, "photo.png")).unwrap(), kept, "a file already there is not replaced");
assert_eq!(std::fs::read(&path_a).unwrap(), red);
assert_eq!(std::fs::read(&path_b).unwrap(), blue);
assert_eq!(image(&s, a).link.unwrap().path, path_a);
assert_eq!(image(&s, b).link.unwrap().path, path_b);
assert_eq!(image(&s, linked).link.unwrap().path, linked_path, "a linked image is left as it is");
assert_eq!((bounds(&s, a), bounds(&s, b)), (bounds_a, bounds_b));
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "one undo step");
run(&mut s, "edit.undo", json!({}));
assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none(), "both embedded again");
assert_eq!(files_in(&out).len(), 3, "undo leaves the files");
// `ids` of one image without `folder` is `id`: the bytes, and nothing changes.
let one = run(&mut s, "links.unembed", json!({"ids": [a.0]}));
assert_eq!(one, run(&mut s, "links.unembed", json!({"id": a.0})));
assert!(one["dataBase64"].is_string(), "{one}");
assert!(image(&s, a).link.is_none());
// With no ids, the selected embedded images.
s.doc_mut().unwrap().selection.objects = vec![b, linked];
let r = run(&mut s, "links.unembed", json!({"folder": out}));
assert_eq!(r, json!({"unembedded": [{"id": b.0, "path": file_in(&out, "photo 4.png")}], "skipped": []}));
assert_eq!(std::fs::read(file_in(&out, "photo 4.png")).unwrap(), blue);
// `id` with `folder` is `ids` of that one image.
let r = run(&mut s, "links.unembed", json!({"id": a.0, "folder": out}));
assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": file_in(&out, "photo 5.png")}], "skipped": []}));
assert_eq!(image(&s, a).link.unwrap().path, file_in(&out, "photo 5.png"));
}
/// A batch that fails part way writes no file and changes nothing; requests that don't fit the
/// command are refused before anything is written.
#[test]
fn unembed_to_a_folder_that_fails_leaves_no_file_and_no_change() {
let dir = Folder::new("unembed-folder-fail");
let out = dir.file("out");
std::fs::create_dir_all(&out).unwrap();
write(&dir.file("one.png"), &png(60, 30, RED));
write(&dir.file("two.png"), &png(60, 30, BLUE));
let mut s = session();
let a = place_embedded(&mut s, &dir.file("one.png"));
let b = place_embedded(&mut s, &dir.file("two.png"));
// The second image's pixels can't be read: the first one's file is removed again.
let key = image(&s, b).key;
let saved = s.doc().unwrap().doc.images.get(&key).cloned().unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key.clone(), vectorcraft_doc::ImageBlob::png(png_header(60, 30)));
let undo_before = s.doc().unwrap().history.undo.len();
let e = s.execute("links.unembed", &json!({"ids": [a.0, b.0], "folder": out})).unwrap_err();
assert!(e.to_string().ends_with("the image's pixels can't be read"), "{e}");
assert!(files_in(&out).is_empty(), "no file left behind");
assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none());
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key, saved);
let refused = |s: &mut Session, p: Value| s.execute("links.unembed", &p).unwrap_err().to_string();
let both = "give `path` or `folder`, not both";
assert!(refused(&mut s, json!({"ids": [a.0, a.0], "folder": out})).ends_with("`ids` names an object twice"));
assert!(refused(&mut s, json!({"id": a.0, "path": file_in(&out, "x.png"), "folder": out})).ends_with(both));
assert!(refused(&mut s, json!({"ids": [a.0], "path": file_in(&out, "x.png"), "folder": out})).ends_with(both));
assert!(refused(&mut s, json!({"ids": [a.0, b.0]})).ends_with("missing `folder`"));
assert!(refused(&mut s, json!({"ids": []})).ends_with("missing `folder`"));
assert!(refused(&mut s, json!({"id": a.0, "ids": [b.0], "folder": out})).ends_with("give `id` or `ids`, not both"));
assert!(refused(&mut s, json!({"id": a.0, "ids": [b.0]})).ends_with("give `id` or `ids`, not both"));
assert!(refused(&mut s, json!({"ids": [a.0], "folder": 5})).ends_with("`folder` must be a string"));
assert!(refused(&mut s, json!({"ids": [], "folder": out})).ends_with("select an image"));
let file = dir.file("one.png");
assert!(refused(&mut s, json!({"ids": [a.0], "folder": file})).ends_with(&format!("{file} is not a folder")));
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
let rect = s.doc().unwrap().selection.objects[0];
assert!(refused(&mut s, json!({"ids": [a.0, rect.0], "folder": out})).ends_with(&format!("object {} is not an image", rect.0)));
assert!(files_in(&out).is_empty(), "nothing written for a refused request");
run(&mut s, "links.unembed", json!({"ids": [a.0], "folder": out}));
assert!(refused(&mut s, json!({"ids": [a.0], "folder": out})).ends_with(&format!("image {} is linked already", a.0)));
assert_eq!(files_in(&out), ["one.png"]);
}
/// Under automation write roots, a folder outside them takes no file.
#[test]
fn unembed_to_a_folder_outside_the_write_roots_is_refused() {
use crate::file_access::{AutomationRoots, confine};
let dir = Folder::new("unembed-folder-roots");
let (inside, outside) = (dir.file("inside"), dir.file("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
write(&file_in(&inside, "pic.png"), &png(60, 30, RED));
let mut s = session();
let id = place_embedded(&mut s, &file_in(&inside, "pic.png"));
let roots = AutomationRoots::new(&[dir.0.as_path()], &[std::path::Path::new(&inside)]).unwrap();
let p = json!({"ids": [id.0], "folder": outside});
let e = confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap_err().to_string();
assert!(e.contains("outside the write root"), "{e}");
assert!(files_in(&outside).is_empty());
assert!(image(&s, id).link.is_none());
let p = json!({"ids": [id.0], "folder": inside});
confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap();
assert!(image(&s, id).link.is_some());
}
#[test]
fn go_to_selects_the_image() {
let dir = Folder::new("goto");
+8 -3
View File
@@ -1629,9 +1629,9 @@ fn cmyk_mesh(create: Value) -> (Session, NodeId) {
(s, a)
}
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the
/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them
/// back), and its warnings.
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` and DeviceCMYK
/// `c m y k k` operands, and the corner colours of its gradient meshes, which are patch shadings,
/// as PDF import reads them back), and its warnings.
fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap();
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
@@ -1646,6 +1646,11 @@ fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
if !nums.is_empty() {
out.push(nums.into_iter().rev().collect());
}
} else if *w == "k" {
let nums: Vec<f32> = words[..i].iter().rev().take(4).map_while(|x| x.parse().ok()).collect();
if nums.len() == 4 {
out.push(nums.into_iter().rev().collect());
}
}
}
}
+188
View File
@@ -392,6 +392,67 @@ fn an_ellipse_takes_pie_angles_and_inverts() {
assert!(s.execute("object.setLiveShape", &json!({"pieStart": "half"})).is_err());
}
/// Constrain Pie Angle (`constrainPie`): a new Pie Start or End Angle moves the other angle by as
/// much, so each selected ellipse keeps its own span, across 0° too; a whole ellipse stays whole;
/// after Invert Pie the inverted span is kept; one undo step for all of them; the angle each
/// already has records nothing; and `constrainPie` with both angles, with neither, with Invert Pie
/// or as text is an error that changes nothing.
#[test]
fn constrain_pie_keeps_each_ellipses_span() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let [a, b, c] = [0, 100, 200].map(|y| id(s.execute("shape.ellipse", &json!({"x": 0, "y": y, "width": 200, "height": 80})).unwrap()));
run(&mut s, json!({"ids": [a.0], "pieStart": 300, "pieEnd": 60}));
run(&mut s, json!({"ids": [b.0], "pieStart": 0, "pieEnd": 90}));
let pies = |s: &Session| {
[a, b, c].map(|i| match &s.doc().unwrap().doc.node(i).unwrap().kind {
NodeKind::Path { live: Some(l), .. } => match &**l {
LiveShape::Ellipse { pie, .. } => *pie,
k => panic!("{k:?}"),
},
k => panic!("{k:?}"),
})
};
let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9;
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let n = undo(&s);
// 300° to 60° spans 120°, through 0°; 0° to 90° spans 90°; the third ellipse is whole.
run(&mut s, json!({"ids": [a.0, b.0, c.0], "pieStart": 350, "constrainPie": true}));
let [pa, pb, pc] = pies(&s);
assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}");
assert!(near(pc, (350.0, 350.0)), "{pc:?}");
assert_eq!(s.doc().unwrap().doc.node(c).unwrap().path_data().unwrap().anchor_count(), 4, "the whole ellipse stays whole");
assert_eq!(undo(&s), n + 1, "one undo step");
run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 20, "constrainPie": true}));
let [pa, pb, _] = pies(&s);
assert!(near(pa, (260.0, 20.0)) && near(pb, (290.0, 20.0)), "{pa:?} {pb:?}");
let n = undo(&s);
run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 380, "constrainPie": true}));
assert_eq!(undo(&s), n, "the end each already has: no undo step");
s.execute("edit.undo", &json!({})).unwrap();
let [pa, pb, _] = pies(&s);
assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}");
// Inverted, 80° to 350° spans 270°, and a linked edit keeps that.
run(&mut s, json!({"ids": [b.0], "invertPie": true}));
run(&mut s, json!({"ids": [b.0], "pieStart": 0, "constrainPie": true}));
assert!(near(pies(&s)[1], (0.0, 270.0)), "{:?}", pies(&s)[1]);
let before = (undo(&s), pies(&s));
for (p, want) in [
(json!({"ids": [b.0], "pieStart": 10, "pieEnd": 20, "constrainPie": true}), "needs one of"),
(json!({"ids": [b.0], "constrainPie": true}), "needs one of"),
(json!({"ids": [b.0], "pieStart": 10, "constrainPie": true, "invertPie": true}), "needs one of"),
(json!({"ids": [b.0], "pieStart": 10, "constrainPie": "yes"}), "`constrainPie` must be true or false"),
] {
let r = s.execute("object.setLiveShape", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}");
assert_eq!((undo(&s), pies(&s)), before, "{p}");
}
// Off, each angle is set on its own, as before.
run(&mut s, json!({"ids": [b.0], "pieStart": 90, "constrainPie": false}));
assert!(near(pies(&s)[1], (90.0, 270.0)), "{:?}", pies(&s)[1]);
}
/// Invert Pie and Make Sides Equal given as text or as another value that is not true or false are
/// an error naming the key: the ellipse's pie, the polygon and the undo history stay as they were.
/// True makes the change, and false and null leave the shape as it is.
@@ -524,6 +585,107 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() {
}
}
/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees
/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the
/// length applies before the angle, every selected line takes them in one undo step, and a value
/// that changes nothing records none.
#[test]
fn a_line_takes_its_length_and_angle() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let line = |s: &mut Session, a: (f64, f64), b: (f64, f64)| {
NodeId(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()["id"].as_u64().unwrap())
};
let id = line(&mut s, (100.0, 100.0), (200.0, 100.0));
let ends = |s: &Session, id: NodeId| match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { live: Some(l), path, .. } => {
let LiveShape::Line { a, b } = **l else { panic!("{l:?}") };
assert_eq!(*path, l.to_path(), "the path follows the line");
(a.x, a.y, b.x, b.y)
}
k => panic!("{k:?}"),
};
let near = |got: (f64, f64, f64, f64), want: (f64, f64, f64, f64)| {
assert!([got.0 - want.0, got.1 - want.1, got.2 - want.2, got.3 - want.3].iter().all(|d| d.abs() < 1e-9), "{got:?} ≠ {want:?}")
};
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
run(&mut s, json!({"lineLength": 50}));
near(ends(&s, id), (100.0, 100.0, 150.0, 100.0));
// 90° points up the page.
run(&mut s, json!({"lineAngle": 90}));
near(ends(&s, id), (125.0, 125.0, 125.0, 75.0));
let n = steps(&s);
for same in [json!({"lineAngle": 450}), json!({"lineAngle": -270}), json!({"lineLength": 50}), json!({"lineLength": 50, "lineAngle": 90})] {
run(&mut s, same.clone());
assert_eq!(steps(&s), n, "{same} records no undo step");
}
near(ends(&s, id), (125.0, 125.0, 125.0, 75.0));
run(&mut s, json!({"lineLength": 20, "lineAngle": 0}));
near(ends(&s, id), (115.0, 115.0, 135.0, 115.0));
assert_eq!(steps(&s), n + 1, "both in one step");
run(&mut s, json!({"lineAngle": 180}));
near(ends(&s, id), (135.0, 115.0, 115.0, 115.0));
run(&mut s, json!({"lineAngle": -90}));
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
let LiveShape::Line { .. } = s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap() else { panic!("still live") };
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap().line_angle(), Some(270.0));
// Several lines: each keeps its own first end, in one undo step.
let other = line(&mut s, (0.0, 0.0), (0.0, 40.0));
let n = steps(&s);
run(&mut s, json!({"ids": [id.0, other.0], "lineLength": 10}));
near(ends(&s, id), (125.0, 105.0, 125.0, 115.0));
near(ends(&s, other), (0.0, 0.0, 0.0, 10.0));
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
near(ends(&s, other), (0.0, 0.0, 0.0, 40.0));
// Bad values, and a line that would reach past the coordinate limit, change neither line.
let far = line(&mut s, (3_900_000.0, 0.0), (3_900_100.0, 0.0));
let n = steps(&s);
for bad in [
json!({"ids": [id.0], "lineLength": 0}),
json!({"ids": [id.0], "lineLength": -3}),
json!({"ids": [id.0], "lineLength": "long"}),
json!({"ids": [id.0], "lineAngle": "up"}),
json!({"ids": [id.0], "lineLength": 1e300}),
json!({"ids": [id.0, far.0], "lineLength": 200_000}),
] {
assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
assert_eq!(steps(&s), n, "{bad}");
}
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
near(ends(&s, far), (3_900_000.0, 0.0, 3_900_100.0, 0.0));
// A length past the coordinate limit is fine while both ends stay inside it.
let wide = line(&mut s, (-3_500_000.0, 0.0), (3_500_000.0, 0.0));
run(&mut s, json!({"ids": [wide.0], "lineLength": 6_000_000}));
near(ends(&s, wide), (-3_500_000.0, 0.0, 2_500_000.0, 0.0));
// A line whose ends meet reads 0°: an angle leaves it as it is, and a length points it right.
let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0));
assert_eq!(s.doc().unwrap().doc.node(dot).unwrap().live_shape().unwrap().line_angle(), Some(0.0));
let n = steps(&s);
run(&mut s, json!({"lineAngle": 45}));
assert_eq!(steps(&s), n);
run(&mut s, json!({"lineLength": 30}));
near(ends(&s, dot), (10.0, 10.0, 40.0, 10.0));
// A very short length is applied.
let speck = line(&mut s, (20.0, 20.0), (20.0, 20.0));
let n = steps(&s);
run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12}));
assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change");
assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck));
// A length so short that the rounded ends do not move records no undo step.
let dust = line(&mut s, (20.0, 20.0), (20.0, 20.0));
let n = steps(&s);
run(&mut s, json!({"ids": [dust.0], "lineLength": 1e-20}));
assert_eq!(steps(&s), n, "a length of 1e-20 pt changes nothing");
near(ends(&s, dust), (20.0, 20.0, 20.0, 20.0));
// Other live shapes ignore the line params.
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
let n = steps(&s);
run(&mut s, json!({"ids": [rect.0], "lineLength": 30, "lineAngle": 45}));
assert_eq!(steps(&s), n);
}
#[test]
fn relative_corner_rounding_keeps_fraction_on_resize() {
let (mut s, id) = session();
@@ -613,3 +775,29 @@ fn an_arrow_press_without_a_drag_keeps_mixed_radii() {
assert_eq!(radii, before, "each corner keeps its radius");
assert!(kinds.iter().all(|k| *k == CornerKind::InvertedRound), "{kinds:?}");
}
/// A double-click on a corner widget with the Rectangle tool asks the frontend for the Transform
/// panel, and leaves the document, its undo history, the selection and the tool as they were.
#[test]
fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
let (mut s, id) = session();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let v = ViewInfo::default();
s.select_tool("rectangle", v).unwrap();
let st = s.doc().unwrap();
let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show");
let at = w.visible().next().expect("a widget");
let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len());
let mut asked = vec![];
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap());
}
assert_eq!(asked, vec![UiRequest::Panel("transform".into())]);
let st = s.doc().unwrap();
assert!(*st.doc == *doc, "the document is unchanged");
assert_eq!(st.selection, selection);
assert_eq!(st.history.undo.len(), steps, "no undo step");
assert!(st.interaction.is_none());
assert_eq!(s.tool_id(), "rectangle");
}
+69
View File
@@ -4473,6 +4473,58 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() {
assert_eq!(selected(&s), vec![g]);
}
/// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one
/// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true`
/// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a
/// sublayer still leaves in one call.
#[test]
fn exit_isolation_goes_up_one_layer_from_a_sublayer() {
let mut s = session();
let top = s.doc().unwrap().doc.layers[0].id;
let mid = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap());
let deep = id_of(&s.execute("layer.newSublayer", &json!({"parent": mid.0})).unwrap());
s.execute("layer.setCurrent", &json!({"id": deep.0})).unwrap();
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);
let isolation = |s: &Session| s.doc().unwrap().isolation;
let exit = |s: &mut Session, p: Value| s.execute("object.exitIsolation", &p).unwrap();
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
let before = history(&s);
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (Some(mid), vec![deep]), "up from the deepest sublayer");
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (Some(top), vec![mid]), "up from the middle sublayer");
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![top]), "out from the top-level layer");
assert_eq!(history(&s), before, "no undo step");
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
exit(&mut s, json!({"all": true}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![deep]), "all: true");
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
exit(&mut s, json!({"all": false}));
assert_eq!(isolation(&s), Some(mid), "all: false");
for bad in [json!({"all": 1}), json!({"all": "yes"}), json!({"all": null})] {
let e = s.execute("object.exitIsolation", &bad).unwrap_err().to_string();
assert!(e.contains("`all` must be true or false"), "{bad}: {e}");
assert_eq!(isolation(&s), Some(mid), "{bad}: still isolated");
}
// A parent layer hidden while its sublayer is isolated isn't isolated: the call leaves.
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
s.execute("layer.setProps", &json!({"id": mid.0, "visible": false})).unwrap();
exit(&mut s, json!({}));
assert_eq!(isolation(&s), None, "hidden parent layer");
s.execute("layer.setProps", &json!({"id": mid.0, "visible": true})).unwrap();
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![g]), "a group in a sublayer");
}
/// Undo and Redo bring back a selection without the guides, ruler guides or guide paths, that
/// Lock Guides has locked since, so a move after them leaves the guides where they are.
#[test]
@@ -5689,3 +5741,20 @@ fn crop_image_trim_leaves_a_cmyk_image_alone() {
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}");
}
/// Lock Guides is not an undo step: it adds none, and undo and redo of the steps before it leave
/// the guides locked.
#[test]
fn lock_guides_is_not_an_undo_step() {
let mut s = session();
let g = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
sel(&mut s, &[g]);
s.execute("view.guides.make", &json!({})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.guides_locked());
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.guides_locked());
}
+113
View File
@@ -637,6 +637,69 @@ fn an_edited_profile_starts_the_documents_of_its_category() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The fill, stroke and weight of `id` in the active document.
fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, Option<f64>) {
let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap();
(n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
}
#[test]
fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("default-style");
// The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 0.25})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
let style = s.doc().unwrap().doc.graphic_styles[0].clone();
let red = style.appearance.stroke_paint();
assert!(matches!(red, Paint::Solid { .. }), "{red:?}");
assert_eq!(style.appearance.stroke().map(|st| st.width), Some(0.25), "{style:?}");
// The Mobile profile is saved as shipped.
s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let green = s.paint.fill.clone();
// A document from the Print profile starts with the style's fill, stroke and weight, and its art takes them.
s.execute("file.new", &json!({"profile": "Print", "colorMode": "cmyk"})).unwrap();
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, red.clone(), 0.25));
let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap();
assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25)));
// Default Fill and Stroke gives the selection and the defaults that look again, as one undo step.
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25)));
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
// Nothing to change: no undo step.
let step = s.doc().unwrap().history.step();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.step(), step);
// The new art is not linked to the style.
assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().extras().graphic_style.is_none());
// A profile with the shipped style, here converted to CMYK, leaves the fill and stroke the user chose.
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00", "keepModel": true})).unwrap();
s.execute("file.new", &json!({"profile": "Mobile", "colorMode": "cmyk"})).unwrap();
assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk);
assert_eq!(s.paint.fill, green);
// So does a document without a profile, and Default Fill and Stroke there gives white and 1 pt black.
s.execute("file.new", &json!({})).unwrap();
assert_eq!(s.paint.fill, green);
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_profile_follows_the_preset_access_and_reset() {
let (mut s, dir) = with_profiles("choice");
@@ -682,6 +745,56 @@ fn the_profile_follows_the_preset_access_and_reset() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The first run's style of text object `id`.
fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle {
let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).cloned().unwrap();
let vectorcraft_doc::NodeKind::Text(t) = &n.kind else { panic!("not type: {n:?}") };
t.runs[0].style.clone()
}
#[test]
fn a_profiles_normal_character_style_is_the_default_font() {
let (mut s, dir) = with_profiles("default-font");
// The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"});
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap();
s.execute("document.save", &json!({})).unwrap();
// New type in a document from the profile takes the font, size and Character Alignment.
s.execute("file.new", &json!({"preset": "A4"})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Serif"})).unwrap();
assert!(made.get("warning").is_none(), "{made}");
let st = first_run(&s, &made["id"]);
assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Source Serif 4", "Regular", 9.0));
assert_eq!(st.char_align, vectorcraft_doc::CharAlign::EmBoxBottom);
// A font, size or Character Alignment given to the command still wins.
let made = s
.execute("text.create", &json!({"x": 20, "y": 80, "text": "Sans", "font": "Source Sans 3", "size": 14, "charAlign": "romanBaseline"}))
.unwrap();
let st = first_run(&s, &made["id"]);
assert_eq!((st.font_family.as_str(), st.size, st.char_align), ("Source Sans 3", 14.0, vectorcraft_doc::CharAlign::RomanBaseline));
// A family given alone starts in Regular, not the style's Bold, and without its axis settings.
let attrs = json!({"font_style": "Bold", "fontAxes": {"wght": 700}});
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Inter", "font": "Inter"})).unwrap();
let st = first_run(&s, &made["id"]);
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Inter", "Regular"));
assert!(st.font_axes.is_empty(), "{:?}", st.font_axes);
// A font of the style that isn't available is reported, as one given to the command is.
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"font_family": "No Such Family 7498"}})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Missing"})).unwrap();
assert!(made["warning"].as_str().is_some_and(|w| w.contains("No Such Family 7498")), "{made}");
// A document from a profile left as shipped starts type in the default font and size.
s.execute("file.new", &json!({"profile": "Web"})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Default"})).unwrap();
let st = first_run(&s, &made["id"]);
let default = vectorcraft_doc::CharStyle::default();
assert_eq!((st.font_family, st.size), (default.font_family, default.size));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
let (mut s, dir) = with_profiles("errors");
+22
View File
@@ -1557,6 +1557,28 @@ fn a_random_brush_in_the_tile_art_draws_every_tile_alike() {
}
}
#[test]
fn a_path_set_to_random_by_its_own_brush_options_draws_every_tile_alike() {
// The brush scatters at fixed values; the tile path's own settings (Options of Selected
// Object) make it scatter at random, so the expanded tiles must still match the canvas.
let mut s = session();
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 12, "height": 12}))["id"].as_u64().unwrap();
run(&mut s, "paint.setFill", json!({"none": true}));
run(&mut s, "paint.setStroke", json!({"color": "#000000"}));
run(&mut s, "brush.apply", json!({"name": "Confetti"}));
run(&mut s, "brush.options", json!({"name": "Confetti", "params": {"modes": ["fixed", "fixed", "fixed", "fixed"]}}));
run(&mut s, "brush.objectOptions", json!({"ids": [tile], "params": {"modes": ["random", "random", "random", "random"]}}));
run(&mut s, "object.pattern.make", json!({"ids": [tile], "name": "Confetti", "width": 60, "height": 60, "edit": false}));
run(&mut s, "select.set", json!({"ids": [tile]}));
run(&mut s, "edit.clear", json!({}));
run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 160, "height": 160}));
run(&mut s, "paint.setFill", json!({"swatch": "Confetti"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
let before = render(&s);
expand_to_tiles(&mut s);
assert_eq!(differing(&before, &render(&s), 64), 0, "every tile as on the canvas");
}
#[test]
fn roughen_in_the_tile_art_of_a_scaled_pattern_keeps_its_detail() {
// Roughen's detail is per inch: the canvas roughens the 10 pt square and scales the tile, so
+171
View File
@@ -405,6 +405,177 @@ fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() {
assert_eq!(r["links"], 1, "{r}");
}
/// A confined request packages no linked file it would copy as it is (a PDF with Preserve Editing,
/// or a native document it does not rewrite) whose native document keeps an Export for Screens
/// folder outside its read roots: the package is refused before anything is written, with an error
/// that names no file or folder. A native document the package rewrites leaves the folder out, a
/// folder inside the roots is packaged, and the person's package copies every file.
#[test]
fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root() {
let away = Folder::new("package-folder-away");
let home = Folder::new("package-folder-home");
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned()];
let out = home.file("out");
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
let refused = |s: &mut Session, p: Value| {
let e = package(s, p.clone()).expect_err("refused");
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
let e = e.to_string();
assert!(e.contains("a linked file's export folder is outside the read roots"), "{p}: {e}");
for h in &hidden {
assert!(!e.contains(h.as_str()), "{p} names {h}: {e}");
}
assert!(!std::path::Path::new(&out).exists(), "{p}");
};
let mut part = session();
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
std::fs::create_dir_all(home.0.join("art")).unwrap();
let native = home.file("art/part.vectorcraft");
let pdf = home.file("art/part.pdf");
let keep = |part: &mut Session, folder: &str| {
std::sync::Arc::make_mut(&mut part.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap();
save(part, &native);
let r = run(part, "document.serialize", json!({"format": "pdf"}));
write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
};
keep(&mut part, &away.0.to_string_lossy());
let poster = |placed: &str| {
let mut s = session();
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
assert_eq!(r["linked"], true, "{r}");
save(&mut s, &home.file("poster.vectorcraft"));
s
};
let mut s = poster(&pdf);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
let mut s = poster(&native);
refused(&mut s, json!({"folder": out, "relink": false}));
// Rewritten, the copy leaves the folder out.
let r = package(&mut s, json!({"folder": out})).unwrap();
assert_eq!(r["links"], 1, "{r}");
let copied = std::fs::read(std::path::Path::new(&out).join("poster Folder/Links/part.vectorcraft")).unwrap();
assert_eq!(vectorcraft_format::load_file(&copied).unwrap().doc.export_settings.get("folder"), None);
std::fs::remove_dir_all(&out).unwrap();
// A folder inside the read roots.
keep(&mut part, &home.file("screens"));
let mut s = poster(&pdf);
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
}
/// A confined request packages no linked file whose native document it can't read to check against
/// its read roots: a PDF that needs a password to open, and a native document that doesn't load,
/// even inside the roots. The package is refused before anything is written, with an error that
/// names no file or folder. A PDF without editing data is copied, and the person's package copies
/// every file.
#[test]
fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() {
let home = Folder::new("package-unreadable-home");
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let out = home.file("out");
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
let refused = |s: &mut Session, p: Value| {
let e = package(s, p.clone()).expect_err("refused");
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
let e = e.to_string();
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}");
assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}");
assert!(!std::path::Path::new(&out).exists(), "{p}");
};
let mut part = session();
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
std::fs::create_dir_all(home.0.join("art")).unwrap();
let native = home.file("art/part.vectorcraft");
let pdf = home.file("art/part.pdf");
save(&mut part, &native);
let pdf_of =
|part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap();
let editable = pdf_of(&mut part, json!({"format": "pdf"}));
let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}}));
assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data");
let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false}));
let poster = |placed: &str| {
let mut s = session();
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
assert_eq!(r["linked"], true, "{r}");
save(&mut s, &home.file("poster.vectorcraft"));
s
};
write(&pdf, &editable);
let mut s = poster(&pdf);
write(&pdf, &locked);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
// A package prepared in the confined request and written on another thread.
let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap();
let e =
std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused");
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}");
assert!(!std::path::Path::new(&out).exists());
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A PDF listing the editing file without its data (`EF` renamed, the same length).
let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF");
let mut detached = editable.clone();
detached[at..at + 3].copy_from_slice(b"/XF");
assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved");
write(&pdf, &detached);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A PDF without editing data.
write(&pdf, &plain);
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
std::fs::remove_dir_all(&out).unwrap();
// A PDF whose attachments are too many to search to their end, with a readable editing file
// listed before the ones left unsearched.
let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data);
assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read");
write(&pdf, &cut);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A native document that doesn't load, rewritten or copied as it is.
let mut s = poster(&native);
write(&native, b"not a document");
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"folder": out, "relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
}
/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree
/// whose second subtree has 70,000 nodes, more than are searched.
fn attachments_cut_short(native: &[u8]) -> Vec<u8> {
let name = vectorcraft_pdf::EDITING_FILE;
let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes();
stream.extend_from_slice(native);
stream.extend_from_slice(b"\nendstream");
let objects = [
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(),
b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(),
format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(),
format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(),
stream,
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, body) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
for at in &offsets {
out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
out
}
/// A missing link stored as a path relative to the document names a file inside a confined
/// request's read root: the package report and Document Info give its stored path.
#[test]
+2
View File
@@ -430,6 +430,8 @@ fn set_live_shape_refuses_an_unknown_key() {
json!({"id": 3, "radius": 5}),
json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}),
json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}),
json!({"pieEnd": 90, "constrainPie": true}),
json!({"ids": [3], "lineLength": 72, "lineAngle": 90}),
json!({"items": null}),
] {
assert!(check_params(ID, &ok).is_ok(), "{ok}");
+168
View File
@@ -0,0 +1,168 @@
//! The params description of each built-in command is parsed once per process; the answers read
//! from it are those of parsing it where they are used.
use std::hint::black_box;
use serde_json::{Value, json};
use crate::cmd::params::{PARSES, accepted_keys, check_keys, doc_keys, id_stands_for_ids, read_once, takes_key, uncached};
use crate::{Session, command_specs};
/// Every answer the key functions give about `doc` for command `id`, as text.
fn answers(id: &str, doc: &'static str) -> Vec<String> {
let own = doc_keys(doc).map(|p| p.keys).unwrap_or_default();
let accepted = accepted_keys(doc);
let mut out = vec![format!("{accepted:?}"), format!("{}", id_stands_for_ids(doc))];
let near = own.first().map(|k| format!("{k}q"));
for key in own.iter().copied().chain(["ids", "id", "zzz"]).chain(near.as_deref()) {
out.push(format!("{key}: {}", takes_key(doc, key)));
}
let all: serde_json::Map<String, Value> = accepted.iter().flatten().map(|k| (k.to_string(), Value::Null)).collect();
let mut cases = vec![json!({}), json!({"zzz": 1}), Value::Object(all)];
cases.extend(near.map(|k| json!({ k: 1 })));
for params in cases {
out.push(format!("{params}: {:?}", check_keys(id, doc, &params)));
}
out
}
#[test]
fn every_command_gets_the_answers_of_its_parsed_description() {
for c in command_specs() {
assert_eq!(answers(c.id, c.params), uncached(|| answers(c.id, c.params)), "{}", c.id);
}
}
#[test]
fn a_built_in_description_is_not_parsed_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
let run = |s: &mut Session| {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("object.move", &json!({"ids": [id], "dx": 1})).unwrap();
s.execute("object.move", &json!({"ids": [id], "dx": -1})).unwrap();
for c in command_specs() {
black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params)));
black_box(check_keys(c.id, c.params, &json!({"zzz": 1})).is_err());
}
};
run(&mut s);
PARSES.set(0);
run(&mut s);
assert_eq!(PARSES.get(), 0, "descriptions parsed again");
// Without the table each command parses its description where it is used.
uncached(|| run(&mut s));
assert!(PARSES.get() > command_specs().len());
}
/// A description that isn't a built-in command's, even with the same words (a plug-in's), is parsed
/// where it is used, and so is one that names a plug-in command, whose keys change as plug-ins are
/// installed and removed.
#[test]
fn other_descriptions_are_parsed_where_they_are_used() {
let spec = command_specs().iter().find(|c| id_stands_for_ids(c.params)).unwrap();
let copy: &'static str = String::from(spec.params).leak();
assert_eq!(answers(spec.id, copy), answers(spec.id, spec.params));
PARSES.set(0);
assert!(takes_key(copy, "ids") && id_stands_for_ids(copy));
assert!(PARSES.get() > 0);
assert!(read_once("{a, …settings as file.new}"));
assert!(!read_once("{a, …settings as plugin.some.command}"));
assert!(!read_once("{a, …the options of `plugin.some.command`}"));
}
/// This thread's CPU time in ns where Linux reports it, else the time since `start`.
fn now(start: std::time::Instant) -> (u128, bool) {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse().ok());
match cpu {
Some(ns) => (ns, true),
None => (start.elapsed().as_nanos(), false),
}
}
fn median(mut v: Vec<u128>) -> u128 {
v.sort_unstable();
v[v.len() / 2]
}
/// `cargo test --release -p vectorcraft-engine --lib params_cache -- --ignored --nocapture` prints
/// the time of the key questions over every built-in description and of `Session::execute` on a
/// one-object document, with descriptions parsed where they are used (`parse`) and read once
/// (`once`), alternating in one process: the median of 7 runs, in this thread's CPU time on Linux.
#[test]
#[ignore = "benchmark"]
fn bench_params_keys_once() {
let start = std::time::Instant::now();
let specs = command_specs();
let questions = || {
for c in specs {
black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id")));
black_box((takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params)));
}
};
let time = |f: &dyn Fn()| {
let t = now(start);
f();
(now(start).0 - t.0, t.1)
};
questions();
uncached(questions);
let (mut parse, mut once, mut cpu) = (Vec::new(), Vec::new(), true);
for _ in 0..7 {
let (p, c1) = time(&|| uncached(|| (0..200).for_each(|_| questions())));
let (o, c2) = time(&|| (0..200).for_each(|_| questions()));
parse.push(p);
once.push(o);
cpu &= c1 && c2;
}
let per = |ns: u128| ns / (200 * specs.len() as u128);
println!("clock: {}", if cpu { "thread CPU time" } else { "wall time" });
println!("key questions, ns per description: parse {} once {}", per(median(parse)), per(median(once)));
for (cmd, params) in [("select.set", "ids"), ("object.move", "move")] {
let doc = || {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
let p = if params == "ids" { json!({"ids": [id]}) } else { json!({"ids": [id], "dx": 1}) };
(s, p)
};
let run = |s: &mut Session, p: &Value| {
for _ in 0..20_000 {
black_box(s.execute(cmd, p).unwrap());
}
};
let ((mut a, pa), (mut b, pb)) = (doc(), doc());
assert_eq!(uncached(|| a.execute(cmd, &pa).unwrap()), b.execute(cmd, &pb).unwrap(), "{cmd}: both ways give the same result");
let timed = |s: &mut Session, p: &Value, cached: bool| {
let t = now(start).0;
if cached {
run(s, p)
} else {
uncached(|| run(s, p))
}
now(start).0 - t
};
let (mut parse, mut once) = (Vec::new(), Vec::new());
for i in 0..7 {
let (mut s1, p1) = doc();
let (mut s2, p2) = doc();
if i % 2 == 0 {
parse.push(timed(&mut s1, &p1, false));
once.push(timed(&mut s2, &p2, true));
} else {
once.push(timed(&mut s2, &p2, true));
parse.push(timed(&mut s1, &p1, false));
}
// Each document has a `uid` of its own.
let state = |s: &Session| {
let mut d = crate::inspect::document(s);
d.as_object_mut().unwrap().remove("uid");
d
};
assert_eq!(state(&s1), state(&s2), "{cmd}: same document");
}
let ms = |ns: u128| ns as f64 / 1e6;
println!("{cmd} x 20,000: parse {:.1} ms once {:.1} ms", ms(median(parse)), ms(median(once)));
}
}
+127
View File
@@ -533,6 +533,133 @@ fn offset_path_stops_after_the_first_failure() {
}
}
/// 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();
+85
View File
@@ -312,6 +312,91 @@ fn view_options_toggle_without_undo_steps_and_survive_presets() {
assert_eq!(PerspectiveGrid::from_doc(&back), Some(g));
}
/// The view options are not undo steps, so undo and redo of other steps leave them as they are:
/// Lock Grid, Lock Station Point, Snap to Grid, Show Rulers and whether the grid shows. Undoing a
/// grid definition brings back the old grid with the current view options.
#[test]
fn undo_and_redo_keep_the_view_options() {
let mut s = session();
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
let old = grid(&s);
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40}));
run(&mut s, "perspective.grid.preset", json!({"kind": 1}));
let n = undo_len(&s);
for (id, on) in
[("perspective.grid.lock", true), ("perspective.grid.lockStation", true), ("perspective.grid.snap", false), ("perspective.grid.rulers", true)]
{
run(&mut s, id, json!({"on": on}));
}
run(&mut s, "perspective.grid.show", json!({"visible": false}));
assert_eq!(undo_len(&s), n);
let view = |g: &PerspectiveGrid| (g.locked, g.lock_station, g.snap, g.rulers, g.visible);
let want = (true, true, false, true, false);
assert_eq!(view(&grid(&s)), want);
// Undo the one-point preset: the two-point grid comes back with today's view options.
s.execute("edit.undo", &json!({})).unwrap();
let g = grid(&s);
assert_eq!((g.kind, g.vp_left, view(&g)), (old.kind, old.vp_left, want));
// Undo the rectangle, which left the grid alone.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
// An option changed now holds through the redo steps.
run(&mut s, "perspective.grid.lock", json!({"on": false}));
s.execute("edit.redo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let g = grid(&s);
assert_eq!((g.kind, view(&g)), (1, (false, true, false, true, false)));
}
/// The view options set on a document whose steps hold no grid yet stay as they are when undo
/// brings back a step without one, and the active plane chosen without an undo step stays too.
#[test]
fn undo_keeps_the_view_options_of_a_grid_no_step_defined() {
let mut s = session();
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40}));
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 40}));
assert!(!s.doc().unwrap().doc.unknown.contains_key(vectorcraft_tools::distort::perspective::DOC_KEY));
run(&mut s, "perspective.grid.show", json!({"visible": true}));
run(&mut s, "perspective.grid.lock", json!({"on": true}));
run(&mut s, "perspective.grid.snap", json!({"on": false}));
run(&mut s, "perspective.plane.set", json!({"plane": "ground"}));
let view = |g: &PerspectiveGrid| (g.visible, g.locked, g.snap, g.plane);
let want = (true, true, false, vectorcraft_tools::distort::perspective::Plane::Ground);
assert_eq!(view(&grid(&s)), want);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
}
/// A step that changed a view option itself takes it back on undo and sets it again on redo: a
/// preset shows the grid, and a grid definition can lock it.
#[test]
fn undo_takes_back_the_view_options_a_step_changed() {
let mut s = session();
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
run(&mut s, "perspective.grid.show", json!({"visible": false}));
run(&mut s, "perspective.grid.preset", json!({"kind": 1}));
assert!(grid(&s).visible);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!grid(&s).visible, "the preset showed the grid");
s.execute("edit.redo", &json!({})).unwrap();
assert!(grid(&s).visible);
let cell = grid(&s).cell;
run(&mut s, "perspective.grid.set", json!({"locked": true, "cell": cell + 10.0}));
assert!(grid(&s).locked);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).cell), (false, cell));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).cell), (true, cell + 10.0));
// An option the step left alone and changed after it stays as it is.
run(&mut s, "perspective.grid.snap", json!({"on": false}));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).snap), (false, false));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).snap), (true, false));
}
/// Lock Grid, Lock Station Point, Snap to Grid and Show Rulers refuse an `on` given as text or as
/// another value that is not true or false: the grid and the undo history stay as they were. Null is
/// read as the key left out, so it toggles the option.
+55 -1
View File
@@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() {
assert_eq!(s.doc().unwrap().doc, before);
}
/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter
/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as
/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's
/// larger budget stay as they are, and setting Normal again applies to the next run.
#[test]
fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() {
use cmd::plugin::FilterRun;
let mut s = session();
let id = "test.engine.largebudget";
let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string();
// More steps than a light budget pays for, fewer than 5 times it.
install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output));
let p = json!({"id": id, "ids": []});
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
assert!(e.contains("instruction budget"), "{e}");
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"}));
let light = vectorcraft_plugins::Limits::default();
let large = FilterRun::prepare(&s, &p).unwrap().limits().clone();
assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() });
assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms));
// Cancel still stops it, and it changes nothing.
let token = vectorcraft_doc::cancel::CancelToken::new();
token.cancel();
let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p));
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
let made = run(&mut s, "plugin.run", p.clone())["ids"].clone();
assert_eq!(made.as_array().map(Vec::len), Some(1));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
// A heavy filter keeps its larger budget with either choice.
let heavy_id = "test.engine.largebudget.heavy";
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true}));
let hp = json!({"id": heavy_id, "ids": []});
for budget in ["large", "normal"] {
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget}));
let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone();
let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS);
assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}");
}
// Normal again: the next run runs out of instructions.
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
assert!(e.contains("instruction budget"), "{e}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
run(&mut s, "plugin.remove", json!({"id": id}));
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
}
/// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list).
fn with_commands(id: &str, kind: &str, commands: &str) -> String {
format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#)
@@ -4511,9 +4564,10 @@ fn plugin_commands_are_registered_run_and_removed() {
install_wat(&mut s, &tpl::module(&tpl::manifest(id, "filter", "{}"), tpl::ECHO, "", 1));
assert!(listed(&s, grow).is_none() && crate::cmd::find_command(grow).is_none());
install_wat(&mut s, &grower(id));
assert!(listed(&s, grow).is_some());
assert!(listed(&s, grow).is_some() && crate::cmd::find_command(grow).is_some());
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(listed(&s, grow).is_none() && listed(&s, tidy).is_none());
assert!(crate::cmd::find_command(grow).is_none() && crate::cmd::find_command(tidy).is_none());
assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs");
}
+109
View File
@@ -109,6 +109,23 @@ fn grid_prefs_apply_to_open_documents() {
assert_eq!((g.spacing, g.subdivisions), (36.0, 4));
}
/// The grid preferences are not an undo step in the documents they apply to, so undo and redo
/// leave the grid as the preferences set it.
#[test]
fn undo_and_redo_keep_the_grid_prefs() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
s.execute("prefs.set", &json!({"values": {"gridlineEvery": 36, "gridSubdivisions": 4}})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let g = &s.doc().unwrap().doc.grid;
assert_eq!((g.spacing, g.subdivisions), (36.0, 4));
s.execute("prefs.set", &json!({"values": {"gridlineEvery": 18, "gridSubdivisions": 3}})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let g = &s.doc().unwrap().doc.grid;
assert_eq!((g.spacing, g.subdivisions), (18.0, 3));
}
/// Guides & Grid › Gridline every and Subdivisions (#394): set with no document open, as the
/// desktop app restores them at launch, they give `file.new`'s document their grid.
#[test]
@@ -447,6 +464,69 @@ fn gpu_preference_defaults_to_automatic_and_validates() {
assert_eq!(s.prefs.gpu_preference, "automatic");
}
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or
/// label, kept through a save and load, and reset with its category. Setting another value is an
/// error that changes nothing; a saved value that is missing, unknown or of another type reads as
/// Normal and leaves the other saved preferences as they are.
#[test]
fn plugin_instruction_budget_defaults_to_normal_and_validates() {
let mut s = Session::new();
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal"));
set_pref(&mut s, "pluginInstructionBudget", json!("Large"));
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large);
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large"));
for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] {
assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}");
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}");
}
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert_eq!(back.plugin_instruction_budget, PluginBudget::Large);
let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")];
let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v}));
for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) {
let read: Prefs = serde_json::from_value(saved.clone()).unwrap();
assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}");
}
let l = s.execute("prefs.list", &json!({})).unwrap();
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone();
assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins")));
assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large")));
s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap();
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
}
/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written
/// before it, a boolean only, kept through a save/load round trip, listed under Performance and
/// reset with it.
#[test]
fn low_latency_drawing_defaults_off_and_takes_only_a_boolean() {
let mut s = Session::new();
assert!(!s.prefs.low_latency_drawing);
assert_eq!(s.execute("prefs.get", &json!({"key": "lowLatencyDrawing"})).unwrap(), json!(false));
s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": true})).unwrap();
assert!(s.prefs.low_latency_drawing);
for bad in [json!(1), json!(null), json!("on"), json!("yes"), json!([true])] {
assert!(s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": bad})).is_err(), "{bad}");
assert!(s.prefs.low_latency_drawing);
}
// Booleans may be given as "true" and "false", as for every boolean preference.
s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "false"})).unwrap();
assert!(!s.prefs.low_latency_drawing);
s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "true"})).unwrap();
assert_eq!(s.prefs.to_json()["lowLatencyDrawing"], json!(true));
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert!(back.low_latency_drawing);
let old: Prefs = serde_json::from_value(json!({"gpuPerformance": true})).unwrap();
assert!(!old.low_latency_drawing);
let l = s.execute("prefs.list", &json!({})).unwrap();
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "lowLatencyDrawing").unwrap().clone();
assert_eq!(row["category"], "Performance");
assert_eq!(row["label"], "Low-Latency Drawing");
s.execute("prefs.reset", &json!({"category": "Performance"})).unwrap();
assert!(!s.prefs.low_latency_drawing);
}
/// Performance › Linux Display Server (#1151): automatic by default, X11 by value or label, and
/// anything else is an error that changes nothing.
#[test]
@@ -2606,6 +2686,35 @@ fn settling_typing_for_a_tool_shows_its_preview_warning() {
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
}
/// Typing kept as its own step when a dialog or a panel begins its preview, or when the font menus
/// end the typing session, returns its applied preview's warning for the status bar. A preview
/// without a warning returns none, and with no typing in progress nothing is kept and no step is
/// added.
#[test]
fn settling_typing_for_a_dialog_returns_its_preview_warning() {
let warned = |w: &[String]| w.iter().any(|m| m.contains("type"));
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let mut s = deferred_bloat("Typing", true, "selection");
let before = steps(&s);
let w = s.begin_interaction_warned("Offset Path").unwrap();
assert!(warned(&w), "{w:?}");
assert_eq!(steps(&s), before + 1, "the typing is a step of its own");
assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.as_str()), Some("Offset Path"));
let mut s = deferred_bloat("Typing", true, "selection");
let w = s.keep_typing().unwrap();
assert!(warned(&w), "{w:?}");
assert!(!s.in_interaction());
assert_eq!(steps(&s), before + 1);
let w = s.keep_typing().unwrap();
assert!(w.is_empty(), "{w:?}");
assert_eq!(steps(&s), before + 1, "nothing in progress adds no step");
let mut s = deferred_bloat("Typing", false, "selection");
let w = s.begin_interaction_warned("Offset Path").unwrap();
assert!(w.is_empty(), "{w:?}");
}
/// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does
/// not replace full-resolution pixels already in the document.
#[test]
+11
View File
@@ -489,6 +489,17 @@ fn edit_group_relinks_art_and_apply_rewrites_the_group_with_the_art() {
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#010203", "cmyk 0 0 0 20"]}));
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), [Color::rgb8(1, 2, 3), Color::cmyk(0.0, 0.0, 0.0, 0.2)]);
// "keep" leaves a swatch its color, without the Global Adjust that the other colors take.
let adjust = json!({"brightness": -50});
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "#ffffff"], "globalAdjust": adjust}));
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
let colors: Vec<Color> = g.swatches.iter().map(|w| w.paint.color().unwrap()).collect();
assert_eq!(colors[0], Color::rgb8(1, 2, 3));
assert_ne!(colors[1].to_hex(), "#ffffff", "the other color takes the Global Adjust");
// Past the group's swatches it adds nothing.
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "keep", "keep"]}));
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), colors);
}
/// Art linked to a global swatch of the group that `recolor.apply` rewrites stays linked when the
File diff suppressed because it is too large. Load diff
+124 -20
View File
@@ -245,10 +245,46 @@ fn files_are_checked_before_they_are_read() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A new empty folder for test `name`.
fn fresh_folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder
/// `dir` there once.
fn start_allowed(s: &mut Session, dir: &std::path::Path, source: &str) {
s.script_frames = true;
assert_eq!(run(s, &format!("Folder.selectDialog('Folder');\n{source}")).unwrap()["running"], true);
for _ in 0..10_000 {
if s.script_picker().is_some() {
let paths = vec![dir.to_string_lossy().into_owned()];
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false }));
return;
}
assert!(s.script_pump().is_none(), "the run waits at its folder dialog");
}
panic!("the run did not open its folder dialog");
}
/// Runs `source` in the app as [`start_allowed`] starts it, to its end.
fn run_allowed(s: &mut Session, dir: &std::path::Path, source: &str) -> Result<Value> {
start_allowed(s, dir, source);
let r = loop {
if let Some(r) = s.script_pump() {
break r;
}
};
s.script_frames = false;
r
}
#[test]
fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let dir = fresh_folder("batch");
let path = dir.join("out.svg");
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
let source = format!(
@@ -257,24 +293,94 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
{{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\
{{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}"
);
let r = run(&mut s, &source).unwrap();
let r = run_allowed(&mut s, &dir, &source).unwrap();
assert_eq!(r["log"], json!(["Error"]), "{r}");
assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay");
assert!(path.exists());
assert_eq!(r["written"], json!([p]), "{r}");
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_export_that_fails_names_no_file() {
let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg");
let dir = fresh_folder("no-folder");
let path = dir.join("missing").join("out.svg");
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}");
let r = run(&mut s, &source).unwrap();
let r = run_allowed(&mut s, &dir, &source).unwrap();
assert_eq!(r["log"], json!(["Error"]), "{r}");
assert!(!path.exists());
assert_eq!(r["written"], json!([]), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The commands a script runs read and write only where its `File` and `Folder` objects may (its
/// temporary folder and what a person allowed it, here), and the files of the open documents,
/// also in a run the person started.
#[test]
fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() {
let dir = fresh_folder("gate");
let (inside, outside) = (dir.join("in"), dir.join("out"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let call = |id: &str, path: &std::path::Path| {
let p = path.to_string_lossy().into_owned();
let format = if id == "document.export" { ", format: 'svg'" } else { "" };
format!(
"try {{ vc.run('{id}', {{path: {p:?}{format}}}); vc.log('ok'); }} catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n"
)
};
let mut s = two_docs();
let r = run(&mut s, &call("document.export", &outside.join("a.svg"))).unwrap();
assert_eq!(r["log"], json!(["denied"]), "a script given as text writes nowhere: {r}");
assert!(!outside.join("a.svg").exists());
let source = format!("{}{}", call("document.export", &inside.join("b.svg")), call("document.export", &outside.join("c.svg")));
let r = run_allowed(&mut s, &inside, &source).unwrap();
assert_eq!(r["log"], json!(["ok", "denied"]), "{r}");
assert!(inside.join("b.svg").exists() && !outside.join("c.svg").exists());
let r = run(&mut s, "var t = Folder.temp.fsName + '/t.svg'; vc.run('document.export', {path: t, format: 'svg'}); vc.log(new File(t).exists);")
.unwrap();
assert_eq!(r["log"], json!([true]), "the run's temporary folder: {r}");
let own = outside.join("own.svg");
s.execute("document.save", &json!({"path": own.to_string_lossy()})).unwrap();
std::fs::copy(&own, outside.join("copy.svg")).unwrap();
let source = format!(
"vc.run('shape.rectangle', {{x: 1, y: 1, width: 1, height: 1}});\n{}{}{}{}",
call("document.save", &own),
call("document.open", &own),
call("document.open", &outside.join("copy.svg")),
call("document.save", &outside.join("other.svg"))
);
let r = run(&mut s, &source).unwrap();
assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}");
assert!(!outside.join("other.svg").exists());
let source = format!("{}{}", call("document.open", &own), call("document.open", &outside.join("copy.svg")));
let r = crate::file_access::unconfined(|| run(&mut s, &source)).unwrap();
assert_eq!(r["log"], json!(["ok", "denied"]), "a run the person starts reads through the gate as well: {r}");
std::fs::remove_file(&own).unwrap();
let r = run(&mut s, &call("document.save", &own)).unwrap();
assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}");
assert!(own.exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A command a script runs does not save into the app's own libraries; the same command run
/// outside a script does.
#[test]
fn a_scripts_commands_do_not_save_into_the_apps_libraries() {
let dir = fresh_folder("gate-library");
let user = dir.join("user");
let mut s = two_docs();
s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().into_owned()));
let source = "try { vc.run('swatch.library.save', {user: true, name: 'Mine'}); vc.log('ok'); } \
catch (e) { vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }";
let r = run(&mut s, source).unwrap();
assert_eq!(r["log"], json!(["denied"]), "{r}");
assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder");
s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap();
assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -346,17 +452,18 @@ fn a_command_whose_result_cannot_cross_is_put_back() {
#[test]
fn an_abandoned_run_reports_the_files_it_wrote() {
let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let dir = fresh_folder("abandon");
let path = dir.join("out.svg");
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
assert!(path.exists(), "the first slice exported");
start_allowed(&mut s, &dir, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
assert!(s.script_pump().is_none());
assert!(path.exists(), "the slice after the dialog exported");
assert!(s.script_abandon());
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}");
assert!(s.script_failure_text().unwrap().contains(&p));
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -886,19 +993,19 @@ fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
#[test]
fn a_file_saved_before_a_failure_stays_written_and_is_named() {
let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let dir = fresh_folder("save");
let path = dir.join("out.svg");
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
let before = state(&s);
let source =
format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');");
let e = run(&mut s, &source).unwrap_err().to_string();
let e = run_allowed(&mut s, &dir, &source).unwrap_err().to_string();
assert!(path.exists());
assert!(e.contains(&p), "{e}");
assert_eq!(s.script_report().unwrap()["written"], json!([p]));
assert_eq!(state(&s), before, "the document does not keep the new path");
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir_all(&dir);
}
/// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope
@@ -923,16 +1030,13 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() {
}
};
let mut s = two_docs();
s.script_frames = true;
let confined_target = outside.join("confined.svg");
let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap();
assert_eq!(started["running"], true);
crate::file_access::confine(Some(&roots), || start_allowed(&mut s, &dir, &export(&confined_target)));
let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap();
assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}");
assert!(!confined_target.exists());
let user_target = outside.join("user.svg");
let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap();
assert_eq!(started["running"], true);
crate::file_access::unconfined(|| start_allowed(&mut s, &dir, &export(&user_target)));
let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap();
assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}");
assert!(user_target.exists());
+62
View File
@@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() {
assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance));
}
/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id,
/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as
/// they are, in one undo step. A style replaced by itself or by a style with the same look records
/// nothing, and bad parameters are errors that change nothing.
#[test]
fn redefine_from_a_style_gives_the_style_that_look() {
let mut s = session();
let (a, b, c) = linked_three(&mut s);
let d = rect(&mut s, 300.0);
set_fill(&mut s, d, "#0000ff");
run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"}));
run(&mut s, "graphicStyle.new", json!({"name": "Blue"}));
set_fill(&mut s, c, "#00ff00");
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s));
assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S");
assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() });
assert_eq!(names(&s), order);
let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap());
for id in [a, b] {
let n = node(&s, id);
assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply));
}
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
// The edited object keeps its look and is unlinked; Blue and its object are as they were.
assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap()));
assert_eq!(node(&s, c).extras().graphic_style, None);
assert_eq!(style(&s, "Blue"), blue);
assert_eq!(linked(&mut s, "Blue"), vec![d.0]);
let step = s.doc().unwrap().history.undo.last().unwrap().clone();
assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1));
run(&mut s, "edit.undo", json!({}));
assert_eq!(style(&s, "S"), old);
assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE)));
assert_eq!(node(&s, c).extras().graphic_style, Some(old.id));
run(&mut s, "edit.redo", json!({}));
assert_eq!(style(&s, "S").appearance, blue.appearance);
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
run(&mut s, "edit.undo", json!({}));
// A style replaced by itself, or by a copy with the same look, records nothing.
run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"}));
let before = steps(&s);
run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"}));
run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"}));
assert_eq!(steps(&s), before);
assert_eq!(style(&s, "S"), old);
// A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors.
for p in [
json!({"name": "S", "from": "nope"}),
json!({"name": "nope", "from": "Blue"}),
json!({"name": "S", "from": 3}),
json!({"name": "S", "from": "Blue", "id": a.0}),
json!({"from": "Blue"}),
] {
assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}");
}
assert_eq!((steps(&s), style(&s, "S")), (before, old));
}
#[test]
fn deleting_a_style_unlinks_and_renaming_keeps_links() {
let mut s = session();
+65
View File
@@ -423,6 +423,71 @@ fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() {
assert_eq!(*doc(&s), before);
}
/// `swatch.editGroup` with the group's own colors, in order, and its own name (or a blank one)
/// records no undo step; a new order, a new color or a new name records one.
#[test]
fn edit_color_group_with_its_own_colors_records_no_undo_step() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00"], "keepModel": true}));
let undo = undo_len(&s);
for p in [
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"]}),
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": "Mine"}),
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": " "}),
] {
let r = run(&mut s, "swatch.editGroup", p.clone());
assert_eq!(r, json!({"name": "Mine", "swatches": ["R=255 G=0 B=0", "R=0 G=255 B=0"], "relinked": 0}), "{p}");
assert_eq!(undo_len(&s), undo, "{p}: no undo step");
}
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"]}));
assert_eq!(undo_len(&s), undo + 1, "a new order is a step");
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"], "rename": "Yours"}));
assert_eq!(undo_len(&s), undo + 2, "a new name is a step");
}
/// `swatch.editGroup` with the color keys of the group's own colors records no undo step when a
/// color lies between the keys' steps, and a rename keeps that color unrounded; a color given as a
/// value is taken as it is.
#[test]
fn edit_color_group_with_its_own_color_keys_keeps_the_colors() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": [{"c": 60.005, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true}));
let colors = |s: &Session| -> Vec<Color> {
doc(s).swatch_groups.iter().find(|g| g.name == "Mine" || g.name == "Yours").unwrap().swatches.iter().filter_map(|w| w.paint.color()).collect()
};
let own = colors(&s);
let keys: Vec<String> = own.iter().map(|c| vectorcraft_color::recolor::ColorKey::of(c).to_string()).collect();
assert_ne!(crate::cmd::color_value(&json!(keys[0])), Some(own[0]), "the key rounds the color");
let undo = undo_len(&s);
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys}));
assert_eq!(undo_len(&s), undo, "the group's own colors record no step");
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys, "rename": "Yours"}));
assert_eq!(undo_len(&s), undo + 1, "a new name is a step");
assert_eq!(colors(&s), own, "the colors are kept unrounded");
// A color given as a value, not a key, is taken exactly, also within a key's step.
let Color::Cmyk { c, .. } = own[0] else { panic!("a CMYK swatch: {:?}", own[0]) };
let nudged = Color::cmyk(c - 0.000_002, 0.0, 0.0, 0.0);
assert_eq!(vectorcraft_color::recolor::ColorKey::of(&nudged), vectorcraft_color::recolor::ColorKey::of(&own[0]));
let p = json!({"group": "Yours", "colors": [{"c": c - 0.000_002, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true});
run(&mut s, "swatch.editGroup", p);
assert_eq!(undo_len(&s), undo + 2, "a new value is a step");
assert_eq!(colors(&s)[0], nudged);
}
#[test]
fn edit_color_group_with_a_null_removes_that_swatch() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true}));
let undo = undo_len(&s);
let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", null, "#0000ff"]}));
assert_eq!(r["swatches"], json!(["R=255 G=0 B=0", "R=0 G=0 B=255"]));
assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0", "R=0 G=0 B=255"]);
assert_eq!(undo_len(&s), undo + 1, "a removed swatch is a step");
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", "#0000ff", null]}));
assert_eq!(undo_len(&s), undo + 1, "a null past the swatches removes nothing and records no step");
assert!(s.execute("swatch.editGroup", &json!({"group": "Mine", "colors": ["#ff0000", "nope"]})).is_err());
}
#[test]
fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() {
let mut s = session();
+185
View File
@@ -300,6 +300,191 @@ fn another_documents_swatches_load_as_a_library() {
assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err());
}
/// Three pattern swatches of another document that paint one pattern, one of them turned, load as
/// three library swatches and come into a document as three swatches of one pattern, each with its
/// own name and placement.
#[test]
fn another_documents_pattern_swatches_of_one_pattern_add_as_separate_swatches() {
use std::sync::Arc;
let turned = vectorcraft_geom::Affine::rotate(0.5);
let mut s = session();
s.edit("Pattern", |d, _| {
let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0));
let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art());
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) });
let swatch = |name: &str, xf| vectorcraft_color::Swatch {
name: name.into(),
paint: Paint::Pattern { pattern: "Dots".into(), xf },
global: false,
spot: false,
};
d.swatches.push(swatch("Tiles", vectorcraft_geom::Affine::IDENTITY));
d.swatches.push(swatch("More tiles", vectorcraft_geom::Affine::IDENTITY));
d.swatches.push(swatch("Turned tiles", turned));
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "More tiles", "Turned tiles"]}));
assert_eq!(r["added"], json!(["Tiles", "More tiles", "Turned tiles"]), "{r}");
let d = doc(&s);
assert_eq!(d.patterns.iter().filter(|p| p.name.starts_with("Dots")).count(), 1, "one pattern");
let xf = |name: &str| match d.swatch(name).map(|w| &w.paint) {
Some(Paint::Pattern { pattern, xf }) if pattern == "Dots" => Some(*xf),
_ => None,
};
assert_eq!((xf("Tiles"), xf("Turned tiles")), (Some(vectorcraft_geom::Affine::IDENTITY), Some(turned)));
let again = run(&mut s, "swatch.library.add", json!({"library": id}));
assert_eq!(again["added"], json!([]), "{again}");
}
/// A library swatch named after its pattern, added in one call after another swatch of that pattern
/// with the same placement, stands for the swatch just added: it is listed as existing, not added
/// again.
#[test]
fn a_pattern_swatch_named_after_its_pattern_reuses_one_added_in_the_same_call() {
use std::sync::Arc;
let mut s = session();
s.edit("Pattern", |d, _| {
let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0));
let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art());
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) });
for name in ["Tiles", "Dots"] {
let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY };
d.swatches.push(vectorcraft_color::Swatch { name: name.into(), paint, global: false, spot: false });
}
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Dots"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles"]), &json!(["Tiles"])), "{r}");
let d = doc(&s);
assert_eq!(d.swatches_iter().filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Dots")).count(), 1, "{r}");
}
/// A library pattern painted with another pattern is not taken for a document pattern with the
/// same art when the pattern its art paints with differs: it comes in as a numbered copy with its
/// own inner pattern, and adding it again reuses that copy.
#[test]
fn a_pattern_painted_with_another_pattern_is_not_matched_by_the_inner_patterns_name() {
use std::sync::Arc;
use vectorcraft_doc::pattern::pattern_paint;
// `Inner` with a tile of `inner` points, `Dots` painted with it, and swatch `Tiles` painting `Dots`.
let make = |d: &mut vectorcraft_doc::Document, inner: f64| {
let dot = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 2.0, 2.0));
let dot = vectorcraft_doc::Node::path(d.alloc_id(), dot, vectorcraft_doc::Appearance::default_art());
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, inner, inner);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Inner", vec![Arc::new(dot)]) });
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(pattern_paint("Inner"), Paint::None, 0.0));
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(square)]) });
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Dots"), global: false, spot: false });
};
let mut s = session();
s.edit("Pattern", |d, _| {
make(d, 4.0);
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
s.edit("Pattern", |d, _| {
make(d, 5.0);
Ok(())
})
.unwrap();
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles 2"]), &json!([])), "{r}");
let d = doc(&s);
let Some(Paint::Pattern { pattern, .. }) = d.swatch("Tiles 2").map(|w| &w.paint) else { panic!("no pattern swatch Tiles 2: {r}") };
let inner = d.pattern(pattern).and_then(|p| p.art.first()).map(|n| n.appearance.fill_paint());
let Some(Paint::Pattern { pattern: inner, .. }) = inner else { panic!("the added pattern is not painted with a pattern: {r}") };
assert_eq!(d.pattern(&inner).map(|p| p.tile), Some(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)), "the library's inner pattern");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles 2"])), "{again}");
}
/// A global color that a library pattern's art links to, added in the same call after the pattern
/// swatch, is the swatch the pattern brought with it: it is added once, not again as a numbered
/// copy, and goes into the library swatch's color group.
#[test]
fn a_color_a_pattern_brings_is_not_added_twice_in_one_call() {
use std::sync::Arc;
use vectorcraft_doc::pattern::pattern_paint;
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#123456", "global": true}));
s.edit("Pattern", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(0x12, 0x34, 0x56), swatch: Some("Ink".into()), tint: 1.0 };
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0));
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) });
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false });
// `Ink` goes into a color group of its own.
let i = d.swatches.iter().position(|w| w.name == "Ink").unwrap();
let ink = d.swatches.remove(i);
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Inks".into(), swatches: vec![ink] });
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Inks"]}));
let d = doc(&s);
let inks: Vec<&str> = d.swatches_iter().filter(|w| w.name.starts_with("Ink")).map(|w| w.name.as_str()).collect();
assert_eq!(inks, ["Ink"], "{r}");
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink"]), &json!([])), "{r}");
let group = d.swatch_groups.iter().find(|g| g.name == "Inks").map(|g| g.swatches.iter().map(|w| w.name.as_str()).collect::<Vec<_>>());
assert_eq!(group, Some(vec!["Ink"]), "{r}");
assert!(d.swatches.iter().all(|w| w.name != "Ink"), "{r}");
}
/// A library pattern whose art links to a global color that the document has under the same name
/// in another color keeps the library's color: the color comes in under a free name ("Ink 2") and
/// the pattern links to it, as the color added in the same call does, and the document's own color
/// is left as it was. Adding the pattern again finds it.
#[test]
fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_another_color() {
use std::sync::Arc;
use vectorcraft_doc::pattern::pattern_paint;
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
s.edit("Pattern", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 };
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0));
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) });
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false });
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink 2"]), &json!([])), "{r}");
let d = doc(&s);
let hex = |n: &str| d.swatch(n).and_then(|w| w.paint.color()).map(|c| c.to_hex());
assert_eq!((hex("Ink"), hex("Ink 2")), (Some("#ff0000".to_string()), Some("#0000ff".to_string())), "{r}");
let fill = d.pattern("Squares").unwrap().art[0].appearance.fill_paint();
let Paint::Solid { color, swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") };
assert_eq!((swatch.as_deref(), color.to_hex()), (Some("Ink 2"), "#0000ff".to_string()), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}");
}
#[test]
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
let bytes = vectorcraft_testkit::ase::sample();
+22
View File
@@ -253,6 +253,28 @@ fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_ste
assert!(st.doc.symbol_edit.is_some());
}
/// Redefining the symbol being edited with `keepArt: true` also leaves symbol editing mode in the
/// same step; the art outside the editing layer stays ordinary art and stays selected, and the
/// art on the editing layer still can't redefine it.
#[test]
fn redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode() {
let (mut s, first, second) = two_instances();
let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30})));
let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
let e = s.execute("symbol.update", &json!({"name": "Box", "keepArt": true})).unwrap_err().to_string();
assert!(e.contains("can't hold an instance of itself"), "{e}");
let steps = s.doc().unwrap().history.undo.len();
let r = run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0], "keepArt": true}));
assert!(r["id"].is_null(), "{r}");
let st = s.doc().unwrap();
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none());
assert_eq!(st.history.undo.len(), steps + 1);
assert!(matches!(st.doc.node(other).map(|n| &n.kind), Some(NodeKind::Path { .. })), "the art stays ordinary art");
assert_eq!(st.selection.objects, vec![other], "the art stays selected");
assert!(is_instance(&s, first), "the instance editing was entered from is still an instance");
assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second));
}
#[test]
fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() {
let (mut s, first, _) = two_instances();
+66
View File
@@ -375,3 +375,69 @@ fn other_documents_symbols_load_and_unreadable_files_are_errors() {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(vectorcraft_format::load(&bytes).unwrap().symbols.len(), 1);
}
/// `symbol.placeFromDocument` places another open document's symbol in the active document as
/// one undo step, with the symbol it nests, the pattern its art uses and its Symbol Options. A
/// second placement uses what the first added; the source document is left as it was; a symbol
/// of the active document itself is placed as it is; a closed document, a name the document does
/// not have and bad params are errors that change nothing.
#[test]
fn another_documents_symbol_is_added_and_placed_in_one_step() {
let mut s = kit();
let source = s.doc().unwrap().uid;
let source_doc = s.doc().unwrap().doc.clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let before = undo_len(&s);
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}));
assert_eq!(undo_len(&s), before + 1, "added and placed in one step");
assert_eq!(r["name"], "Badge");
let mut names = symbols(&s);
names.sort();
assert_eq!(names, ["Badge", "Star"], "the nested Star came along");
assert_eq!(doc(&s).symbol_registration("Badge"), SymbolRegistration(0));
let placed = NodeId(r["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().selection.objects, [placed]);
let NodeKind::SymbolInstance { symbol, .. } = &doc(&s).node(placed).unwrap().kind else { panic!("not an instance") };
assert_eq!(symbol, "Badge");
let size = |d: &vectorcraft_doc::Document| d.unknown.get("symbolSizes").and_then(|m| m.get("Badge")).cloned();
assert!(size(doc(&s)).is_some());
assert_eq!(size(doc(&s)), size(&source_doc));
// The Dots symbol brings its pattern and swatch.
run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Dots"}));
assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some());
// Placed again, Badge is the one already added.
let count = doc(&s).symbols.len();
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge"}));
assert_eq!((r["name"].as_str(), doc(&s).symbols.len()), (Some("Badge"), count));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(symbols(&s).is_empty() && doc(&s).pattern("Dots").is_none());
// The active document's own symbol, by its uid: placed, nothing added.
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
run(&mut s, "symbol.new", json!({"name": "Star"}));
let own = s.doc().unwrap().uid;
let before = undo_len(&s);
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": own, "name": "Star", "x": 70, "y": 70}));
assert_eq!((undo_len(&s), r["name"].as_str(), symbols(&s)), (before + 1, Some("Star"), vec!["Star".to_string()]));
// Errors change nothing.
let before = (undo_len(&s), doc(&s).clone());
for p in [
json!({"sourceDocument": source, "name": "Nope"}),
json!({"sourceDocument": source}),
json!({"name": "Star"}),
json!({"sourceDocument": -1, "name": "Star"}),
json!({"sourceDocument": "1", "name": "Star"}),
json!({"sourceDocument": source, "name": "Star", "x": "10"}),
json!({"sourceDocument": u64::MAX, "name": "Star"}),
] {
assert!(s.execute("symbol.placeFromDocument", &p).is_err(), "{p}");
assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{p}");
}
// The source document is left as it was, and once it is closed its symbols are gone with it.
assert!(s.set_active(0));
assert_eq!(*s.doc().unwrap().doc, *source_doc);
run(&mut s, "file.close", json!({"index": 0}));
let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err();
assert!(e.to_string().contains("no longer open"), "{e}");
}
+35
View File
@@ -3173,6 +3173,41 @@ fn a_previewed_transform_while_typing_keeps_the_typing() {
assert!((left(&s, id) - 400.0).abs() < 1e-6);
}
/// With Performance › Real-time Drawing and Editing off, the typing is applied when its session
/// ends. Ending it for another edit applies it first, as a step of its own: a dialog or a panel
/// beginning its preview, the font menus ([`Session::keep_typing`]), a paint for the selected
/// characters.
#[test]
fn ending_deferred_typing_for_another_edit_keeps_the_typing() {
let typed = |end: &dyn Fn(&mut Session)| {
let mut s = session();
s.prefs.real_time_drawing = false;
let v = ViewInfo::default();
let id = text(&mut s, "Hello");
s.select_tool("type", v).unwrap();
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
click(&mut s, b.x1 - 1.0, b.center().y);
s.tool_text(" world", v).unwrap();
assert_eq!(obj(&s, id).plain_text(), "Hello", "the typing waits for its session to end");
let steps = undo_labels(&s).len();
end(&mut s);
assert_eq!(obj(&s, id).plain_text(), "Hello world");
assert_eq!(undo_labels(&s)[steps], "Typing", "{:?}", undo_labels(&s));
};
typed(&|s| {
assert!(s.begin_interaction_warned("Fill Color").unwrap().is_empty());
s.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
s.commit_interaction().unwrap();
});
typed(&|s| {
assert!(s.keep_typing().unwrap().is_empty());
assert!(!s.in_interaction());
});
typed(&|s| {
s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap();
});
}
/// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the
/// typed text: its interaction used to join the typing session and preview from the document
/// before the typing, so the new type came back as its placeholder text.
+30
View File
@@ -135,6 +135,36 @@ fn text_files_report_and_queue_with_their_options() {
assert!(close(frame, Rect::new(50.0, 60.0, 130.0, 100.0)), "{frame:?}");
}
/// Text Import Options' other character sets place their text as area type, and an unknown
/// character set is refused with the list of sets and places nothing.
#[test]
fn text_files_place_in_the_other_character_sets() {
let mut s = session();
let cases: [(&str, &str, &[u8], &str); 11] = [
("shiftJis", "windows", &[0x93, 0xFA, 0x96, 0x7B], "日本"),
("gb2312", "windows", &[0xD6, 0xD0, 0xCE, 0xC4], "中文"),
("chineseBig5", "mac", &[0xA4, 0xA4, 0xA4, 0xE5], "中文"),
("cyrillic", "windows", &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"),
("cyrillic", "mac", &[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"),
("gb18030", "windows", &[0x95, 0x32, 0x82, 0x36], "\u{20000}"),
("greek", "windows", &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"),
("turkish", "mac", &[0xDD, 0x73, 0x74], "İst"),
("baltic", "windows", &[0x52, 0xEE, 0x67, 0x61], "Rīga"),
("centralEuropean", "windows", &[0xA3, 0xF3, 0x64, 0x9F, b'\r', b'\n', 0xA3], "Łódź\nŁ"),
("shiftJis", "windows", &[0x82, 0x22], "\u{FFFD}\""),
];
for (set, platform, bytes, text) in cases {
let r = place_text(&mut s, bytes, json!({"text": {"characterSet": set, "platform": platform}}));
assert_eq!(placed(&s, &r).0, text, "{set} on {platform}");
}
let undo = s.doc().unwrap().history.undo.len();
let bad = json!({"name": "a.txt", "dataBase64": "YQ==", "text": {"characterSet": "latin9"}});
let err = s.execute("file.place", &bad).unwrap_err().to_string();
let list = r#""unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#;
assert!(err.contains(&format!("text.characterSet `latin9`: use {list}")), "{err}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing placed");
}
/// An RTF file with a font table, a color table, a bold run, an italic run, a superscript and a
/// centered, indented second paragraph.
const LETTER_RTF: &str = concat!(
+113 -1
View File
@@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() {
let mut s = session();
for active in [false, true] {
select(&mut s, if active { "spiral" } else { "selection" });
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap();
// A decay past the 99.99 % a spiral draws is refused, and nothing changes.
let before = s.tool_options_of("spiral");
let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}}));
assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string()));
assert_eq!(s.tool_options_of("spiral"), before);
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap();
assert_eq!(options["decay"], json!(99.99));
assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99));
assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99));
@@ -387,3 +392,110 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() {
assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}");
}
}
/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an
/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also
/// when another option given with it is good, and nothing is saved or recorded for undo.
#[test]
fn bad_option_values_are_errors_that_set_nothing() {
let mut s = session();
select(&mut s, "smooth");
let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len());
let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100";
for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] {
assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}");
}
let cases = [
(json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"),
(json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"),
(json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"),
(json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"),
(json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"),
(json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"),
(
json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}),
"tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`",
),
(json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"),
(json!({"values": [1]}), "`values` must be an object"),
(json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"),
(json!({"key": "fidelity"}), "`value` is missing for `fidelity`"),
];
for (p, want) in cases {
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
}
assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]);
assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo));
// A good value after the errors is set and read back.
assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0));
}
/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing.
#[test]
fn an_empty_set_option_reads_and_saves_nothing() {
let mut s = session();
select(&mut s, "smooth");
let saved = s.prefs.tool_settings.clone();
assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options());
assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare"));
// No params (null) read too; params that are not an object are an error.
assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options());
for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] {
assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}"));
}
assert_eq!(s.prefs.tool_settings, saved);
}
/// A Place queue with a malformed entry is an error, and the queue held stays as it was.
#[test]
fn a_malformed_place_queue_is_an_error() {
let mut s = session();
select(&mut s, "place");
let entry = json!({"params": {"svg": "<svg/>"}, "name": "a", "width": 10, "height": 10});
s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap();
let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10});
let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err();
assert!(e.starts_with("tool `place`: `queue` must be"), "{e}");
assert_eq!(s.tool_options()["names"], json!(["a"]));
assert_eq!(
s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(),
"tool `place`: `current` must be the index of a queued file, from 0 to 0"
);
}
/// A `current` given with a new Place queue picks among the files of that queue.
#[test]
fn a_place_queue_and_its_current_file_set_together() {
let mut s = session();
select(&mut s, "place");
let entry = |name: &str| json!({"params": {"svg": "<svg/>"}, "name": name, "width": 10, "height": 10});
let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]});
let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap();
assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2)));
let short = json!({"entries": [entry("d")]});
let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err();
assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0");
assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held");
}
/// A value given with a parametric shape's new `kind` is checked against that kind's range and
/// set on it, whether the tool is chosen or not.
#[test]
fn a_parametric_shape_kind_and_its_values_set_together() {
for active in [false, true] {
let mut s = session();
if active {
select(&mut s, "parametricShape");
}
let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values}));
set(&mut s, json!({"kind": "polygon"})).unwrap();
let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap();
assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}");
set(&mut s, json!({"kind": "ring"})).unwrap();
let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap();
assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}");
let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err();
assert!(e.contains("`a`"), "{e}");
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
}
}
+224 -14
View File
@@ -2062,8 +2062,8 @@ fn datasets_csv_export_imports_back_to_the_same_data_sets() {
}
/// The export's `warning` names the variables whose column a document without the variables
/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or
/// false, and a header that names a variable an earlier column defined with another kind. A
/// refuses, so it doesn't import the file: a `%` header over values, a `#` header whose values
/// aren't true or false, and a header that names a variable an earlier column defined with another kind. A
/// header that names such a variable with its kind is read with that kind, and is listed as one
/// read back with another kind.
#[test]
@@ -2081,7 +2081,9 @@ fn datasets_csv_export_warns_of_headers_a_new_document_refuses() {
let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}");
let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}");
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true));
// A `%` header's cells are read as paths of graph data files.
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({"%Rate": "5"})), (refuses("`%Rate`"), true));
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (loses("`%Rate`, `Chart`"), false));
assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true));
assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false));
assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true));
@@ -2109,18 +2111,190 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() {
}
}
/// A `%` header cell that isn't a variable's name (graph data files) is refused with its column,
/// and the import defines nothing.
/// The data `graph.setData` reports for the graph `g`: series, categories and rows.
fn graph_data(s: &mut Session, g: NodeId) -> Value {
let v = s.execute("graph.setData", &json!({"id": g.0})).unwrap();
json!({"series": v["series"], "categories": v["categories"], "rows": v["rows"]})
}
/// A `%` header defines a graph variable, and each of its cells is the path of a graph data file,
/// as the set-up page's five-column example has them. A relative path is taken from the CSV file's
/// folder. Selecting a data set gives the bound graph the data that Graph Data's Import Data and
/// Apply give it for the same file: tab- or comma-separated, the first row the series labels and the
/// first column the category labels, in UTF-16 too. An empty cell is no value.
#[test]
fn datasets_csv_refuses_graph_data_file_columns() {
fn datasets_csv_reads_graph_data_files_in_percent_columns() {
let dir = Folder::new("vars-csv-graph-files");
let tabs: &[u8] = b"\t2024\t2025\nQ1\t3\t4\nQ2\t5\t6\n";
let commas: &[u8] = b",North\nJan,7\nFeb,8\n";
let utf16: Vec<u8> = [0xFF, 0xFE].into_iter().chain(",A\r\nX,9\r\n".encode_utf16().flat_map(u16::to_le_bytes)).collect();
write(&dir.file("graphs/bill.txt"), tabs);
write(&dir.file("dat.csv"), commas);
write(&dir.file("ruiz.txt"), &utf16);
let absolute = dir.file("dat.csv");
let csv = format!(
"Name,Age,@Photos,%Graphs,#Visibility\nBill,36,b.jpg,graphs/bill.txt,true\nDat,53,d.jpg,{absolute},true\nMaria,26,r.jpg,ruiz.txt,false\nNone,1,n.jpg,,true\n"
);
let path = dir.file("data.csv");
write(&path, csv.as_bytes());
let mut s = session();
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt");
assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}");
let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx");
assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}");
let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"})).unwrap();
let g = NodeId(graph["id"].as_u64().unwrap());
let imp = s.execute("dataset.import", &json!({"path": path})).unwrap();
assert_eq!(imp["defined"], json!(["Name", "Age", "Photos", "Graphs", "Visibility"]));
assert_eq!(imp["imported"], 4);
let listed = s.execute("variable.list", &json!({})).unwrap();
assert_eq!(listed["variables"][3], json!({"name": "Graphs", "kind": "graph", "bindings": 0}));
s.execute("variable.bind", &json!({"variable": "Graphs", "ids": [g.0]})).unwrap();
// What Import Data and Apply give the graph for each file.
let sheet = |bytes: &[u8]| {
let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(bytes)));
let mut probe = session();
let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"});
let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
let mut set = data.clone();
set["id"] = json!(id.0);
probe.execute("graph.setData", &set).unwrap();
graph_data(&mut probe, id)
};
for (set, bytes) in ["Data Set 1", "Data Set 2", "Data Set 3"].into_iter().zip([tabs, commas, utf16.as_slice()]) {
s.execute("dataset.select", &json!({"name": set})).unwrap();
assert_eq!(graph_data(&mut s, g), sheet(bytes), "{set}");
}
assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[9.0]]}));
let vars = &s.doc().unwrap().doc.variables;
assert!(vars.variables.is_empty() && vars.datasets.is_empty());
assert_eq!(vars.datasets[3].values.get("Graphs"), None, "an empty cell is no value");
// A `%` header names a graph variable the document has, and `base` sets the folder of
// relative paths when the CSV comes as text.
let mut t = session();
t.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap();
let base = dir.0.to_string_lossy().into_owned();
let imp = t.execute("dataset.import", &json!({"csv": "% Sales\ndat.csv", "base": base})).unwrap();
assert_eq!(imp["defined"], json!([]));
let value = t.doc().unwrap().doc.variables.datasets[0].values.get("Sales").cloned();
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains("North") && c.contains("Feb")), "{value:?}");
}
/// A graph data file whose rows hold more values than its first row has series labels gives the
/// bound graph the series labels that Graph Data's Import Data and Apply give it: up to the last one
/// given, with no blank label for the series after it.
#[test]
fn datasets_csv_graph_data_file_keeps_the_given_series_labels() {
let dir = Folder::new("vars-csv-graph-wide");
let wide: &[u8] = b"\tA\t\nX\t1\t2\n";
write(&dir.file("wide.txt"), wide);
let path = dir.file("data.csv");
write(&path, b"Name,%Chart\na,wide.txt\n");
let mut s = session();
let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"});
let g = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
s.execute("dataset.import", &json!({"path": path})).unwrap();
s.execute("variable.bind", &json!({"variable": "Chart", "ids": [g.0]})).unwrap();
s.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap();
let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(wide)));
let mut probe = session();
let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
let mut set = data.clone();
set["id"] = json!(id.0);
probe.execute("graph.setData", &set).unwrap();
assert_eq!(graph_data(&mut s, g), graph_data(&mut probe, id));
assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[1.0, 2.0]]}));
}
/// A `%` column's file that is missing, a folder, larger than 1 MB, or gives a graph value longer
/// than 256 KB, a relative path with no
/// folder to take it from, a `base` that isn't a folder path, and a `%` header whose name is a
/// variable of another kind refuse the import with the line and column, and leave the variables and
/// data sets as they were. A file of exactly 1 MB is read, and a file named by many cells is read
/// once.
#[test]
fn datasets_csv_refuses_unreadable_graph_data_files() {
let dir = Folder::new("vars-csv-graph-refused");
write(&dir.file("ok.txt"), b"\tA\nX\t1\n");
write(&dir.file("big.txt"), &vec![b'1'; crate::cmd::MAX_GRAPH_DATA_FILE + 1]);
let at_limit = [b"\tA\nX\t2\n".as_slice(), &vec![b' '; crate::cmd::MAX_GRAPH_DATA_FILE - 7]].concat();
write(&dir.file("limit.txt"), &at_limit);
std::fs::create_dir_all(dir.file("folder.txt")).unwrap();
// 10,000 categories with long labels: under 1 MB, but a graph value over 256 KB.
let long: String = (0..10_000).map(|i| format!("category label number {i:05}\t{i}\n")).collect();
write(&dir.file("long.txt"), format!("\tA\n{long}").as_bytes());
let base = dir.0.to_string_lossy().into_owned();
let mut s = session();
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
s.execute("dataset.import", &json!({"csv": "Title\nkept"})).unwrap();
let before = s.doc().unwrap().doc.variables.clone();
let undo = s.doc().unwrap().history.undo.len();
let cases = [
(json!({"csv": "Name,%Chart\na,ok.txt\nb,missing.txt", "base": base}), "line 3, column 2: the graph data file for `Chart` can't be read"),
(json!({"csv": "Name,%Chart\na,folder.txt", "base": base}), "line 2, column 2: the graph data file for `Chart` can't be read"),
(json!({"csv": "%Chart\nbig.txt", "base": base}), "line 2, column 1: the graph data file `big.txt` for `Chart` is larger than 1048576 bytes"),
(
json!({"csv": "Name,%Chart\na,long.txt", "base": base}),
"line 2, column 2: the graph data file `long.txt` for `Chart` gives a graph value longer than 262144 bytes",
),
(json!({"csv": "%Chart\nok.txt"}), "line 2, column 1: the graph data file `ok.txt` for `Chart` is a relative path"),
(json!({"csv": "%Chart\nok.txt", "base": ""}), "`base` is empty"),
(json!({"csv": "%Chart\nok.txt", "base": 3}), "`base` must be a string"),
(json!({"csv": "%Title\nok.txt", "base": base}), "column 1: `%Title` names `Title`, which is a text variable"),
];
for (p, want) in cases {
let e = s.execute("dataset.import", &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
assert_eq!(s.doc().unwrap().doc.variables, before, "{p}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{p}");
}
let rows: String = (0..300).map(|_| "limit.txt\n").collect();
let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{rows}"), "base": base})).unwrap();
assert_eq!(imp["imported"], 300, "a 1 MB file named by 300 cells counts once against the import's limit");
let value = s.doc().unwrap().doc.variables.datasets[299].values.get("Chart").cloned();
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('2')), "{value:?}");
}
/// A `%` column's path is followed as an image variable's path is: a path on another computer (a
/// UNC path or a `file:` URL with a host) or a URL other than `file:` refuses the import with the
/// line and column and the reason, before any file is read, and leaves the variables and data sets
/// as they were. A relative path inside the CSV's folder is still read, and so is a `file:` URL
/// without a host when no folder is given.
#[test]
fn datasets_csv_refuses_graph_data_files_on_other_computers() {
let dir = Folder::new("vars-csv-graph-network");
write(&dir.file("sub/ok.txt"), b"\tA\nX\t1\n");
let path = dir.file("data.csv");
write(&path, b"Name,%Chart\na,sub/ok.txt\n");
let base = dir.0.to_string_lossy().into_owned();
let mut s = session();
let imp = s.execute("dataset.import", &json!({"path": path})).unwrap();
assert_eq!(imp["imported"], 1);
let value = s.doc().unwrap().doc.variables.datasets[0].values.get("Chart").cloned();
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('A')), "{value:?}");
// A `file:` URL without a host is a path on this computer, read without a folder to take it from.
let file = dir.file("sub/ok.txt").replace('\\', "/");
let url = if file.starts_with('/') { format!("file://{file}") } else { format!("file:///{file}") };
let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{url}")})).unwrap();
assert_eq!(imp["imported"], 1, "{url}");
let before = s.doc().unwrap().doc.variables.clone();
let undo = s.doc().unwrap().history.undo.len();
for (cell, reason) in [
(r"\\server\share\ok.txt", "the path is on another computer"),
("//server/share/ok.txt", "the path is on another computer"),
("file://server/share/ok.txt", "the path is on another computer"),
("https://example.com/ok.txt", "the link is not a file path"),
] {
let want = format!("line 3, column 2: the graph data file `{cell}` for `Chart` isn't followed: {reason}");
let p = json!({"csv": format!("Name,%Chart\na,sub/ok.txt\nb,{cell}"), "base": base});
let e = s.execute("dataset.import", &p).unwrap_err().to_string();
assert!(e.contains(&want), "{cell}: {e}");
assert_eq!(s.doc().unwrap().doc.variables, before, "{cell}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cell}");
}
}
/// Two header cells that name one variable, by the same name or by a name and its prefix, are
@@ -3537,12 +3711,12 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
// A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds
// that aren't text.
let (o, warnings) = svg_opened(&untraited, "untraited.svg");
assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}");
assert!(warnings.contains(&json!("variables that aren't text were left out: Unknown (1)")), "{warnings:?}");
assert!(o.doc().unwrap().doc.variables.variables.is_empty());
// The values of the other kinds aren't read, so one that Load Variable Library would refuse
// leaves the text variables and their values as they open.
let (o, warnings) = svg_opened(&relative, "relative.svg");
assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}");
assert!(warnings.contains(&json!("variables that aren't text were left out: Linked File (1)")), "{warnings:?}");
let vars = &o.doc().unwrap().doc.variables;
assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]);
assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into()));
@@ -3555,6 +3729,42 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
}
/// The warning about an SVG's variables that aren't text names each kind once, in the order it
/// first comes, with its count: Visibility, Linked File and Graph Data for the traits VectorCraft
/// reads, Unknown for a variable without a `trait`, and any other `trait` as the file writes it, in
/// backticks with each backtick in it doubled, so a `trait` that looks like a kind or a list entry
/// stays one entry of its own.
#[test]
fn svg_variable_data_warning_names_each_kind_left_out() {
let variables = [
("V1", Some("visibility")),
("I1", Some("fileref")),
("V2", Some("visibility")),
("T", Some("textcontent")),
("G1", Some("graphdata")),
("U1", None),
("X1", Some("unknown")),
("X2", Some("a`b (1), c")),
("X3", Some("Visibility")),
("I2", Some("fileref")),
("U2", None),
];
let declared: String = variables
.iter()
.map(|(name, t)| match t {
Some(t) => format!("<variable varName=\"{name}\" trait=\"{t}\"/>"),
None => format!("<variable varName=\"{name}\"/>"),
})
.collect();
let svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\"><variableSets><variableSet><variables>{declared}</variables></variableSet></variableSets><rect x=\"1\" y=\"1\" width=\"5\" height=\"5\"/></svg>"
);
let (o, warnings) = svg_opened(&svg, "kinds.svg");
let warning = "variables that aren't text were left out: Visibility (2), Linked File (2), Graph Data (1), Unknown (2), `unknown` (1), `a``b (1), c` (1), `Visibility` (1)";
assert!(warnings.contains(&json!(warning)), "{warnings:?}");
assert_eq!(o.doc().unwrap().doc.variables.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]);
}
/// Five variables of three kinds, defined out of every order: `beta` (text, on type named Mike),
/// `Alpha` (visibility, on a rectangle named apple), `gamma` (image, bound to nothing), `Delta`
/// (visibility, on two rectangles) and `Echo` (text, on type named Bravo).
+276
View File
@@ -453,6 +453,282 @@ fn colour_table_lock_web_shift_snap_and_sort() {
assert!(lossy < plain, "{lossy} vs {plain}");
}
/// Delete Color: the deleted colors leave the table and the file, their pixels take the nearest
/// color left, and the edit stays with the settings until another reduction is chosen.
#[test]
fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
let mut s = session(40.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
let sources = |v: &Value| -> Vec<String> {
let mut out: Vec<String> =
v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| c["source"].as_str().unwrap().to_string()).collect();
out.sort();
out
};
let base = preview(&mut s, json!({"dither": "none"}));
assert_eq!(base["colors"].as_array().unwrap().len(), 4, "{base}");
for format in ["gif", "png8"] {
let p = json!({"format": format, "dither": "none", "colorTable": {"deleted": ["#EE1100"]}});
let v = preview(&mut s, p.clone());
assert_eq!(v["colors"].as_array().unwrap().len(), 3, "{format}: {v}");
assert!(v["colors"].as_array().unwrap().iter().any(|c| c["transparent"] == true), "{format}: the transparent entry stays");
assert_eq!(sources(&v), ["#0000ff", "#ff0000"], "{format}");
let file = one(&mut s, p);
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
let img = pixels(&file);
assert_eq!(img.get_pixel(15, 5).0, [255, 0, 0, 255], "{format}: the nearest color left");
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0));
assert_eq!(distinct(&img), 3, "{format}");
}
// A color the table does not hold is no edit; sorting does not bring a deleted one back.
assert_eq!(sources(&preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#123456"]}}))).len(), 3);
let sorted = preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#ee1100"], "sort": "luminance"}}));
assert_eq!(sources(&sorted), ["#0000ff", "#ff0000"]);
// A fixed palette: colors it lacks are not made again, and deletions come out of it.
let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}}));
assert_eq!(sources(&fixed), ["#0000ff", "#ff0000"]);
let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"], "deleted": ["#ff0000"]}}));
assert_eq!(sources(&fixed), ["#0000ff"]);
// At most `colors` entries of a fixed palette, the transparent one included.
let two = preview(&mut s, json!({"dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}}));
assert_eq!(sources(&two), ["#0000ff"]);
// Deleting every opaque color is refused: the pixels need a color.
// Colors mapped to transparent do not count as left.
for table in [
json!({"deleted": ["#ff0000", "#ee1100", "#0000ff"]}),
json!({"customPalette": ["#ff0000"], "deleted": ["#ff0000"]}),
json!({"deleted": ["#0000ff", "#ee1100"], "transparent": ["#ff0000"]}),
json!({"customPalette": ["#ff0000", "#0000ff"], "deleted": ["#0000ff"], "transparent": ["#ff0000"]}),
] {
let p = json!({"colorTable": table});
let e = s.execute("document.exportForWeb.preview", &p).err().map(|e| e.to_string()).unwrap_or_default();
assert!(e.contains(cmd::webexport::KEEP_ONE), "{p}: {e}");
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
}
for bad in [
json!({"colorTable": {"deleted": ["nope"]}}),
json!({"colorTable": {"customPalette": ["#ff000080"]}}),
json!({"colorTable": {"deleted": vec!["#ff0000"; 257]}}),
] {
assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}");
assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}");
}
// A deleted color leaves the other lists; JPEG and PNG-24 have no table to edit.
let table = json!({
"deleted": ["#ee1100"], "customPalette": ["#ff0000", "#ee1100", "#0000ff"], "locked": ["#EE1100", "#0000ff"],
"transparent": ["#ee1100"], "webShift": ["#ee1100"],
});
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
let t = r["settings"]["colorTable"].clone();
assert_eq!((&t["locked"], &t["transparent"], &t["webShift"]), (&json!(["#0000ff"]), &json!([]), &json!([])));
assert_eq!(t["deleted"], json!(["#ee1100"]));
for format in ["jpg", "png24"] {
assert!(preview(&mut s, json!({"format": format, "colorTable": t.clone()})).get("colors").is_none(), "{format}");
}
// The remembered edit survives other keys and a format change, and goes with another reduction.
let r = run(&mut s, "webExport.settings", json!({"colors": 64, "format": "png8"}));
assert_eq!(r["settings"]["colorTable"]["deleted"], json!(["#ee1100"]));
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
assert_eq!((&r["settings"]["colorTable"]["deleted"], &r["settings"]["colorTable"]["customPalette"]), (&json!([]), &json!([])));
// A saved preset keeps the edit.
run(&mut s, "webExport.presets.save", json!({"name": "No near red", "dither": "none", "colorTable": {"deleted": ["#ee1100"]}}));
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
}
/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the
/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the
/// pixels of the colors mapped to transparent become transparent.
#[test]
fn colour_table_fixed_palette_keeps_an_opaque_color() {
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
let mut s = session(40.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
for table in [
json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}),
json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}),
] {
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table});
let v = run(&mut s, "document.exportForWeb.preview", p.clone());
let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect();
assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}");
let img = pixels(&one(&mut s, p.clone()));
let alpha = |x: u32| img.get_pixel(x, 5).0[3];
assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}");
}
// A color mapped to transparent that no pixel takes leaves its slot to an opaque color.
let mut u = session(20.0, 10.0);
rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00");
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}});
let img = pixels(&one(&mut u, p));
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255]));
// At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry.
let full: Vec<String> =
std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect();
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}});
let img = pixels(&one(&mut s, p));
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0));
// With one opaque color and 255 mapped to transparent, the last of those does not fit, and its
// pixels still become transparent rather than taking the opaque color nearest them.
let mut d = session(30.0, 10.0);
rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee");
let clear: Vec<String> = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect();
let palette: Vec<String> = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect();
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}});
let img = pixels(&one(&mut d, p));
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0));
// Without transparent pixels the colors mapped to transparent still take one slot together.
let mut t = session(30.0, 10.0);
rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100");
rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff");
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {
"customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"],
}});
let v = run(&mut t, "document.exportForWeb.preview", p.clone());
assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}");
let img = pixels(&one(&mut t, p));
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255]));
}
/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in
/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is
/// the file.
#[test]
fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() {
let mut s = session(30.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00");
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null);
for format in ["gif", "png8"] {
let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}});
let v = preview(&mut s, p.clone());
let c = entry(&v, "#0000ff");
assert_eq!(
(c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()),
(Some("#ff8800"), Some(true), Some(true), Some(false)),
"{format}: {v}"
);
assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000")));
let file = one(&mut s, p);
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
let img = pixels(&file);
assert_eq!(
(img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0),
([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]),
"{format}"
);
assert_eq!(distinct(&img), 3, "{format}");
}
// A shifted color is kept when the colors are reduced, as a locked one is.
let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}}));
assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}");
// With one slot to keep, the shifted color takes it before a locked one.
let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}});
let first = preview(&mut s, p);
assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}");
// A source the table does not hold shifts nothing, and the shift stays with the settings.
let base = preview(&mut s, json!({"dither": "none"}));
let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}}));
assert_eq!(absent["colors"], base["colors"]);
// Two colors may be shifted to one color and keep their own sources.
let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}}));
assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456")));
assert_eq!(entry(&same, "#00ff00")["shifted"], false);
// A shift by hand wins over web shift, web snap and a lock; transparency wins over it.
let p =
json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}});
let c = entry(&preview(&mut s, p), "#0000ff");
assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true)));
let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}});
let v = preview(&mut s, clear.clone());
assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}");
assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0);
// The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and
// the web shift of a color shifted by hand.
let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]});
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
let t = &r["settings"]["colorTable"];
assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([])));
// Another reduction keeps the shifts; a saved preset keeps them.
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}}));
assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101");
// Bad shifts are refused and change nothing.
let many: serde_json::Map<String, Value> = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect();
for bad in [
json!({"nope": "#000000"}),
json!({"#ff0000": "nope"}),
json!({"#ff0000": "#ff000080"}),
json!({"#ff000080": "#000000"}),
json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}),
json!({"#f00": "#000000", "#ff0000": "#ffffff"}),
Value::Object(many),
] {
let p = json!({"colorTable": {"shifted": bad}});
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}");
assert!(s.execute("webExport.settings", &p).is_err(), "{p}");
}
assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
// Settings saved before shifts existed still read.
let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap();
assert!(old.color_table.shifted.is_empty());
}
/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near
/// another one does not take in that color's pixels.
#[test]
fn lossy_does_not_spread_a_shifted_color_into_another() {
let mut s = session(30.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000");
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}});
let img = pixels(&one(&mut s, p));
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255]));
}
/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to
/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels.
#[test]
fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() {
let mut s = session(30.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6");
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff");
rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6");
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}});
let img = pixels(&one(&mut s, p));
let near_blue = [20, 20, 230, 255];
for x in 0..30 {
let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue };
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
}
}
/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not
/// take a color that snaps far from it.
#[test]
fn lossy_compares_pixels_with_the_snapped_colors() {
let mut s = session(20.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a");
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000");
let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50})));
for x in 0..20 {
let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] };
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
}
}
#[test]
fn presets_and_remembered_settings() {
let mut s = two_colours();
+118
View File
@@ -167,6 +167,124 @@ fn adjust_adjoining_scales_the_neighbours() {
assert_eq!(points(&s, id), vec![(0.5, 4.0, 1.0)]);
}
/// A line with a discontinuous point in the middle: 1× before it, 2× after it.
fn pair_session(points: serde_json::Value) -> (Session, NodeId) {
let (mut s, id) = line_session();
s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": points})).unwrap();
s.doc_mut().unwrap().mark_saved();
(s, id)
}
#[test]
fn paired_set_edits_both_halves_in_one_step() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20});
assert_eq!(set(&mut s, p.clone()), 1);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 2.0, 1.0), (0.5, 3.0, 4.0), (1.0, 1.0, 1.0)]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let after = s.doc().unwrap().doc.clone();
// The same widths again change nothing and record no undo step.
set(&mut s, p);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
}
#[test]
fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
// The incoming half doubles and the outgoing half halves: the start doubles, the end halves.
set(
&mut s,
json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 10, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.5, 2.0, 2.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]);
// A discontinuous point at the start has only a point after it to adjust.
let (mut s, id) = pair_session(json!([[0, 1, 1], [0, 2, 2], [1, 1, 1]]));
set(
&mut s,
json!({"id": id.0, "index": 0, "t": 0, "left": 10, "right": 10, "outIndex": 1, "outLeft": 20, "outRight": 20, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]);
}
/// Three points each within 1e-6 of the next: the first two are the pair, and the third, though
/// within 1e-6 of the outgoing half, is the point after the pair that the outgoing half adjusts.
#[test]
fn paired_set_adjusts_the_point_after_a_chained_pair() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.50000075, 2, 2], [0.5000015, 1, 1], [1, 1, 1]]));
set(
&mut s,
json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 1.0, 1.0), (0.5000015, 0.5, 0.5), (1.0, 1.0, 1.0)]);
}
#[test]
fn single_width_only_leaves_one_continuous_point() {
for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20, "single": single});
assert_eq!(set(&mut s, p), 1);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{single}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
}
// With Adjust Adjoining, each neighbor follows the change of the half beside it.
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "single": "incoming", "adjustAdjoining": true});
set(&mut s, p);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]);
}
#[test]
fn paired_set_refuses_what_is_not_one_discontinuous_point() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.25, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [0.75, 3, 3], [0.75, 3, 3], [0.75, 3, 3], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let pair = |extra: serde_json::Value| {
let mut p = json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "outIndex": 3, "outLeft": 5, "outRight": 5});
for (k, v) in extra.as_object().unwrap() {
if v.is_null() {
p.as_object_mut().unwrap().remove(k);
} else {
p[k] = v.clone();
}
}
p
};
for p in [
pair(json!({"index": 1, "t": 0.25, "outIndex": 2})),
pair(json!({"outIndex": 4})),
pair(json!({"index": 3, "outIndex": 2})),
pair(json!({"outIndex": 99})),
pair(json!({"outIndex": "3"})),
pair(json!({"outIndex": -1})),
pair(json!({"t": 0.6})),
pair(json!({"index": 4, "t": 0.75, "outIndex": 5})),
pair(json!({"index": null})),
pair(json!({"outLeft": null})),
pair(json!({"outRight": -1})),
pair(json!({"outLeft": 1.0e6})),
pair(json!({"single": "both"})),
pair(json!({"single": true})),
pair(json!({"outIndex": null})),
pair(json!({"outIndex": null, "outLeft": null})),
json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}),
] {
assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}");
assert_eq!(s.doc().unwrap().doc, before, "{p}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
}
#[test]
fn flipping_along_swaps_the_sides_of_a_discontinuous_point() {
let (mut s, id) = line_session();
+18
View File
@@ -40,6 +40,24 @@ fn the_width_tool_edits_a_compound_paths_stroke() {
assert_eq!(s.journal.last().unwrap().1["id"], json!(c.0));
}
/// A compound path whose stroke draws with a brush: a press or a double-click on a member puts the
/// tool's reason in the status bar and leaves the stroke and the undo history as they were.
#[test]
fn the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone() {
let (mut s, c, _) = compound();
s.execute("brush.apply", &json!({"ids": [c.0], "name": "3 pt. Round"})).unwrap();
let steps = s.journal.len();
let v = ViewInfo::default();
s.select_tool("width", v).unwrap();
for (kind, reason) in [(PointerKind::Down, true), (PointerKind::Drag, false), (PointerKind::Up, false), (PointerKind::DoubleClick, true)] {
let ui = s.pointer(&PointerEvent::new(kind, 200.0, 301.0), v).unwrap();
let said = ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m == vectorcraft_tools::distort::KEEPS_SIZE));
assert_eq!(said, reason, "{kind:?}: {ui:?}");
}
assert_eq!(profile(&s, c), None);
assert_eq!(s.journal.len(), steps, "no command ran");
}
#[test]
fn width_point_commands_given_a_member_edit_the_compound() {
let (mut s, c, members) = compound();
+122 -5
View File
@@ -480,8 +480,8 @@ fn reflect_and_shear_tools() {
assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}");
}
/// Reflect and Shear return an error for an `axis` they don't take (Reflect's names it and also
/// takes an angle): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect
/// Reflect and Shear return an error for an `axis` they don't take, naming it (both also take an
/// angle, Shear's from -359° to 359°): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect
/// then reflects across the vertical axis and Shear shears along the horizontal one.
#[test]
fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
@@ -489,13 +489,17 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
let n = undo_len(&s);
let reflect = "axis must be \"vertical\", \"horizontal\" or an angle in degrees";
let shear = "`axis` must be one of horizontal, vertical";
let shear = "axis must be \"horizontal\", \"vertical\" or an angle in degrees from -359 to 359";
for (cmd, p, msg) in [
("object.reflect", json!({"axis": "diagonal", "origin": [0, 0]}), format!("{reflect}, not `diagonal`")),
("object.reflect", json!({"axis": "45", "origin": [0, 0]}), format!("{reflect}, not `45`")),
("object.reflect", json!({"axis": true, "origin": [0, 0]}), format!("{reflect}, not `true`")),
("object.shear", json!({"angle": 30, "axis": "diagonal"}), shear.to_string()),
("object.shear", json!({"angle": 30, "axis": 90}), shear.to_string()),
("object.shear", json!({"angle": 30, "axis": "diagonal"}), format!("{shear}, not `diagonal`")),
("object.shear", json!({"angle": 30, "axis": "90"}), format!("{shear}, not `90`")),
("object.shear", json!({"angle": 30, "axis": 360}), format!("{shear}, not `360`")),
("object.shear", json!({"angle": 30, "axis": -359.5}), format!("{shear}, not `-359.5`")),
("object.shear", json!({"angle": 30, "axis": [45]}), format!("{shear}, not `[45]`")),
("object.shear", json!({"angle": 30, "axis": false}), format!("{shear}, not `false`")),
] {
let e = s.execute(cmd, &p).expect_err(&format!("{cmd} {p}"));
assert_eq!(e.to_string(), format!("invalid parameters for `{cmd}`: {msg}"));
@@ -511,6 +515,119 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}");
}
/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant
/// opposite ways, and 120 and 300 slant as -60 does.
#[test]
fn shear_angles_slant_by_their_tangent() {
let run = 100.0 * 60f64.to_radians().tan();
for (angle, want) in [
(60.0, Rect::new(-run, 0.0, 100.0, 100.0)),
(-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
(120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
(300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
(-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)),
] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap();
assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a));
}
}
/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no
/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded.
#[test]
fn shear_rejects_angles_with_no_shear_or_out_of_range() {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
let n = undo_len(&s);
let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear");
let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}");
for (angle, msg) in [
(90.0, none(90.0)),
(-90.0, none(-90.0)),
(270.0, none(270.0)),
(-270.0, none(-270.0)),
(90.0 + 1e-12, none(90.0 + 1e-12)),
(360.0, range(360.0)),
(-359.5, range(-359.5)),
(1e300, range(1e300)),
] {
let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string());
assert_eq!(e.to_string(), msg);
}
assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle");
assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a));
assert_eq!(undo_len(&s), n, "no undo step");
}
/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact
/// coordinates and no undo step is recorded.
#[test]
fn shear_by_0_and_180_changes_nothing() {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
let before = bounds(&s, a);
let n = undo_len(&s);
for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] {
for axis in ["horizontal", "vertical"] {
s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap();
assert_eq!(bounds(&s, a), before, "{angle} {axis}");
assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step");
}
}
}
/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point
/// slides along the axis by the tangent of the shear angle times its distance across the axis
/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again
/// repeats it; 0° and 90° shear as the named axes do, and a copy leaves the original in place.
#[test]
fn shear_along_an_axis_at_an_angle() {
let anchors = |s: &Session, id: NodeId| -> Vec<Point> {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect()
};
// The axis's direction and the direction a quarter turn counter-clockwise from it, with y down.
let sheared = |p: Point, o: Point, axis: f64, angle: f64| {
let (a, k) = (axis.to_radians(), angle.to_radians().tan());
let (along, across) = (Vec2::new(a.cos(), -a.sin()), Vec2::new(-a.sin(), -a.cos()));
p + along * (k * (p - o).dot(across))
};
let near = |a: &[Point], b: &[Point]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| p.distance(*q) < 1e-9);
let o = Point::new(20.0, 30.0);
for (axis, angle) in [(45.0, 30.0), (-120.5, 20.0), (359.0, 30.0), (-359.0, -30.0), (30.0, 30.0)] {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
let before = anchors(&s, a);
let n = undo_len(&s);
s.execute("object.shear", &json!({"angle": angle, "axis": axis, "origin": [o.x, o.y]})).unwrap();
let want: Vec<Point> = before.iter().map(|p| sheared(*p, o, axis, angle)).collect();
assert!(near(&anchors(&s, a), &want), "{axis}° {angle}°: {:?}, not {want:?}", anchors(&s, a));
assert_eq!(undo_len(&s), n + 1, "one undo step");
s.execute("object.transformAgain", &json!({})).unwrap();
let again: Vec<Point> = want.iter().map(|p| sheared(*p, o, axis, angle)).collect();
assert!(near(&anchors(&s, a), &again), "Transform Again at {axis}°: {:?}", anchors(&s, a));
}
for (named, axis) in [("horizontal", 0.0), ("vertical", 90.0), ("vertical", -270.0)] {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
s.execute("object.shear", &json!({"angle": 30, "axis": named, "origin": [o.x, o.y]})).unwrap();
let by_name = anchors(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.shear", &json!({"angle": 30, "axis": axis, "origin": [o.x, o.y]})).unwrap();
assert!(near(&anchors(&s, a), &by_name), "{axis}° shears as {named}: {:?}, not {by_name:?}", anchors(&s, a));
}
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
let before = anchors(&s, a);
s.execute("object.shear", &json!({"angle": 30, "axis": 45, "origin": [o.x, o.y], "copy": true})).unwrap();
assert!(near(&anchors(&s, a), &before), "the original stays: {:?}", anchors(&s, a));
let copy = *s.doc().unwrap().selection.objects.first().unwrap();
assert_ne!(copy, a, "the copy is selected");
let want: Vec<Point> = before.iter().map(|p| sheared(*p, o, 45.0, 30.0)).collect();
assert!(near(&anchors(&s, copy), &want), "the copy is sheared: {:?}", anchors(&s, copy));
}
#[test]
fn distort_command_maps_corners() {
let mut s = session();