Merge main into feat/field-x-multiply

This commit is contained in:
dotCooCoo
2026-11-18 06:26:33 -08:00
463 changed files with 35689 additions and 2252 deletions
+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]
+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]
+331
View File
@@ -1289,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
@@ -1400,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"]});
@@ -1569,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() {
@@ -1612,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();
@@ -2074,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);
+30
View File
@@ -1083,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());
+66 -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]
@@ -6292,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() {
+239
View File
@@ -529,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
@@ -213,6 +213,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()
}
@@ -481,6 +592,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();
@@ -643,6 +802,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]
@@ -904,6 +1102,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();
-28
View File
@@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() {
}
}
/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first
/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does
/// not refuse it, and one in the first asset does.
#[test]
fn confined_single_file_pdf_checks_the_document_it_carries() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("single-pdf-away");
let home = Folder::new("single-pdf-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
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();
let placed = place(&mut s, &photo);
let mut assets = vec![];
for id in [rect, placed] {
assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap());
}
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
let reversed = [assets[1], assets[0]];
let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{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
+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());
}
}
}
}
+162
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();
+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");
+111
View File
@@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_
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)));
}
}
+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");
}
+49
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,38 @@ 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.
+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();
+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}");
}
+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");
}
}
+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();