Merge main into feat/symbolism-shift-gestures

This commit is contained in:
dotCooCoo
2026-11-19 06:05:13 -08:00
518 changed files with 65995 additions and 2383 deletions
@@ -234,3 +234,65 @@ fn a_linked_handle_makes_the_anchor_smooth() {
assert!(s.doc().unwrap().doc == before, "a refused request changed the document");
assert_eq!(undo_steps(&s), undo);
}
/// A linked `path.setHandle` request repeated as it was changes nothing and records no undo step,
/// even where turning the other handle again from its stored end rounds it differently, near the
/// origin and 3e6 pt from it. On a smooth anchor whose other handle is off line by 1e-8, linking
/// the handle where it is still turns the other one into line and records an undo step, at both
/// places. 3.9e6 pt from the origin, a 1.5e-9 pt handle at right angles and a handle 1e-9 pt off
/// line are turned too, and so is an other handle on the same side as the linked one.
#[test]
fn a_repeated_linked_handle_records_no_undo_step() {
let (mut s, id) = long_path(100);
let near = anchor(&s, id, 5).p;
for p in [near, Point::new(3e6, -2e6)] {
let corner =
Anchor { p, h_in: p + Vec2::new(117.73528366134629, 927.4795508230089), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner };
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
path.subpaths[0].anchors[5] = corner;
for i in 0..40 {
let t = f64::from(i) * 0.37;
let to = p + Vec2::new(8.028549152229672 * t.cos() + 0.1 * f64::from(i), -9.388200339328929 * t.sin() - 0.03 * f64::from(i));
let link = json!({"id": id.0, "anchor": 5, "which": "out", "x": to.x, "y": to.y, "link": true});
s.execute("path.setHandle", &link).unwrap();
let (steps, a) = (undo_steps(&s), anchor(&s, id, 5));
s.execute("path.setHandle", &link).unwrap();
assert_eq!(undo_steps(&s), steps, "request {i} at {p:?} repeated recorded an undo step");
assert_eq!(anchor(&s, id, 5), a, "request {i} at {p:?} repeated changed the anchor");
}
let skewed = Anchor { p, h_in: p + Vec2::new(-10.0, 1e-8), h_out: p + Vec2::new(10.0, 0.0), kind: AnchorKind::Smooth };
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
path.subpaths[0].anchors[5] = skewed;
let steps = undo_steps(&s);
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": skewed.h_out.x, "y": skewed.h_out.y, "link": true}))
.unwrap();
assert_eq!(undo_steps(&s), steps + 1, "the off-line handle at {p:?} was left as it was");
let a = anchor(&s, id, 5);
assert!(a.h_out == skewed.h_out && a.h_in.y == p.y, "{a:?}");
}
// Far from the origin, a short handle at right angles and a handle 1e-9 pt off line are still
// turned into line.
let p = Point::new(3.9e6, 0.0);
for h_in in [Point::new(p.x, 1.5e-9), Point::new(p.x - 10.0, 1e-9)] {
let off = Anchor { p, h_in, h_out: p + Vec2::new(10.0, 0.0), kind: AnchorKind::Smooth };
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
path.subpaths[0].anchors[5] = off;
let steps = undo_steps(&s);
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": off.h_out.x, "y": off.h_out.y, "link": true})).unwrap();
assert_eq!(undo_steps(&s), steps + 1, "the handle at {h_in:?} was left as it was");
let a = anchor(&s, id, 5);
assert!(a.h_in.y == 0.0 && a.h_in.x < p.x, "{a:?}");
}
// An other handle on the same side as the linked one is turned to the far side.
let p = near;
let same = Anchor { p, h_in: p + Vec2::new(5.0, 0.0), h_out: p + Vec2::new(10.0, 0.0), kind: AnchorKind::Smooth };
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
path.subpaths[0].anchors[5] = same;
let steps = undo_steps(&s);
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": same.h_out.x, "y": same.h_out.y, "link": true})).unwrap();
assert_eq!(undo_steps(&s), steps + 1, "the handle on the same side was left as it was");
assert!(anchor(&s, id, 5).h_in.distance(p + Vec2::new(-5.0, 0.0)) < 1e-9, "{:?}", anchor(&s, id, 5));
}
+106
View File
@@ -312,6 +312,112 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
}
/// A blue 100 × 100 square revolved straight on about its left edge with `params`, with the red
/// 10 × 20 graphic "Mark" mapped onto its side `x` pt from the middle, collected as a 3D asset named
/// "Ball" in `format`.
fn revolved(format: &str, params: Value, x: f64) -> (Session, u64) {
let mut s = session();
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap();
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0});
p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone());
run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": p}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "x": x, "ids": [id]}));
run(&mut s, "layer.setProps", json!({"id": id, "name": "Ball"}));
let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap();
(s, asset)
}
#[test]
fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() {
for (format, names) in [
("usda", vec!["Ball.usda", "Ball-texture-1.png"]),
("usdz", vec!["Ball.usdz"]),
("gltf", vec!["Ball.gltf"]),
("obj", vec!["Ball.obj", "Ball.mtl", "Ball-texture-1.png"]),
] {
let (mut s, _) = revolved(format, json!({}), 0.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}");
}
// The side unrolled is 200π around the axis (the square's far edge is 100 from it) by 300
// along the profile (its edge on the axis sweeps nothing): 512 × 245 pixels, blue with the red
// graphic at the middle.
let (mut s, _) = revolved("usda", json!({}), 0.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512})));
let picture = &out[1].1;
let scale = 512.0 / (200.0 * std::f64::consts::PI);
assert_eq!(image::load_from_memory(picture).unwrap().to_rgba8().dimensions(), (512, (300.0 * scale).ceil() as u32));
let middle = (150.0 * scale) as u32;
assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle));
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face");
// Moved 50 pt around the axis, the graphic moves as far across the picture.
let (mut s, _) = revolved("usda", json!({}), 50.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512})));
let moved = (256.0 + 50.0 * scale).round() as u32;
assert!(is_red(pixel(&out[1].1, moved, middle)) && is_blue(pixel(&out[1].1, 256, middle)));
// An OBJ's texture coordinates stay inside the picture, as OBJ reads them (up from its bottom).
let (mut s, _) = revolved("obj", json!({}), 0.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let obj = String::from_utf8(out[0].1.clone()).unwrap();
let vt: Vec<f64> = obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ').map(|v| v.parse::<f64>().unwrap())).collect();
assert!(!vt.is_empty() && vt.iter().all(|v| (-1e-9..=1.0 + 1e-9).contains(v)), "{vt:?}");
assert!(String::from_utf8(out[1].1.clone()).unwrap().contains("map_Kd -clamp on Ball-texture-1.png"));
// glTF embeds the picture, and the side's coordinates are its TEXCOORD_0.
let (mut s, _) = revolved("gltf", json!({}), 0.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let g: Value = serde_json::from_slice(&out[0].1).unwrap();
assert_eq!(g["images"].as_array().map(Vec::len), Some(1));
assert!(g["meshes"].as_array().unwrap().iter().any(|m| !m["primitives"][0]["attributes"]["TEXCOORD_0"].is_null()));
}
#[test]
fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() {
let (mut s, asset) = revolved("usda", json!({"angle": 270.0}), 0.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Ball.usda", "Ball-texture-1.png"]);
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side");
let d = &s.doc().unwrap().doc;
let id = d.asset(asset).unwrap().nodes[0].0;
// Without its graphics the surface is one plain mesh, as before.
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Ball.usda"]);
assert_eq!(String::from_utf8(out[0].1.clone()).unwrap().matches("def Mesh").count(), 1);
}
#[test]
fn a_revolved_groups_graphics_export_on_its_longest_members_side_only() {
let mut s = session();
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
let a = run(&mut s, "path.create", json!({"d": "M100 100L140 100L140 200L100 200Z"}))["id"].as_u64().unwrap();
let b = run(&mut s, "path.create", json!({"d": "M100 120L160 120L160 130L100 130Z"}))["id"].as_u64().unwrap();
let g = run(&mut s, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [g]}));
run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [g]}));
let d = &s.doc().unwrap().doc;
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap();
assert_eq!(parts.len(), 2);
let textured: Vec<usize> = parts.iter().enumerate().filter(|(_, p)| p.graphics.is_some()).map(|(k, _)| k).collect();
assert_eq!(textured, [0], "the taller member's side");
// A half-opaque member: as on the canvas, its opacity applies to its side and the graphics
// together, and the graphics keep the opacity of the fill.
run(&mut s, "transparency.set", json!({"ids": [a], "opacity": 50}));
let d = &s.doc().unwrap().doc;
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap();
let graphics = parts[0].graphics.as_ref().unwrap();
assert_eq!((graphics.opacity, graphics.object), (1.0, 0.5));
assert!((parts[0].color[3] - 0.5).abs() < 1e-6, "{:?}", parts[0].color);
}
#[test]
fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() {
let half = |a: u8| (120..=135).contains(&a);
+98 -6
View File
@@ -114,44 +114,49 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"bristle-brushes",
"pattern-borders",
"scatter-shapes",
"stipple",
"game-trails",
"energy-beams",
"dry-media",
"tech-circuit",
"arrows"
"arrows",
"image-brush"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
// Looked up by id, so a library added to the list does not shift these checks.
let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap();
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
assert_eq!(
lib["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"]
);
assert_eq!(libs[0]["count"].as_u64(), Some(5));
assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5));
let trails = run(&mut s, "brush.library", json!({"library": "game-trails"}));
assert_eq!(
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"]
);
assert_eq!(libs[7]["count"].as_u64(), Some(4));
assert_eq!(entry("game-trails")["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[8]["count"].as_u64(), Some(4));
assert_eq!(entry("energy-beams")["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[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
assert_eq!((entry("dry-media")["name"].as_str(), entry("dry-media")["count"].as_u64()), (Some("Dry Media"), Some(4)));
let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"}));
assert_eq!(
arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
);
assert_eq!((libs[11]["name"].as_str(), libs[11]["count"].as_u64()), (Some("Arrows"), Some(5)));
assert_eq!((entry("arrows")["name"].as_str(), entry("arrows")["count"].as_u64()), (Some("Arrows"), Some(5)));
assert_eq!((entry("stipple")["name"].as_str(), entry("stipple")["count"].as_u64()), (Some("Stipple"), 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]}));
@@ -166,10 +171,12 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("bristle-brushes", "bristle"),
("pattern-borders", "pattern"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
("game-trails", "art"),
("energy-beams", "art"),
("dry-media", "art"),
("arrows", "art"),
("image-brush", "scatter"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
@@ -200,6 +207,43 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "image-brush").unwrap();
let names = ["Soft Bloom", "Halftone Field", "Solar Grain", "Color Flecks"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
assert_eq!(lib.doc.images.len(), 4);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
for b in &lib.brushes {
let BrushKind::Scatter(sc) = &b.kind else { panic!("{} is not a scatter brush", b.name) };
let NodeKind::Image(image) = &sc.art.kind else { panic!("{} has no image stamp", b.name) };
assert!(lib.doc.images.get(&image.key).is_some_and(|blob| blob.bytes.starts_with(b"\x89PNG\r\n\x1a\n")));
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke());
assert!(pieces.len() >= 3 && pieces.iter().all(|p| matches!(p.kind, NodeKind::Image(_))), "{}", b.name);
// A short accent shows at least one stamp at a 1 pt stroke.
let short = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(10.0), &black_stroke());
assert!(!short.is_empty() && short.iter().all(|p| matches!(p.kind, NodeKind::Image(_))), "{} on a 10 pt line", b.name);
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "image-brush", "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!(doc(&s).images.contains_key(&image.key), "{} pixels were not copied", b.name);
}
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();
let mut saved_brushes = vectorcraft_brush::library(&reopened);
for brush in &mut saved_brushes {
if let BrushKind::Scatter(sc) = &mut brush.kind {
sc.art.id = NodeId(0); // Loaded image art is given a fresh document node ID.
}
}
assert_eq!(saved_brushes, lib.brushes);
assert_eq!(reopened.images, lib.doc.images);
}
/// Every path of brush art `n`: (anchors, opacity).
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
let mut out = vec![];
@@ -228,6 +272,54 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
}
#[test]
fn stipple_library_draws_dot_textures_and_survives_save() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "stipple").unwrap();
let names: Vec<&str> = lib.brushes.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["Fine Stipple", "Dense Stipple", "Soft Stipple", "Bold Stipple"]);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
for b in &lib.brushes {
let BrushKind::Scatter(scatter) = &b.kind else { panic!("{} is not a scatter brush", b.name) };
assert_eq!(scatter.colorization, vectorcraft_brush::Colorization::Tints);
assert!(scatter.spacing.0 > 0.0 && scatter.spacing.1 >= scatter.spacing.0);
// A red stroke: the black dots take it as their color, and Soft Stipple's dots stay translucent.
let red = vectorcraft_color::Color::rgb(0.8, 0.1, 0.2);
let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(red), 1.0);
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.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()), "{}", b.name);
let mut dots = vec![];
for piece in &pieces {
piece.walk(&mut |c| {
if c.path_data().is_some() {
let fill = c.appearance.fill().unwrap_or_else(|| panic!("a {} dot has no fill", b.name));
dots.push((fill.paint.color(), fill.opacity));
}
});
}
assert!(!dots.is_empty(), "{}", b.name);
for (color, opacity) in dots {
let rgb = color.unwrap_or_else(|| panic!("a {} dot is not a solid color", b.name)).to_rgb();
assert!(rgb.iter().zip(red.to_rgb()).all(|(a, e)| (a - e).abs() < 1e-4), "{} dot is {rgb:?}, not the stroke color", b.name);
if b.name == "Soft Stipple" {
assert!(opacity > 0.0 && opacity < 1.0, "Soft Stipple dot opacity {opacity}");
} else {
assert_eq!(opacity, 1.0, "{}", b.name);
}
}
let before = undo_len(&s);
let result = run(&mut s, "brush.addFromLibrary", json!({"library": "stipple", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&result["added"]), [b.name.as_str()]);
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);
}
#[test]
fn arrows_library_lists_renders_and_applies_original_brushes() {
let mut s = session();
+74 -1
View File
@@ -1572,6 +1572,79 @@ fn freehand_points_record_the_pens_tilt_bearing_and_rotation() {
assert_eq!(tilt.unwrap().at(0.9), vectorcraft_doc::PressureProfile::MID, "half way over without one");
}
/// The airbrush finger wheel recorded on the stroke `id`.
fn wheel_of(s: &Session, id: NodeId) -> Option<PressureProfile> {
node(s, id).appearance.stroke().and_then(|st| st.wheel.clone())
}
/// `path.freehand` points carry an airbrush pen's finger wheel seventh (or as `wheel`), 0..1; the
/// stroke keeps it, a continued or reversed stroke keeps it in step, a wheel that is not a number
/// or is outside 0..1 is refused, and the Paintbrush records it from the pen. A Calligraphic brush with
/// Size on Stylus Wheel draws it, and it lasts through saving, new art leaving it behind.
#[test]
fn freehand_points_record_the_stylus_wheel() {
let mut s = session();
let draw = |s: &mut Session, points: Value| {
NodeId(s.execute("path.freehand", &json!({"points": points, "style": "brush"})).unwrap()["id"].as_u64().unwrap())
};
let id = draw(&mut s, json!([[0, 50, null, null, null, null, 0], [100, 50, null, null, null, null, 1]]));
let w = wheel_of(&s, id).unwrap();
assert!(w.at(0.0) < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}");
assert_eq!(pose_of(&s, id), (None, None, None), "the wheel alone");
assert_eq!(pressure_of(&s, id), None);
// As keys; a point without one is half way.
let id = draw(&mut s, json!([{"x": 0, "y": 150, "wheel": 0}, {"x": 50, "y": 150}, {"x": 100, "y": 150, "wheel": 1}]));
let w = wheel_of(&s, id).unwrap();
assert!(w.at(0.0) < 1e-6 && (w.at(0.5) - 0.5).abs() < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}");
// No wheel given: none recorded.
let id = draw(&mut s, json!([[0, 250, 0.5, 30, 0, 90], [100, 250, 0.5, 30, 0, 90]]));
assert_eq!(wheel_of(&s, id), None);
// Not a number: refused, and nothing drawn.
let before = s.doc().unwrap().doc.clone();
let err = s.execute("path.freehand", &json!({"points": [[0, 0, null, null, null, null, "0.5"], [10, 0]], "style": "brush"}));
assert!(err.unwrap_err().to_string().contains("`wheel` must be a number"));
assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged");
// Outside 0..1: refused, and nothing drawn.
for points in [json!([{"x": 0, "y": 0, "wheel": -2}, {"x": 10, "y": 0}]), json!([[0, 0], [10, 0, null, null, null, null, 9]])] {
let err = s.execute("path.freehand", &json!({"points": points, "style": "brush"}));
assert!(err.unwrap_err().to_string().contains("`wheel` must be from 0 to 1"));
assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged");
}
// Continued at its end by a stroke without a wheel: the old part keeps it, the new one is half way.
let id = draw(&mut s, json!([[0, 350, null, null, null, null, 1], [100, 350, null, null, null, null, 1]]));
s.execute("path.freehand", &json!({"points": [[100, 350], [200, 350]], "style": "brush", "extend": {"id": id.0, "end": "end"}})).unwrap();
let w = wheel_of(&s, id).unwrap();
assert!((w.at(0.25) - 1.0).abs() < 1e-6 && (w.at(0.9) - 0.5).abs() < 1e-6, "{w:?}");
// The Paintbrush records it, and a brush with Size on Stylus Wheel draws it.
let params = json!({"angle": 0, "roundness": 100, "size": 6, "variation": [0, 0, 4], "modes": ["fixed", "fixed", "stylusWheel"]});
s.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap();
s.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap();
let v = ViewInfo::default();
s.select_tool("paintbrush", v).unwrap();
let strokes = |s: &mut Session, y: f64, wheel: Option<f32>| {
let pen = wheel.map(|w| PenPose { wheel: Some(w), ..PenPose::default() });
for (k, x) in [(PointerKind::Down, 20.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 220.0), (PointerKind::Up, 320.0)] {
s.pointer(&PointerEvent { pen, ..PointerEvent::new(k, x, y) }, v).unwrap();
}
let id = s.doc().unwrap().selection.objects[0];
select(s, &[]);
id
};
let far = strokes(&mut s, 500.0, Some(1.0));
let near = strokes(&mut s, 600.0, Some(0.0));
let mouse = strokes(&mut s, 700.0, None);
assert_eq!(wheel_of(&s, far).map(|w| w.at(0.5)), Some(1.0));
assert_eq!(wheel_of(&s, mouse), None, "a mouse has no wheel");
let height = |s: &Session, id| brushed_bounds(s, id).height();
assert!((height(&s, far) - 10.0).abs() < 0.1 && (height(&s, near) - 2.0).abs() < 0.1, "{} {}", height(&s, far), height(&s, near));
assert!((height(&s, mouse) - 6.0).abs() < 0.1, "the brush's own size: {}", height(&s, mouse));
// Saved and reopened as it was; new art takes the look without the wheel.
let doc: Document = (*s.doc().unwrap().doc).clone();
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(back.node(far).unwrap().appearance.stroke(), doc.node(far).unwrap().appearance.stroke());
assert!(vectorcraft_doc::Appearance::clone(&doc.node(far).unwrap().appearance).without_pressure().stroke().is_some_and(|st| st.wheel.is_none()));
}
/// #764: a stroke that connects two paths joins the pen's tilt, bearing and rotation of both, the
/// connected path's after the stroke's.
#[test]
@@ -1611,7 +1684,7 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() {
select(s, &[]);
id
};
let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0) }));
let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0), wheel: None }));
let (tilt, bearing, rotation) = pose_of(&s, pen);
assert_eq!(tilt.as_ref().map(|t| t.at(0.5)), Some(0.0), "upright");
assert!(bearing.is_some() && (rotation.unwrap().at(0.5) + 30.0).abs() < 1e-6);
+822
View File
@@ -3189,6 +3189,283 @@ fn live_paint_stroke_edge() {
assert!(s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [300, 300]})).is_err());
}
/// While the Live Paint Bucket is active, a fill or stroke color chosen without `ids`, `id` or
/// `item` becomes the color the bucket paints with: the selected Live Paint group and other
/// selected art keep their paint, and the next bucket click paints one face in that color. Given
/// `ids`, the paint still goes to those objects.
#[test]
fn live_paint_bucket_color_choice_leaves_the_selection_unpainted() {
use vectorcraft_tools::builder::{edges, faces};
let mut s = session();
let g = live(&mut s);
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
let rect_fill = node(&s, rect).appearance.fill_paint();
s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
let before = node(&s, g);
let steps = s.doc().unwrap().history.undo.len();
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
let r = s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
assert_eq!(r["objects"], 0);
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(s.paint.fill, magenta, "the bucket's fill color");
assert_eq!(s.paint.stroke, Paint::solid(Color::from_hex("#0000ff").unwrap()));
assert_eq!(node(&s, g), before, "the group keeps its paint");
assert_eq!(node(&s, rect).appearance.fill_paint(), rect_fill, "other selected art keeps its paint");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
// The proxies show the bucket's colors, not the selection's.
assert_eq!(s.proxy_paints(), (magenta.clone(), s.paint.stroke.clone()));
assert_eq!(s.proxy_mixed(), (false, false));
// Invert recolors the bucket's color, not the selection.
s.execute("paint.invert", &json!({"stroke": false})).unwrap();
assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()));
assert_eq!(node(&s, g), before, "Invert leaves the group as it was");
// A previewed color (the Color Picker) that is canceled puts the bucket's color back.
s.begin_interaction("Fill Color").unwrap();
s.preview("paint.setFill", &json!({"color": "#123456"})).unwrap();
assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#123456").unwrap()));
s.cancel_interaction().unwrap();
assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()), "the canceled color is not kept");
// With New Art Has Basic Appearance off, the selection's appearance does not replace them.
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
assert_eq!(s.paint.fill, magenta, "the bucket's fill color stays");
// The bucket paints the face it clicks in the color chosen.
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50]})).unwrap();
let face = NodeId(r["face"].as_u64().unwrap());
let gn = node(&s, g);
assert_eq!(faces(&gn).iter().filter(|f| f.appearance.fill_paint() == magenta).map(|f| f.id).collect::<Vec<_>>(), vec![face]);
assert!(edges(&gn).iter().all(|e| e.appearance.fill_paint().is_none()));
// Named objects still take the paint.
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
assert_eq!(node(&s, rect).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()));
}
/// While the Live Paint Bucket is active, each paint and stroke command run without `ids`, `id` or
/// `item` changes only the fill, stroke or weight the bucket paints with: the selection keeps its
/// paint and no undo step is recorded. Each command runs in its own session, and every command that
/// fails is listed.
#[test]
fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() {
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
let cyan = Paint::solid(Color::from_hex("#00ffff").unwrap());
let blue = Color::from_hex("#0000ff").unwrap();
let is_gradient = |p: &Paint| matches!(p, Paint::Gradient(_));
type Check = Box<dyn Fn(&Session) -> bool>;
let cases: Vec<(&str, Value, Check)> = vec![
(
"paint.swap",
json!({}),
Box::new({
let red = red.clone();
move |s: &Session| s.paint.stroke == red
}),
),
("paint.default", json!({}), Box::new(|s: &Session| s.paint.fill == Paint::solid(Color::WHITE))),
("paint.none", json!({}), Box::new(|s: &Session| s.paint.fill == Paint::None)),
("paint.lastColor", json!({"stroke": false}), Box::new(move |s: &Session| s.paint.fill == Paint::solid(blue))),
("paint.lastGradient", json!({"stroke": false}), Box::new(move |s: &Session| is_gradient(&s.paint.fill))),
(
"paint.complement",
json!({"stroke": false}),
Box::new({
let cyan = cyan.clone();
move |s: &Session| s.paint.fill == cyan
}),
),
(
"paint.sampleColor",
json!({"color": "#00ffff", "stroke": false}),
Box::new({
let cyan = cyan.clone();
move |s: &Session| s.paint.fill == cyan
}),
),
// A null `ids` or `id` names no object, as it does for every other command.
("paint.setFill", json!({"color": "#00ffff", "ids": null, "id": null}), Box::new(move |s: &Session| s.paint.fill == cyan)),
("paint.editGradient", json!({"stroke": false, "angle": 45}), Box::new(move |s: &Session| is_gradient(&s.paint.fill))),
(
"paint.editGradient",
json!({"stroke": true, "strokeMode": "along"}),
Box::new(move |s: &Session| {
is_gradient(&s.paint.stroke) && s.new_art_stroke().gradient_mode == vectorcraft_doc::StrokeGradientMode::Along
}),
),
("stroke.set", json!({"weight": 5}), Box::new(|s: &Session| s.paint.stroke_width == 5.0 && s.shown_stroke().map(|st| st.width) == Some(5.0))),
("stroke.weightUp", json!({}), Box::new(|s: &Session| s.paint.stroke_width == 3.0)),
("stroke.weightDown", json!({}), Box::new(|s: &Session| s.paint.stroke_width == 1.0)),
("stroke.set", json!({"weight": 6, "ids": null}), Box::new(|s: &Session| s.paint.stroke_width == 6.0)),
("stroke.weightUp", json!({"id": null}), Box::new(|s: &Session| s.paint.stroke_width == 3.0)),
(
"stroke.setAdvanced",
json!({"arrowScale": [150, 200]}),
Box::new(|s: &Session| s.shown_stroke().map(|st| st.arrow_scale) == Some((150.0, 200.0))),
),
];
let mut failed = vec![];
for (cmd, params, check) in cases {
let mut s = session();
let g = live(&mut s);
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.paint.fill = red.clone();
s.paint.stroke_width = 2.0;
s.last_solid = blue;
let (group, art) = (node(&s, g), node(&s, rect));
let steps = s.doc().unwrap().history.undo.len();
if let Err(e) = s.execute(cmd, &params) {
failed.push(format!("{cmd}: {e}"));
continue;
}
if !check(&s) {
failed.push(format!("{cmd}: the bucket's paint did not change as expected"));
}
if node(&s, g) != group || node(&s, rect) != art {
failed.push(format!("{cmd}: the selection was painted"));
}
if s.doc().unwrap().history.undo.len() != steps {
failed.push(format!("{cmd}: an undo step was recorded"));
}
}
assert!(failed.is_empty(), "{failed:#?}");
}
/// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush
/// still goes to the selection.
#[test]
fn live_paint_bucket_named_objects_and_brushes_still_take_the_stroke() {
let mut s = session();
let g = live(&mut s);
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.execute("stroke.set", &json!({"weight": 4, "ids": [rect.0]})).unwrap();
assert_eq!(node(&s, rect).appearance.stroke_width(), 4.0);
// A brush still goes to the selection.
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("stroke.setAdvanced", &json!({"brush": "3 pt. Round"})).unwrap();
assert_eq!(node(&s, rect).appearance.stroke().and_then(|st| st.brush.clone()).as_deref(), Some("3 pt. Round"));
}
/// While the Live Paint Bucket is active and the Fill proxy is in front, a gradient preset and a
/// color sampled into a gradient stop change the bucket's fill, even when the selection's active
/// Appearance row is a stroke.
#[test]
fn live_paint_bucket_gradient_preset_and_sampled_stop_follow_the_active_proxy() {
let mut s = session();
live(&mut s);
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": 1})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.execute("paint.toggleActive", &json!({"fill": true})).unwrap();
assert_eq!(s.appearance_item(), Some(1), "the stroke row stays active");
let (art, stroke) = (node(&s, rect), s.paint.stroke.clone());
s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap();
let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") };
assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Radial);
assert_eq!(s.paint.stroke, stroke, "the bucket's stroke stays");
s.execute("paint.sampleColor", &json!({"color": "#00ffff", "stop": 0})).unwrap();
let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") };
assert_eq!(g.gradient.stops[0].color, Color::from_hex("#00ffff").unwrap(), "the sampled stop");
assert_eq!(node(&s, rect), art, "the selection keeps its paint");
}
/// A gradient stop selected on the selection's gradient is not selected once the Live Paint
/// Bucket is active (its proxies show the default paint), and one selected on the bucket's
/// gradient is not selected once another tool is chosen.
#[test]
fn live_paint_bucket_and_the_selection_keep_their_own_selected_stop() {
let mut s = session();
live(&mut s);
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap();
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
assert_eq!(s.selected_stop(), Some(1));
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
assert_eq!(s.selected_stop(), None, "the selection's stop is not the bucket's");
s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap();
s.execute("gradient.selectStop", &json!({"index": 0})).unwrap();
assert_eq!(s.selected_stop(), Some(0));
s.select_tool("selection", ViewInfo::default()).unwrap();
assert_eq!(s.selected_stop(), None, "the bucket's stop is not the selection's");
}
/// While the Live Paint Bucket is active, a paint or stroke command with a bad `target` or
/// `aligned` is refused, as it is with the Selection tool, and the bucket's fill, stroke and weight
/// stay.
#[test]
fn live_paint_bucket_refuses_a_bad_target_or_aligned() {
let refused = [
("paint.setFill", json!({"color": "#00ffff", "target": "bogus"})),
("paint.invert", json!({"ids": null, "aligned": "bad"})),
("paint.complement", json!({"aligned": "bad"})),
("stroke.set", json!({"weight": 6, "target": "bogus"})),
("stroke.set", json!({"weight": 6, "aligned": "bad"})),
("stroke.weightUp", json!({"target": "bogus"})),
("stroke.weightUp", json!({"aligned": "bad"})),
("stroke.weightDown", json!({"target": "bogus"})),
("stroke.weightDown", json!({"aligned": "bad"})),
("paint.swap", json!({"aligned": "bad"})),
("paint.default", json!({"target": "bogus"})),
];
for tool in ["selection", "livePaintBucket"] {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.select_tool(tool, ViewInfo::default()).unwrap();
let before = (s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
for (cmd, p) in &refused {
assert!(s.execute(cmd, p).is_err(), "{tool}: {cmd} {p}");
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), before, "{tool}: {cmd} {p}");
}
}
}
/// While the Live Paint Bucket is active, each preview of a paint command in one interaction starts
/// from the colors the interaction began with, so previewing a swap twice and committing swaps once.
#[test]
fn live_paint_bucket_previews_start_from_the_interaction_colors() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone());
s.begin_interaction("Swap").unwrap();
s.preview("paint.swap", &json!({})).unwrap();
s.preview("paint.swap", &json!({})).unwrap();
s.commit_interaction().unwrap();
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), (stroke, fill), "one swap");
}
/// A color chosen with the Live Paint Bucket is the current fill: a tool held for a moment (the
/// Hand) and let go leaves it in place, so the bucket paints with it afterwards, with New Art Has
/// Basic Appearance off and on.
#[test]
fn a_held_tool_keeps_the_live_paint_bucket_color() {
for basic in [false, true] {
let mut s = session();
live(&mut s);
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap();
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
s.select_tool("hand", ViewInfo::default()).unwrap();
assert_eq!(s.paint.fill, magenta, "basic {basic}: the Hand keeps the current fill");
s.switch_tool("livePaintBucket", ViewInfo::default()).unwrap();
assert_eq!(s.paint.fill, magenta, "basic {basic}: the bucket paints with its color");
assert_eq!(s.proxy_paints().0, magenta, "basic {basic}: the Fill proxy shows it");
assert_eq!(node(&s, rect).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "basic {basic}");
}
}
/// The undo and redo depths, the unsaved state and the revision of the active document.
fn history_state(s: &Session) -> (usize, usize, bool, u64) {
let st = s.doc().unwrap();
@@ -3507,6 +3784,419 @@ fn live_paint_fill_skips_hidden_faces() {
assert!(!node(&s, hidden).visible);
}
/// The appearance of each face and each edge of Live Paint group `g`.
fn part_looks(s: &Session, g: NodeId) -> (Vec<vectorcraft_doc::Appearance>, Vec<vectorcraft_doc::Appearance>) {
use vectorcraft_tools::builder::{edges, faces};
let n = node(s, g);
let looks = |parts: Vec<&Arc<Node>>| parts.iter().map(|p| (*p.appearance).clone()).collect();
(looks(faces(&n)), looks(edges(&n)))
}
/// The appearance of each hidden source path of Live Paint group `g`.
fn sources_looks(s: &Session, g: NodeId) -> Vec<vectorcraft_doc::Appearance> {
let n = node(s, g);
let src = vectorcraft_tools::builder::sources(&n).unwrap();
src.children().unwrap().iter().map(|c| (*c.appearance).clone()).collect()
}
/// With a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group
/// paints its faces and leaves its edges as they are, and a stroke paints its edges and leaves its
/// faces as they are. The Fill and Stroke proxies show the faces' fill and the edges' stroke.
#[test]
fn live_paint_group_fill_goes_to_faces_and_stroke_to_edges() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (faces0, edges0) = part_looks(&s, g);
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
let sources0 = sources_looks(&s, g);
assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap()["objects"], faces0.len());
let (faces1, edges1) = part_looks(&s, g);
assert!(faces1.iter().all(|f| f.fill_paint() == magenta));
assert_eq!(edges1, edges0, "edges take no fill");
let p = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!(p["fillMixed"], false);
assert_eq!(p["fill"], serde_json::to_value(&magenta).unwrap());
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
assert_eq!(s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap()["objects"], edges0.len());
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their paint");
let (faces2, edges2) = part_looks(&s, g);
assert!(edges2.iter().all(|e| e.stroke_paint() == blue));
assert_eq!(faces2, faces1, "faces take no stroke");
let p = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!(p["strokeMixed"], false);
assert_eq!(p["stroke"], serde_json::to_value(&blue).unwrap());
// The same with the group given by id, and inside a selected group.
s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#00ff00"})).unwrap();
let (faces3, edges3) = part_looks(&s, g);
assert_eq!(edges3, edges2, "edges take no fill given by id");
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
assert!(faces3.iter().all(|f| f.fill_paint() == green));
s.execute("object.group", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
let (faces4, edges4) = part_looks(&s, g);
assert_eq!(faces4, faces3, "faces of a grouped Live Paint group take no stroke");
assert!(edges4.iter().all(|e| e.stroke_paint() == Paint::solid(Color::from_hex("#ff0000").unwrap())));
// The bucket then paints one face, and nothing in the group draws a fill over it.
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#ffff00"})).unwrap();
let face = NodeId(r["face"].as_u64().unwrap());
assert_eq!(node(&s, face).appearance.fill_paint(), Paint::solid(Color::from_hex("#ffff00").unwrap()));
assert!(part_looks(&s, g).1.iter().all(|e| e.fill_paint().is_none()));
}
/// Swap Fill and Stroke on a whole selected Live Paint group gives its faces the stroke its edges
/// share and its edges the fill its faces share; with faces of different fills, or without faces,
/// it leaves the group as it is.
#[test]
fn live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let sources0 = sources_looks(&s, g);
// The faces are red and blue: nothing on the group changes, in no undo step.
let (faces0, edges0) = part_looks(&s, g);
let depth = history_state(&s).0;
s.execute("paint.swap", &json!({})).unwrap();
assert_eq!(part_looks(&s, g), (faces0, edges0));
assert_eq!(history_state(&s).0, depth);
// One fill on every face: the faces take the edges' black, the edges the faces' red, at their weight.
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
s.execute("paint.swap", &json!({})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
assert!(faces1.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK)));
assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0)) && e.stroke_width() == 2.0));
assert!(edges1.iter().all(|e| e.fill_paint().is_none()), "edges take no fill");
assert_eq!(sources_looks(&s, g), sources0);
s.execute("edit.undo", &json!({})).unwrap();
assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "one undo step");
// A gradient placed on each face's own bounds is one shared fill: the edges take it, fitted to each edge.
s.execute("paint.setFill", &json!({"gradient": {"aspect": 50}})).unwrap();
let placed: Vec<Paint> = part_looks(&s, g).0.iter().map(|f| f.fill_paint()).collect();
assert!(placed.iter().all(|p| matches!(p, Paint::Gradient(gr) if gr.geom.is_some())) && placed[0] != placed[1]);
s.execute("paint.swap", &json!({})).unwrap();
let (faces2, edges2) = part_looks(&s, g);
assert!(faces2.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK)));
assert!(edges2.iter().all(|e| matches!(e.stroke_paint(), Paint::Gradient(gr) if gr.geom.is_none() && gr.freeform.is_none())));
// A freeform gradient's points belong to its face: faces with freeform fills keep their paint, in no undo step.
s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
assert!(
part_looks(&s, g)
.0
.iter()
.all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.gradient.kind == vectorcraft_color::GradientKind::Freeform))
);
let looks = part_looks(&s, g);
let depth = history_state(&s).0;
s.execute("paint.swap", &json!({})).unwrap();
assert_eq!(part_looks(&s, g), looks);
assert_eq!(history_state(&s).0, depth);
// A group with edges and no faces keeps its paint.
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap());
let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
assert!(part_looks(&s, edges_only).0.is_empty());
s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
let looks = part_looks(&s, edges_only);
s.execute("paint.swap", &json!({})).unwrap();
assert_eq!(part_looks(&s, edges_only), looks);
}
/// Default Fill and Stroke on a whole selected Live Paint group leaves its faces with no fill and
/// gives its edges a 0.5 pt black stroke, and new art takes the same; other art selected with it
/// takes the white fill and 1 pt black stroke.
#[test]
fn live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let sources0 = sources_looks(&s, g);
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("paint.default", &json!({})).unwrap();
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().all(|f| f.fill_paint().is_none() && f.stroke_paint().is_none()));
assert!(edges.iter().all(|e| e.stroke_paint() == Paint::solid(Color::BLACK) && e.stroke_width() == 0.5 && e.fill_paint().is_none()));
assert_eq!(sources_looks(&s, g), sources0);
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, Paint::solid(Color::BLACK), 0.5));
let p = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!((p["fillMixed"].clone(), p["strokeMixed"].clone()), (json!(false), json!(false)));
// The next shape drawn has no fill and a 0.5 pt black stroke.
let next = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
let look = node(&s, next).appearance.clone();
assert!(!look.has_visible_fill());
assert_eq!((look.stroke_paint(), look.stroke_width()), (Paint::solid(Color::BLACK), 0.5));
// With a plain rectangle selected too, the rectangle and new art take the white fill and 1 pt black stroke.
let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [r.0], "color": "#00ff00"})).unwrap();
s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::WHITE));
assert_eq!(part_looks(&s, g), (faces.clone(), edges.clone()));
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::solid(Color::WHITE), 1.0));
// A redefined Default Graphic Style goes to other art; the parts still take no fill and a 0.5 pt black stroke.
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(part_looks(&s, g), (faces, edges), "the parts do not take the redefined style");
assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()));
}
/// Invert on a whole selected Live Paint group recolors its faces' fills and leaves its edges and
/// hidden source paths as they are.
#[test]
fn live_paint_group_invert_recolors_the_faces_fill() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let sources0 = sources_looks(&s, g);
let (_, edges0) = part_looks(&s, g);
s.execute("paint.invert", &json!({"stroke": false})).unwrap();
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
assert_eq!(edges, edges0);
assert_eq!(sources_looks(&s, g), sources0);
// The same with `target: "contents"`, for the stroke.
s.execute("paint.invert", &json!({"stroke": true, "target": "contents"})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
assert_eq!(faces1, faces);
assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::WHITE)));
assert_eq!(sources_looks(&s, g), sources0);
// A gradient edit of the fill goes to the faces only.
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap();
let (faces2, edges2) = part_looks(&s, g);
assert!(faces2.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(_))));
assert_eq!(edges2, edges1, "edges take no fill gradient");
assert_eq!(sources_looks(&s, g), sources0);
// Selecting a Live Paint group with edges and no faces gives new art its edges' stroke.
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap());
let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setStroke", &json!({"ids": [edges_only.0], "color": "#00ff00"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.paint.stroke = Paint::None;
s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
assert_eq!(s.paint.stroke, Paint::solid(Color::from_hex("#00ff00").unwrap()));
}
/// A gradient vector or freeform point edit of a whole selected Live Paint group's fill changes its
/// faces' gradients and leaves its edges and hidden source paths as they are.
#[test]
fn live_paint_group_gradient_vector_and_freeform_edits_change_its_faces() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
let sources0 = sources_looks(&s, g);
let (_, edges0) = part_looks(&s, g);
let face_ids: Vec<u64> = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id.0).collect();
let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "start": [0, 0], "end": [100, 0]})).unwrap();
let mut changed: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
changed.sort_unstable();
let mut faces = face_ids.clone();
faces.sort_unstable();
assert_eq!(changed, faces, "only the faces take the vector");
assert_eq!(part_looks(&s, g).1, edges0);
assert_eq!(sources_looks(&s, g), sources0);
s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
s.execute("paint.freeform.addPoint", &json!({"stroke": false, "at": [25, 50], "color": "#00ff00"})).unwrap();
assert!(part_looks(&s, g).0.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.freeform.is_some())));
assert_eq!(part_looks(&s, g).1, edges0);
assert_eq!(sources_looks(&s, g), sources0);
}
/// The Live Paint rules stop where a paint command stops: a Live Paint group in a compound shape or
/// a blend keeps its parts' paint when the compound shape or blend takes the default, Invert
/// remembers the faces' color the proxy shows, and a Live Paint group without faces lets the Fill
/// proxy show the next selected object's fill, while an empty plain group does not.
#[test]
fn live_paint_group_rules_stop_where_paint_commands_stop() {
let mut s = session();
let g = live(&mut s);
let looks = part_looks(&s, g);
let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
let c = NodeId(s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("paint.default", &json!({})).unwrap();
s.execute("paint.swap", &json!({})).unwrap();
assert_eq!(part_looks(&s, g), looks, "a compound shape's member keeps its paint");
s.execute("paint.default", &json!({"ids": [c.0, g.0]})).unwrap();
assert_eq!(part_looks(&s, g), looks, "a compound shape's member given as well keeps its paint");
// Given alone, the member is a Live Paint group: a fill paints its faces and leaves its edges.
s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#ff00ff"})).unwrap();
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::from_hex("#ff00ff").unwrap())));
assert_eq!(edges, looks.1, "the edges of a member given alone take no fill");
// A Live Paint group selected with one of its edges: the edge counts with the group.
let mut s = session();
let g = live(&mut s);
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("select.set", &json!({"ids": [g.0, edge.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fillMixed"], false);
assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge selected with its group takes no fill");
// The same for an edge given in `ids` with its group.
s.execute("paint.setFill", &json!({"ids": [g.0, edge.0], "color": "#0000ff"})).unwrap();
assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge given with its group takes no fill");
// The same for a blend's key.
let mut s = session();
let g = live(&mut s);
let looks = part_looks(&s, g);
let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
let b = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("paint.default", &json!({})).unwrap();
s.execute("paint.swap", &json!({})).unwrap();
assert_eq!(part_looks(&s, g), looks, "a blend's key keeps its paint");
// A Live Paint group inside a selected group: Invert recolors its faces' fills only.
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let sources0 = sources_looks(&s, g);
let (_, edges0) = part_looks(&s, g);
s.execute("object.group", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.invert", &json!({"stroke": false})).unwrap();
assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
assert_eq!(part_looks(&s, g).1, edges0);
assert_eq!(sources_looks(&s, g), sources0);
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
Ok(())
})
.unwrap();
s.execute("paint.invert", &json!({"stroke": false})).unwrap();
// Like any group's, the group's own row is recolored too; the color remembered is the faces' one the proxy shows.
assert_eq!(node(&s, g).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 1.0, 0.0)));
assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
assert_eq!(s.last_solid, Color::rgb(0.0, 1.0, 1.0));
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
assert!(part_looks(&s, edges_only).0.is_empty());
let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
set_fill(&mut s, r, Color::from_hex("#00ff00").unwrap());
s.execute("select.set", &json!({"ids": [edges_only.0, r.0]})).unwrap();
let p = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!(p["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#00ff00").unwrap())).unwrap());
// The edges-only group shows its edges' stroke in the Stroke panel.
let edge_width = part_looks(&s, edges_only).1[0].stroke_width();
assert_eq!(s.shown_stroke().map(|st| st.width), Some(edge_width));
// Any other object with nothing painted in it first in the selection (a group left empty) shows
// the defaults for new art, not the next object's paint.
let inner = rect(&mut s, 0.0, 300.0, 50.0, 50.0);
let empty = NodeId(s.execute("object.group", &json!({"ids": [inner.0]})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.children_mut(Some(empty)).unwrap().clear();
Ok(())
})
.unwrap();
s.execute("stroke.set", &json!({"ids": [r.0], "weight": 7})).unwrap();
s.paint.fill = Paint::None;
s.execute("select.set", &json!({"ids": [empty.0, r.0]})).unwrap();
let p = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!(p["fill"], serde_json::to_value(Paint::None).unwrap());
assert!(s.shown_stroke().is_none());
}
/// Stroke panel edits of a whole selected Live Paint group (a weight, a step up or down, options)
/// change its edges and leave its faces as they are, and the panel shows the edges' stroke.
#[test]
fn live_paint_group_stroke_panel_edits_change_its_edges() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (faces0, edges0) = part_looks(&s, g);
assert_eq!(s.execute("stroke.set", &json!({"weight": 5})).unwrap()["objects"], edges0.len());
let (faces1, edges1) = part_looks(&s, g);
assert_eq!(faces1, faces0, "faces take no stroke weight");
assert!(edges1.iter().all(|e| e.stroke().is_some_and(|st| st.width == 5.0)));
assert_eq!(s.shown_stroke().map(|st| st.width), Some(5.0));
assert!(!s.doc().unwrap().stroke_mixed().weight);
s.execute("stroke.weightUp", &json!({})).unwrap();
s.execute("stroke.set", &json!({"cap": "round"})).unwrap();
let (faces2, edges2) = part_looks(&s, g);
assert_eq!(faces2, faces0, "faces take no stroke step or cap");
assert!(edges2.iter().all(|e| e.stroke().is_some_and(|st| st.width == 6.0 && st.cap == LineCap::Round)));
// A stroke on the faces (from a file, say) leaves the panel showing the edges' stroke.
let face_ids: Vec<NodeId> = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id).collect();
s.edit("t", |d, _| {
for id in &face_ids {
let face = d.node_mut(*id).unwrap();
face.appearance.set_stroke(Paint::solid(Color::BLACK));
face.appearance.stroke_at_mut(None).unwrap().width = 2.0;
}
Ok(())
})
.unwrap();
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0));
assert!(!s.doc().unwrap().stroke_mixed().weight);
// A face selected with its group counts with the group, whose stroke is its edges'.
s.execute("select.set", &json!({"ids": [g.0, face_ids[0].0]})).unwrap();
assert!(!s.doc().unwrap().stroke_mixed().weight);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
// A stroke row on the group itself: a weight still goes to the edges the panel shows.
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.set_stroke(Paint::solid(Color::BLACK));
Ok(())
})
.unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
assert!(part_looks(&s, g).1.iter().all(|e| e.stroke_width() == 3.0));
assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
}
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
/// leaves the settings for new art as they are.
#[test]
fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
let mut s = session();
let g = live(&mut s);
let edge_ids: Vec<NodeId> = vectorcraft_tools::builder::edges(&node(&s, g)).iter().map(|e| e.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !edge_ids.contains(&c.id));
Ok(())
})
.unwrap();
assert!(part_looks(&s, g).1.is_empty());
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let looks = part_looks(&s, g);
let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
s.execute("stroke.set", &json!({"cap": "round"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
s.execute("stroke.weightUp", &json!({})).unwrap();
s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
assert_eq!(part_looks(&s, g), looks);
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
let looks = part_looks(&s, edges_only);
let paint0 = s.paint.clone();
s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap();
assert_eq!(s.paint, paint0, "new art keeps its fill");
assert_eq!(part_looks(&s, edges_only), looks);
}
/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of
/// `xs`.
fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId {
@@ -5474,6 +6164,90 @@ fn layers_drag_into_a_nested_live_paint_group_makes_the_outer_group_again() {
assert_eq!(faces(&node(&s, outer)).len(), cut, "the outer group is made after the inner one");
}
/// A Live Paint group's sources group can't be dragged out of the group, which would leave faces
/// and edges with no paths: the move is refused and changes nothing. A reorder within the group,
/// and a copy dragged out, are allowed.
#[test]
fn layers_drag_keeps_the_sources_group_in_its_live_paint_group() {
use vectorcraft_tools::builder::{faces, is_live_paint, sources};
let mut s = session();
let g = live(&mut s);
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
let src = sources(&node(&s, g)).unwrap().id;
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let err = s.execute("layer.move", &json!({"ids": [src.0], "target": layer.0})).unwrap_err().to_string();
assert!(err.contains("sources group stays in the group"), "{err}");
let err = s.execute("node.move", &json!({"id": src.0, "parent": layer.0, "index": 0})).unwrap_err().to_string();
assert!(err.contains("sources group stays in the group"), "{err}");
assert!(s.doc().unwrap().doc == before.0, "nothing moved");
assert_eq!(s.doc().unwrap().history.undo.len(), before.1);
s.execute("node.move", &json!({"id": src.0, "parent": g.0, "index": 99})).unwrap();
let n = node(&s, g);
assert!(is_live_paint(&n));
assert_eq!(sources(&n).unwrap().id, src);
assert_eq!(faces(&n).len(), 3);
s.execute("layer.move", &json!({"ids": [src.0], "target": layer.0, "copy": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(src), Some(g), "a copy leaves the sources group where it is");
}
/// A shown path dragged into a hidden group among a Live Paint group's paths stops cutting its
/// faces, and dragged back out of it cuts them again.
#[test]
fn layers_drag_into_a_hidden_group_among_the_sources_makes_the_faces_again() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
let first_source = |s: &Session| sources(&node(s, g)).unwrap().children().unwrap()[0].id;
let a = line_to_right_face(&mut s, 30.0);
let target = first_source(&s);
s.execute("layer.move", &json!({"ids": [a.0], "target": target.0, "place": "above"})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 5);
let b = line_to_right_face(&mut s, 70.0);
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let hidden = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
let target = first_source(&s);
s.execute("layer.move", &json!({"ids": [hidden.0], "target": target.0, "place": "above"})).unwrap();
let src = sources(&node(&s, g)).unwrap().id;
assert_eq!(s.doc().unwrap().doc.parent_of(hidden), Some(src));
assert_eq!(faces(&node(&s, g)).len(), 5, "a hidden group cuts nothing");
s.execute("layer.move", &json!({"ids": [a.0], "target": hidden.0, "place": "inside"})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(hidden));
assert_eq!(faces(&node(&s, g)).len(), 3, "the path in the hidden group no longer cuts the faces");
let target = first_source(&s);
s.execute("layer.move", &json!({"ids": [a.0], "target": target.0, "place": "above"})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, g)).unwrap().id));
assert_eq!(faces(&node(&s, g)).len(), 5, "back among the shown paths, it cuts them again");
}
/// A Live Paint group with no paths dragged into another one with none joins it: the drop is one
/// "Merge Live Paint" step, and the group stays a Live Paint group with no faces or edges.
#[test]
fn layers_drag_of_an_empty_live_paint_group_into_another_joins_it() {
use vectorcraft_tools::builder::{edges, faces, is_live_paint, sources};
let mut s = session();
let empty = |s: &mut Session| {
let g = live(s);
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
for p in sources(&node(s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>() {
s.execute("layer.move", &json!({"ids": [p.0], "target": layer.0})).unwrap();
}
assert!(faces(&node(s, g)).is_empty());
g
};
let (g, h) = (empty(&mut s), empty(&mut s));
let r = s.execute("layer.move", &json!({"ids": [h.0], "target": g.0, "place": "inside"})).unwrap();
assert_eq!(r["ids"], json!([g.0]));
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"));
let n = node(&s, g);
assert!(is_live_paint(&n));
assert!(sources(&n).unwrap().children().unwrap().is_empty());
assert!(faces(&n).is_empty() && edges(&n).is_empty());
assert!(s.doc().unwrap().doc.node(h).is_none(), "the dropped group joined");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(h).is_some());
}
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
/// graphic style link, and return it as it then is.
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
@@ -8617,6 +9391,54 @@ fn image_trace_view_is_stored_kept_and_validated() {
assert!(s.execute("imageTrace.setView", &json!({"id": a.0, "view": "outlines"})).is_err());
}
/// The Split view's divider is set with the view, kept when omitted, when tracing again and through
/// save and open, adds no undo step when unchanged and one when changed, and is checked. On screen
/// the source image shows left of it and the result right of it; exports draw the result.
#[test]
fn image_trace_split_view_keeps_and_validates_its_divider() {
let mut s = session();
let g = disc_on_blue(&mut s);
// The image covers 50 to 250 across; the disc 90 to 210, so the divider moves over the disc.
let r = s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap();
assert_eq!((r["view"].as_str(), r["split"].as_f64()), (Some("split"), Some(0.5)));
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute("imageTrace.setView", &json!({"view": "split", "split": 0.25})).unwrap();
assert_eq!(r["split"].as_f64(), Some(0.25));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
assert_eq!(node(&s, g).trace_split(), 0.25);
for same in [json!({"view": "split", "split": 0.25}), json!({"view": "split"})] {
let r = s.execute("imageTrace.setView", &same).unwrap();
assert_eq!(r["split"].as_f64(), Some(0.25), "{same}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{same}: no undo step");
}
// Pixels at y = 60 (above the disc): the image's blue left of x = 100, white right of it.
let blue = |p: [u8; 4]| p[0] < 200 && p[2] > 245;
let white = |p: [u8; 4]| p[0] > 245 && p[1] > 245 && p[2] > 245;
let screen = render_doc(&s, true);
assert!(blue(screen.pixel(60, 60)) && blue(screen.pixel(95, 60)), "{:?}", screen.pixel(95, 60));
assert!(white(screen.pixel(105, 60)) && white(screen.pixel(240, 60)), "{:?}", screen.pixel(105, 60));
let export = render_doc(&s, false);
assert!(white(export.pixel(60, 60)), "exports draw the tracing result");
// Another view keeps the divider for when Split is chosen again.
s.execute("imageTrace.setView", &json!({"view": "outlines"})).unwrap();
assert_eq!(node(&s, g).trace_split(), 0.25);
s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap();
let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": {"ignoreWhite": true, "noise": 30}})).unwrap()["id"].as_u64().unwrap());
assert_eq!((node(&s, g).trace_view(), node(&s, g).trace_split()), (vectorcraft_doc::TraceView::Split, 0.25), "tracing again");
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25));
// Bad dividers are refused and change nothing.
let steps = s.doc().unwrap().history.undo.len();
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] {
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
}
assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25));
for edge in [0.0, 1.0] {
s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap();
assert_eq!(node(&s, g).trace_split(), edge);
}
}
#[test]
fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() {
let mut s = session();
+226
View File
@@ -0,0 +1,226 @@
//! `shape.curvatureCircle`: the circle that touches a path at a point and bends as the path bends
//! there, and the Curvature Circle tool that runs it.
use serde_json::{Value, json};
use vectorcraft_doc::LiveShape;
use vectorcraft_geom::{Point, Rect};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::*;
const C: &str = "shape.curvatureCircle";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn object_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|_| n += 1);
n
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn center_of(v: &Value) -> Point {
Point::new(v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap())
}
/// Whether the geometric bounds of `id` are `want` to within 10⁻⁶ pt.
fn bounds_are(s: &Session, id: NodeId, want: Rect) -> bool {
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-6)
}
/// A circle of radius 100 centered at (200, 200).
fn circle(s: &mut Session) -> NodeId {
id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap())
}
/// The parabola y = 200 + (x − 200)² / 200 from x = 100 to 300, one cubic: its vertex is at
/// (200, 200), where it bends with radius 100 about (200, 300).
fn parabola(s: &mut Session) -> NodeId {
let (a, b) = (166.666_666_666_666_66, 233.333_333_333_333_34);
let d = format!("M100 250 C{a} 183.333333333333334 {b} 183.333333333333334 300 250");
id_of(&s.execute("path.create", &json!({ "d": d })).unwrap())
}
/// On a circle, the curvature circle is the circle itself: a live ellipse with the current paint,
/// selected, in one undo step. On the other side, it is the same size and touches the circle from
/// outside.
#[test]
fn the_curvature_circle_of_a_circle_is_the_circle() {
let mut s = session();
let path = circle(&mut s);
let (undo, count) = (undo_len(&s), object_count(&s));
for seg in 0..4 {
let v = s.execute(C, &json!({"id": path.0, "segment": seg, "t": 0.5})).unwrap();
assert!(v["nominal"].as_bool().unwrap() && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{v}");
assert!(center_of(&v).distance(Point::new(200.0, 200.0)) < 1e-9, "{v}");
let id = id_of(&v);
assert!(bounds_are(&s, id, Rect::new(100.0, 100.0, 300.0, 300.0)));
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
let vectorcraft_doc::NodeKind::Path { live: Some(live), .. } = &node.kind else { panic!("a live shape: {node:?}") };
assert!(matches!(**live, LiveShape::Ellipse { .. }));
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
}
assert_eq!((undo_len(&s), object_count(&s)), (undo + 4, count + 4));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(object_count(&s), count + 3);
let v = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.5, "convex": true})).unwrap();
assert!((center_of(&v).distance(Point::new(200.0, 200.0)) - 200.0).abs() < 1e-9 && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{v}");
}
/// At the vertex of a parabola, the circle has the parabola's curvature, radius 100, on the side
/// it bends toward, or on the other side with `convex`.
#[test]
fn the_curvature_circle_at_a_parabola_vertex() {
let mut s = session();
let path = parabola(&mut s);
let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap();
assert!(!v["nominal"].as_bool().unwrap() && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-6, "{v}");
assert!(center_of(&v).distance(Point::new(200.0, 300.0)) < 1e-6, "{v}");
let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "convex": true})).unwrap();
assert!(center_of(&v).distance(Point::new(200.0, 100.0)) < 1e-6, "{v}");
}
/// A straight segment, a cusp, a corner anchor and a bend so slight that its circle would reach
/// past the canvas are errors, and nothing is drawn.
#[test]
fn straight_segments_cusps_and_huge_circles_are_refused() {
let mut s = session();
let line = id_of(&s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 130, "y2": 70})).unwrap());
let cusp = id_of(&s.execute("path.create", &json!({"d": "M0 0 C100 100 0 100 100 0"})).unwrap());
let gentle = id_of(&s.execute("path.create", &json!({"d": "M0 0 C100 0.0000001 200 0.0000001 300 0"})).unwrap());
// A curve that meets a line at a corner anchor (150, 0).
let corner = id_of(&s.execute("path.create", &json!({"d": "M0 0 C50 -50 100 -50 150 0 L300 0"})).unwrap());
let (undo, count) = (undo_len(&s), object_count(&s));
for (id, t, want) in [
(line, 0.5, "the path is straight there, so no circle matches its curvature"),
(cusp, 0.5, "the path has a cusp there, so it has no single curvature"),
(corner, 1.0, "the path has a corner there, so it has no single curvature"),
(gentle, 0.5, "the circle that matches the path there would reach past the canvas"),
] {
let e = s.execute(C, &json!({"id": id.0, "segment": 0, "t": t})).unwrap_err().to_string();
assert!(e.contains(want), "{e}");
}
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Params that are missing or out of range are errors, and nothing is drawn.
#[test]
fn bad_params_are_refused() {
let mut s = session();
let path = circle(&mut s);
let (undo, count) = (undo_len(&s), object_count(&s));
for (p, want) in [
(json!({"segment": 0, "t": 0.5}), "missing id"),
(json!({"id": path.0, "t": 0.5}), "missing segment"),
(json!({"id": path.0, "segment": 0}), "missing number `t`"),
(json!({"id": path.0, "segment": 0, "t": 1.5}), "`t` must be from 0 to 1"),
(json!({"id": path.0, "segment": 0, "t": -0.1}), "`t` must be from 0 to 1"),
(json!({"id": path.0, "segment": 0, "t": "0.5"}), "`t` must be a number"),
(json!({"id": path.0, "segment": 4, "t": 0.5}), "no such segment"),
(json!({"id": path.0, "subpath": 1, "segment": 0, "t": 0.5}), "no such subpath"),
(json!({"id": path.0, "segment": 0, "t": 0.5, "convex": "yes"}), "`convex` must be true or false"),
] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
assert!(s.execute(C, &json!({"id": 9999, "segment": 0, "t": 0.5})).is_err());
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// A guide has no curvature circle, as the tool leaves guides out; an error names the command.
#[test]
fn a_guide_is_refused() {
let mut s = session();
let path = circle(&mut s);
s.execute("view.guides.make", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(path).unwrap().is_guide());
let (undo, count) = (undo_len(&s), object_count(&s));
let e = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap_err().to_string();
assert!(e.contains("a guide has no curvature circle") && e.contains(C), "{e}");
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// With Align New Objects to Pixel Grid on, the circle still touches the path where it was asked:
/// it is not pixel-aligned, so the grid does not move it.
#[test]
fn the_circle_is_not_moved_onto_the_pixel_grid() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let path = id_of(&s.execute("shape.ellipse", &json!({"x": 100.3, "y": 100.2, "width": 200.4, "height": 200.4})).unwrap());
let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap();
let (c, r) = (center_of(&v), v["radius"].as_f64().unwrap());
let id = id_of(&v);
assert!(bounds_are(&s, id, Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)), "{v}");
assert!(!s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned);
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
for k in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap();
}
}
/// With the Curvature Circle tool, a click on a path draws the circle that matches it there, in
/// one undo step; with Shift, on the other side. A click on a straight line or away from every
/// path draws nothing.
#[test]
fn the_curvature_circle_tool_draws_the_circle_where_it_clicks() {
let mut s = session();
let path = circle(&mut s);
s.execute("shape.line", &json!({"x1": 10, "y1": 380, "x2": 390, "y2": 380})).unwrap();
s.select_tool("curvatureCircle", view()).unwrap();
let (undo, count) = (undo_len(&s), object_count(&s));
click(&mut s, Mods::default(), 301.0, 200.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert_ne!(id, path);
assert!(bounds_are(&s, id, Rect::new(100.0, 100.0, 300.0, 300.0)));
let shift = Mods { shift: true, ..Mods::default() };
click(&mut s, shift, 300.0, 200.0);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(bounds_are(&s, id, Rect::new(300.0, 100.0, 500.0, 300.0)));
assert_eq!(object_count(&s), count + 2);
click(&mut s, Mods::default(), 200.0, 381.0);
click(&mut s, Mods::default(), 20.0, 20.0);
assert_eq!((undo_len(&s), object_count(&s)), (undo + 2, count + 2));
}
/// After a click at a parabola's vertex, a click at (280, 236), 2.4 pt from the circle just drawn
/// and about 3.1 pt from the parabola, passes over that circle and draws the parabola's circle
/// there; after an Undo, the pointer reaches the circle again.
#[test]
fn the_next_click_passes_over_the_circle_the_tool_drew() {
let mut s = session();
parabola(&mut s);
s.select_tool("curvatureCircle", view()).unwrap();
click(&mut s, Mods::default(), 200.0, 200.0);
let first = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(bounds_are(&s, first, Rect::new(100.0, 200.0, 300.0, 400.0)));
click(&mut s, Mods::default(), 280.0, 236.0);
let second = *s.doc().unwrap().selection.objects.first().unwrap();
assert_ne!(second, first);
let r = s.doc().unwrap().doc.bounds_of(&[second], false).unwrap().width() / 2.0;
assert!(r > 150.0, "the parabola's circle at x = 280 is larger than at its vertex: {r}");
s.execute("edit.undo", &json!({})).unwrap();
let count = object_count(&s);
click(&mut s, Mods::default(), 280.0, 241.0);
assert_eq!(object_count(&s), count + 1, "the circle drawn first is within reach again");
let third = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle");
}
+21 -12
View File
@@ -751,14 +751,14 @@ fn eraser_size_follows_the_pen_pressure() {
assert!(err.to_string().contains("sizeMode"), "{err}");
}
/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Rotation, Bearing,
/// Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a
/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Stylus Wheel, Rotation,
/// Bearing, Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a
/// drag without the reading erases at the value itself, an open path is cut where the varied tip
/// covers it, and an unknown mode or a variation out of its range is refused with nothing erased.
#[test]
fn the_eraser_tip_varies_with_its_modes() {
// Which of `probes` a level drag through the middle of a 400 by 200 rectangle erases, each of
// its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation]).
// its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation, wheel]).
let erased = |tip: serde_json::Value, pen: serde_json::Value, probes: &[(f64, f64)]| -> Vec<bool> {
let mut s = session();
rect(&mut s, 0.0, 0.0, 400.0, 200.0);
@@ -785,6 +785,10 @@ fn the_eraser_tip_varies_with_its_modes() {
// The barrel turned half way round reads the most, which turns the tip upright.
assert_eq!(erased(on_rotation.clone(), json!([none, none, none, 180]), &probes), [true, true], "Rotation");
assert_eq!(erased(on_rotation.clone(), json!([]), &probes), [true, false], "Rotation without a reading");
// The finger wheel at the far end of its travel reads the most; without a wheel the tip lies level.
let on_wheel = with(&level, json!({"angleMode": "stylusWheel", "angleVariation": 90}));
assert_eq!(erased(on_wheel.clone(), json!([none, none, none, none, 1.0]), &probes), [true, true], "Stylus Wheel");
assert_eq!(erased(on_wheel, json!([none, none, none, none, none]), &probes), [true, false], "Stylus Wheel without a reading");
// Leaning to the left (a bearing of 180°) reads the most too.
let on_bearing = with(&level, json!({"angleMode": "bearing", "angleVariation": 90}));
assert_eq!(erased(on_bearing.clone(), json!([none, -45, 0, none]), &probes), [true, true], "Bearing");
@@ -831,11 +835,11 @@ fn the_eraser_tip_varies_with_its_modes() {
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let stroke = json!({"points": [[-10, 50], [110, 50]]});
let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\"";
for (extra, want) in [
(json!({"angleMode": "wheel"}), format!("angleMode is one of {modes}, not `wheel`")),
(json!({"roundnessMode": 3}), format!("roundnessMode is one of {modes}, not 3")),
(json!({"sizeMode": "stylusWheel"}), format!("sizeMode is one of {modes}, not `stylusWheel`")),
(json!({"sizeMode": "Pressure"}), format!("sizeMode is one of {modes}, not `Pressure`")),
(json!({"angleVariation": 181}), "angleVariation must be at most 180".to_string()),
(json!({"roundnessVariation": 101}), "roundnessVariation must be at most 100".to_string()),
(json!({"roundnessVariation": -1}), "roundnessVariation must be 0 or more".to_string()),
@@ -3171,8 +3175,9 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() {
}
/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90
/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six
/// numbers, naming the point; the document, the selection and the undo history stay as they were.
/// to 90, a rotation outside 0 to 360 and a stylus wheel outside 0 to 1, naming the key, and a
/// point array of more than seven numbers, naming the point; the document, the selection and the
/// undo history stay as they were.
/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw.
#[test]
fn pen_values_outside_their_ranges_are_refused() {
@@ -3194,7 +3199,8 @@ fn pen_values_outside_their_ranges_are_refused() {
let tilt_x = "`tiltX` must be from -90 to 90";
let tilt_y = "`tiltY` must be from -90 to 90";
let rotation = "`rotation` must be from 0 to 360";
let entries = "`points[3]` must be an array of at most 6 entries";
let wheel = "`wheel` must be from 0 to 1";
let entries = "`points[3]` must be an array of at most 7 entries";
for cmd in cmds {
for (bad, want) in [
(json!([150, 150, -0.01]), pressure),
@@ -3208,8 +3214,11 @@ fn pen_values_outside_their_ranges_are_refused() {
(json!([150, 150, null, null, null, -1]), rotation),
(json!({"x": 150, "y": 150, "rotation": 360.5}), rotation),
(json!([150, 150, null, null, null, 720]), rotation),
(json!([150, 150, 0.5, 0, 0, 0, 1]), entries),
(json!([150, 150, null, null, null, null, null]), entries),
(json!([150, 150, null, null, null, null, -0.01]), wheel),
(json!([150, 150, 0.5, 0, 0, 0, 1.5]), wheel),
(json!({"x": 150, "y": 150, "wheel": 1e300}), wheel),
(json!([150, 150, 0.5, 0, 0, 0, 1, 0]), entries),
(json!([150, 150, null, null, null, null, null, null]), entries),
] {
let points: Vec<_> = good.iter().cloned().chain([bad]).collect();
let sel = s.doc().unwrap().selection.clone();
@@ -3220,8 +3229,8 @@ fn pen_values_outside_their_ranges_are_refused() {
for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() {
let y = 300.0 + 50.0 * row as f64;
let points = json!([
[100, y, 0, -90, 90, 0],
[150, y, 1, 90, -90, 360],
[100, y, 0, -90, 90, 0, 0],
[150, y, 1, 90, -90, 360, 1],
[200, y, 0.5, null, 30],
{"x": 250, "y": y, "tiltX": -45, "pressure": null},
[300, y],
@@ -1154,6 +1154,39 @@ fn the_fill_and_stroke_proxies_show_the_picked_object() {
assert_eq!(proxy_colors(&mut s), (Some("#0000ff".into()), None));
}
/// With an object of a dynamic symbol instance picked and the Live Paint Bucket active, the stroke
/// weight commands step the weight the bucket paints with and leave the instance as it is.
#[test]
fn live_paint_bucket_weight_steps_with_a_picked_symbol_object() {
let mut s = session();
let inst = pair(&mut s, "dynamic");
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.paint.stroke_width = 2.0;
for (cmd, weight) in [("stroke.weightUp", 3.0), ("stroke.weightDown", 2.0)] {
assert_eq!(s.execute(cmd, &json!({})).unwrap()["objects"], 0, "{cmd}");
assert_eq!(s.paint.stroke_width, weight, "{cmd}");
}
assert_eq!(overrides(&s, inst), 0);
}
/// With an object of a dynamic symbol instance picked and the Live Paint Bucket active, a gradient
/// stop of the bucket's fill can be selected and cleared, and the instance keeps its art.
#[test]
fn live_paint_bucket_selects_its_gradient_stop_with_a_picked_symbol_object() {
let mut s = session();
let inst = pair(&mut s, "dynamic");
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.fill_active = true;
s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap();
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
assert_eq!(s.selected_stop(), Some(1));
s.execute("gradient.selectStop", &json!({"index": null})).unwrap();
assert_eq!(s.selected_stop(), None);
assert_eq!(overrides(&s, inst), 0);
}
#[test]
fn selecting_a_guide_too_lets_go_of_the_picked_object() {
let mut s = session();
+129
View File
@@ -1290,3 +1290,132 @@ fn a_failed_preview_is_not_journaled_at_commit() {
s.commit_interaction().unwrap();
assert_eq!(s.journal.len(), journal);
}
/// `take_shape_drawn` is true once after a shape tool's drag is released, a shape command runs (alone
/// or as a batch step), and false after a drag in progress, a canceled or failed one, a click (which
/// opens the tool's dialog), other commands and saved steps that play.
#[test]
fn take_shape_drawn_follows_the_shapes_that_were_drawn() {
use vectorcraft_tools::{Action, PointerEvent, PointerKind};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
assert!(!s.take_shape_drawn(), "a new document draws no shape");
let v = crate::tooling::ViewInfo { smart_guides: false, ..Default::default() };
for (tool, kind) in [
("rectangle", "Rectangle"),
("roundedRectangle", "Rectangle"),
("ellipse", "Ellipse"),
("polygon", "Polygon"),
("star", "Star"),
("lineSegment", "Line"),
] {
s.select_tool(tool, v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 110.0), v).unwrap();
assert!(!s.take_shape_drawn(), "{tool}: a drag in progress");
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 130.0), v).unwrap();
assert!(s.take_shape_drawn(), "{tool} ({kind}): the released drag");
assert!(!s.take_shape_drawn(), "{tool}: once");
// Nothing selected, so the next press is not on the new shape's bounding box.
s.execute("select.none", &json!({})).unwrap();
// A click asks for the tool's dialog and draws nothing yet.
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap();
assert!(!s.take_shape_drawn(), "{tool}: a click");
}
// A canceled drag, and a drag whose preview failed.
let rect = json!({"x": 10, "y": 10, "width": 40, "height": 30});
s.apply_actions(vec![Action::Begin("Rectangle".into()), Action::Preview("shape.rectangle".into(), rect.clone()), Action::Cancel]).unwrap();
assert!(!s.take_shape_drawn(), "a canceled drag");
let bad = json!({"x": 10, "y": 10, "width": "wide", "height": 30});
s.apply_actions(vec![Action::Begin("Rectangle".into()), Action::Preview("shape.rectangle".into(), bad.clone()), Action::Commit]).unwrap();
assert!(!s.take_shape_drawn(), "a failed drag");
// Commands: each shape command, a failed one, a batch with and without a shape, other edits.
for (id, p) in [
("shape.rectangle", rect.clone()),
("shape.ellipse", rect.clone()),
("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 30})),
("shape.star", json!({"cx": 100, "cy": 100, "radius1": 30, "radius2": 15, "points": 5})),
("shape.line", json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50})),
] {
s.execute(id, &p).unwrap();
assert!(s.take_shape_drawn(), "{id}");
}
assert!(s.execute("shape.rectangle", &bad).is_err());
assert!(!s.take_shape_drawn(), "a failed command");
s.execute(
"command.batch",
&json!({"commands": [{"command": "shape.ellipse", "params": rect}, {"command": "object.move", "params": {"dx": 5, "dy": 0}}]}),
)
.unwrap();
assert!(s.take_shape_drawn(), "a batch that draws");
s.execute("command.batch", &json!({"commands": [{"command": "object.move", "params": {"dx": 5, "dy": 0}}]})).unwrap();
assert!(!s.take_shape_drawn(), "a batch that draws nothing");
s.execute("shape.rectangularGrid", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert!(!s.take_shape_drawn(), "other commands, undo and redo");
// Saved steps that play.
s.replay("shape.rectangle", &rect).unwrap();
s.replay(
"command.batch",
&json!({"commands": [{"command": "shape.star", "params": {"cx": 50, "cy": 50, "radius1": 20, "radius2": 10, "points": 5}}]}),
)
.unwrap();
assert!(!s.take_shape_drawn(), "saved steps");
// A script's commands.
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
let shapes = count(&s);
s.execute("script.run", &json!({"source": "vc.run('shape.rectangle', {x:100,y:0,width:5,height:5});", "name": "t.js"})).unwrap();
assert_eq!(count(&s), shapes + 1, "the script drew");
assert!(!s.take_shape_drawn(), "a script");
}
/// With the perspective grid shown and a plane active, a shape tool's drag journals
/// `perspective.draw` naming the shape command: `take_shape_drawn` is true for a Rectangle drawn on
/// the plane and for `perspective.draw` naming a shape command (alone or as a batch step), and false
/// for one naming a shape outside [`crate::DRAWS_SHAPE`].
#[test]
fn take_shape_drawn_counts_shapes_drawn_in_perspective() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let (mut s, _) = super::persp_select::persp_session();
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.take_shape_drawn();
let v = crate::tooling::ViewInfo { smart_guides: false, ..Default::default() };
s.select_tool("rectangle", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 350.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 380.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 410.0), v).unwrap();
assert_eq!(s.journal.last().unwrap().0, "perspective.draw");
assert!(s.take_shape_drawn(), "a Rectangle drawn on the plane");
let rect = json!({"x": 260, "y": 360, "width": 30, "height": 30});
s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": rect})).unwrap();
assert!(s.take_shape_drawn(), "perspective.draw naming shape.rectangle");
s.execute("command.batch", &json!({"commands": [{"command": "perspective.draw", "params": {"command": "shape.ellipse", "params": rect}}]}))
.unwrap();
assert!(s.take_shape_drawn(), "a batch step drawing in perspective");
s.execute("perspective.draw", &json!({"command": "shape.flare", "params": {"cx": 300, "cy": 380, "diameter": 40}})).unwrap();
assert!(!s.take_shape_drawn(), "perspective.draw naming a flare");
}
/// Show on Shape Creation (`showOnShapeCreation`) is off until set, is set and read through
/// `prefs.set` and `prefs.get`, refuses a value that is not a boolean, and is kept with the saved
/// preferences.
#[test]
fn show_on_shape_creation_is_a_saved_preference() {
let mut s = Session::new();
assert!(!s.prefs.show_on_shape_creation);
assert_eq!(s.execute("prefs.get", &json!({"key": "showOnShapeCreation"})).unwrap(), json!(false));
s.execute("prefs.set", &json!({"key": "showOnShapeCreation", "value": true})).unwrap();
assert!(s.prefs.show_on_shape_creation);
assert_eq!(s.execute("prefs.get", &json!({"key": "showOnShapeCreation"})).unwrap(), json!(true));
assert!(s.execute("prefs.set", &json!({"key": "showOnShapeCreation", "value": "yes"})).is_err());
assert!(s.prefs.show_on_shape_creation, "a refused value changes nothing");
let saved = serde_json::to_value(&s.prefs).unwrap();
assert_eq!(saved["showOnShapeCreation"], json!(true));
let read: Prefs = serde_json::from_value(saved).unwrap();
assert!(read.show_on_shape_creation);
}
+11
View File
@@ -4652,6 +4652,17 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() {
assert_eq!(selected(&s), vec![g]);
}
/// A ruler guide is not isolated, and isolation mode stays as it was.
#[test]
fn ruler_guides_are_not_isolated() {
let mut s = session();
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap();
let err = s.execute("object.isolate", &json!({"id": guide.0})).unwrap_err();
assert!(err.to_string().contains("ruler guides can't be isolated"), "{err}");
assert_eq!(s.doc().unwrap().isolation, None);
}
/// 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
+14
View File
@@ -281,6 +281,10 @@ fn overprint_black_covers_type_gradients_spots_and_groups() {
/// pixel (0 full ink, 255 none).
fn plate(doc: &Document, plate: &str) -> Vec<u8> {
let mut r = Renderer::new();
plate_with_renderer(&mut r, doc, plate)
}
fn plate_with_renderer(r: &mut Renderer, doc: &Document, plate: &str) -> Vec<u8> {
r.threads = 0;
let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() };
let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() };
@@ -304,8 +308,18 @@ fn classic_3d_black_overprint_shades_on_the_black_plate() {
let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc);
let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count();
assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn");
for name in ["Cyan", "Magenta", "Yellow"] {
let shaded = plate(over_doc, name);
let unshaded = plate(flat_doc, name);
let changed = shaded.iter().zip(&unshaded).filter(|(s, u)| s.abs_diff(**u) > 1).count();
assert_eq!(changed, 0, "Black Overprint changes the {name} plate");
}
assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate");
assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black");
let mut renderer = Renderer::new();
let first_cyan = plate_with_renderer(&mut renderer, over_doc, "Cyan");
assert!(inked(&plate_with_renderer(&mut renderer, over_doc, "Black")) > 100);
assert_eq!(plate_with_renderer(&mut renderer, over_doc, "Cyan"), first_cyan, "switching plates preserves the Cyan preview");
// On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan.
let image = |d: &Document| {
let mut r = Renderer::new();
+3 -1
View File
@@ -747,7 +747,9 @@ fn a_font_named_by_another_of_its_names_is_copied() {
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let report = String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap();
assert!(report.contains("SourceSans3-Semibold Regular → Fonts/"), "{report}");
let details = report.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default();
// The Font Details row: the Fonts rows above it start with the same label.
let font_details = report.split("\nFONT DETAILS\n").nth(1).unwrap_or_default();
let details = font_details.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default();
assert!(details.contains("embedding allowed") && !details.contains("missing"), "{report}");
}
+300
View File
@@ -0,0 +1,300 @@
//! The Quick Pen tool driven through the session, and `path.quickPen`.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, SubPath};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::tooling::ViewInfo;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..Default::default() }
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn paths(s: &Session) -> Vec<(NodeId, PathData)> {
let mut v = vec![];
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Path { path, .. } = &n.kind {
v.push((n.id, path.clone()));
}
});
v
}
fn only_path(s: &Session) -> SubPath {
let all = paths(s);
assert_eq!(all.len(), 1, "one path");
all[0].1.subpaths[0].clone()
}
fn pt(x: f64, y: f64) -> Point {
Point::new(x, y)
}
fn press(s: &mut Session, pts: &[(f64, f64)]) {
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
for &(x, y) in &pts[1..] {
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
}
let l = pts[pts.len() - 1];
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap();
}
fn click(s: &mut Session, x: f64, y: f64) {
press(s, &[(x, y)]);
}
fn key(s: &mut Session, k: ToolKey) {
s.tool_key(k, Mods::default(), view()).unwrap();
}
fn quick_pen(s: &mut Session) {
s.select_tool("quickPen", view()).unwrap();
}
/// Clicks draw lines; Alt tapped alone switches to the next action, so the next clicks draw a
/// continuous arc and a sharp-corner half circle. Each piece is one undo step.
#[test]
fn clicks_draw_lines_and_arcs_one_undo_step_each() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
let undo = undo_steps(&s);
click(&mut s, 200.0, 100.0);
assert_eq!(undo_steps(&s), undo + 1);
key(&mut s, ToolKey::AltTap);
assert_eq!(s.tool_options()["action"], "continuousArc");
click(&mut s, 300.0, 200.0);
key(&mut s, ToolKey::AltTap);
assert_eq!(s.tool_options()["action"], "sharpArc");
click(&mut s, 300.0, 300.0);
assert_eq!(undo_steps(&s), undo + 3);
let sp = only_path(&s);
assert!(!sp.closed);
let ends: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
assert_eq!(ends.first(), Some(&pt(100.0, 100.0)));
assert_eq!(ends.last(), Some(&pt(300.0, 300.0)));
// Line (2 points), quarter circle (1 more), half circle in two quarters (2 more).
assert_eq!(ends.len(), 5);
// The continuous arc left (200, 100) heading right, as the line arrived.
let joint = sp.anchors.get(1).unwrap();
assert!((joint.h_out - joint.p).y.abs() < 1e-9 && joint.h_out.x > joint.p.x);
// The half circle on (300, 200)–(300, 300) bulges to the left of the way it was drawn
// (downward, so to the right on the page): its middle point is at x = 350.
assert!(sp.anchors.get(3).unwrap().p.distance(pt(350.0, 250.0)) < 1e-9);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(only_path(&s).anchors.len(), 3);
}
/// C flips the last sharp-corner arc, and [ and ] make it 15° smaller or larger, each as one
/// undo step; the next arc keeps the new size. C is not taken while the last piece is a line.
#[test]
fn c_flips_and_brackets_size_the_last_sharp_arc() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 300.0, 300.0);
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 200.0)) < 1e-9, "above the chord");
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
let undo = undo_steps(&s);
key(&mut s, ToolKey::Letter('c'));
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "below once flipped");
assert_eq!(undo_steps(&s), undo + 1);
key(&mut s, ToolKey::BracketLeft);
assert_eq!(s.tool_options()["turn"], 165.0);
let sp = only_path(&s);
// A 165° arc is two segments; its middle point lies on the chord's perpendicular bisector,
// still below.
assert_eq!(sp.anchors.len(), 3);
let mid = sp.anchors.get(1).unwrap().p;
assert!((mid.x - 200.0).abs() < 1e-9 && mid.y > 300.0);
assert_eq!(undo_steps(&s), undo + 2);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap();
click(&mut s, 400.0, 300.0);
assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
}
/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
#[test]
fn an_alt_tap_during_a_drag_switches_the_piece_and_drawing_goes_on() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "continuousArc"})).unwrap();
// A quarter circle that arrives at (300, 200) heading down.
click(&mut s, 300.0, 200.0);
let joint = only_path(&s).anchors.len() - 1;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 210.0, 310.0), v).unwrap();
assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Smooth);
key(&mut s, ToolKey::AltTap);
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 300.0), v).unwrap();
assert_eq!(s.tool_options()["action"], "sharpArc");
assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Corner);
click(&mut s, 100.0, 300.0);
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(100.0, 300.0), "the same path");
}
/// A click on the first point closes the path; the next click starts a new one.
#[test]
fn a_click_on_the_first_point_closes_the_path() {
let mut s = session();
quick_pen(&mut s);
for (x, y) in [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (101.0, 101.0)] {
click(&mut s, x, y);
}
let sp = only_path(&s);
assert!(sp.closed);
assert_eq!(sp.anchors.len(), 3);
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2);
}
/// Escape ends the path: the next click starts a new path. A press dragged places the piece
/// where it is let go.
#[test]
fn escape_ends_the_path_and_a_drag_places_the_piece() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
press(&mut s, &[(150.0, 100.0), (180.0, 120.0), (250.0, 150.0)]);
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
assert!(s.tool_ends_on_escape(view()));
key(&mut s, ToolKey::Escape);
assert!(!s.tool_ends_on_escape(view()));
click(&mut s, 500.0, 500.0);
assert_eq!(paths(&s).len(), 2);
}
/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
/// over the edit, and the next click starts a new path instead of rebuilding the old one.
#[test]
fn an_edit_from_outside_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 300.0, 300.0);
let (id, _) = paths(&s)[0].clone();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 320, "y": 280})).unwrap();
assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
click(&mut s, 500.0, 500.0);
let all = paths(&s);
assert_eq!(all.len(), 2, "a new path");
assert_eq!(all[0].1.subpaths[0].anchors.last().unwrap().p, pt(320.0, 280.0), "the edit stays");
// The same for a point of a path the tool went on from, and for the first point of a new path.
for new in [true, false] {
let mut s = session();
let id = if new {
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
paths(&s)[0].0
} else {
let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
quick_pen(&mut s);
click(&mut s, 200.0, 100.0);
click(&mut s, 200.0, 200.0);
id
};
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path (new: {new})");
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.first().unwrap().p, pt(90.0, 90.0));
}
}
/// A click on an end of an open path goes on drawing from it, in the same path; from its start,
/// the path is reversed first.
#[test]
fn a_click_on_an_open_end_continues_the_path() {
let mut s = session();
let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 100.0, 200.0);
let all = paths(&s);
assert_eq!(all.len(), 1);
assert_eq!(all[0].0, id);
let ends: Vec<Point> = all[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]);
}
/// `path.quickPen` makes a new path with the current paint, or a black stroke without any.
#[test]
fn path_quick_pen_makes_a_stroked_path() {
let mut s = session();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
let r = s
.execute(
"path.quickPen",
&json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100, "action": "sharpArc", "turn": 90, "flip": true}]}),
)
.unwrap();
let id = r["id"].as_u64().unwrap();
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
assert!(!n.appearance.stroke_paint().is_none(), "a black stroke");
assert_eq!(n.path_data().unwrap().subpaths[0].anchors.len(), 3);
}
/// Bad params are refused and change nothing.
#[test]
fn path_quick_pen_refuses_bad_params() {
let mut s = session();
let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}]})).unwrap();
let id = r["id"].as_u64().unwrap();
let before = paths(&s);
let bad: [Value; 11] = [
json!({}),
json!({"pieces": []}),
json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "arc"}]}),
json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "sharpArc", "turn": 0}]}),
json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "turn": 360}]}),
json!({"start": [0, 0], "pieces": [{"x": "1", "y": 1}]}),
json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "flip": "yes"}]}),
json!({"start": [0, 0], "keep": 1}),
json!({"id": id, "keep": 0}),
json!({"id": id, "keep": 3}),
json!({"id": id, "start": [0, 0]}),
];
for p in bad {
assert!(s.execute("path.quickPen", &p).is_err(), "{p}");
}
assert!(s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": vec![json!({"x": 1, "y": 1}); 10_001]})).is_err());
s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap();
assert!(s.execute("path.quickPen", &json!({"id": id, "pieces": [{"x": 5, "y": 5}]})).is_err(), "closed");
assert_eq!(paths(&s).len(), before.len());
}
/// With `id` and `keep`, the points after the first `keep` are replaced by the pieces.
#[test]
fn path_quick_pen_replaces_the_points_after_keep() {
let mut s = session();
let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
let id = r["id"].as_u64().unwrap();
s.execute("path.quickPen", &json!({"id": id, "keep": 2, "pieces": [{"x": 200, "y": 0}]})).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]);
}
+4 -2
View File
@@ -12,12 +12,14 @@ use crate::*;
const DENIED: &str = "Script file access denied";
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real
/// path: kept grants hold real paths, and a path named through a link (macOS's `/var` is
/// `/private/var`) is refused by its names alone.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
base
std::fs::canonicalize(&base).unwrap()
}
fn write(path: &Path, bytes: &[u8]) {
+19
View File
@@ -46,6 +46,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "neon-glow" && l["name"] == "Neon & Glow" && l["count"] == 6), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "paper-cutouts" && l["name"] == "Paper Cutouts" && l["count"] == 6), "{libs:?}");
for l in libs {
let id = l["id"].as_str().unwrap();
let g = run(&mut s, "graphicStyle.library", json!({"library": id}));
@@ -91,6 +92,24 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn paper_cutout_style_applies_to_an_object_and_undoes_together() {
let mut s = session();
let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0);
let before = doc(&s).node(id).unwrap().appearance.clone();
let undo_before = undo_len(&s);
let result =
run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "paper-cutouts", "name": "Coral Layers", "apply": true, "ids": [id.0]}));
assert_eq!((names(&result["added"]), result["applied"].as_str()), (vec!["Coral Layers"], Some("Coral Layers")));
assert_eq!(undo_len(&s), undo_before + 1);
let applied = &doc(&s).node(id).unwrap().appearance;
assert_eq!(applied.items.len(), 3);
assert_eq!(applied.effects[0].id, "stylize.dropShadow");
assert_eq!(applied.effects[0].params["blur"], 0.0);
run(&mut s, "edit.undo", json!({}));
assert_eq!(doc(&s).node(id).unwrap().appearance, before);
}
#[test]
fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() {
let mut s = session();
+66
View File
@@ -569,6 +569,72 @@ fn ungroup_and_sort_by_kind_are_one_undo_step_each() {
assert_eq!(n[n.iter().position(|x| x == "Orange").unwrap() + 1], "Ocean", "the spot colour comes after the process ones, then the gradients");
}
/// Color Group Options renames a color group alone, as one undo step: its swatches, their colors
/// and the art linked to them stay as they are. A name another group or a swatch has, an empty
/// name and a parameter that is missing or not a string are errors that change nothing, and the
/// group's own name records no undo step.
#[test]
fn rename_group_renames_only_the_group_in_one_undo_step() {
let mut s = session();
run(&mut s, "swatch.edit", json!({"name": "Bright Red", "global": true}));
let a = rect_filled(&mut s, json!({"swatch": "Bright Red"}));
let linked = fill(&s, a);
let members = names(&s, Some("Brights"));
let before = doc(&s).clone();
let undo = undo_len(&s);
assert_eq!(run(&mut s, "swatch.renameGroup", json!({"group": "Brights", "name": " Vivid Colors "}))["name"], "Vivid Colors");
assert!(doc(&s).swatch_groups.iter().all(|g| g.name != "Brights"));
assert_eq!(names(&s, Some("Vivid Colors")), members);
assert_eq!(fill(&s, a), linked, "linked art keeps its swatch and color");
assert_eq!(undo_len(&s), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(*doc(&s), before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(names(&s, Some("Vivid Colors")), members);
let renamed = doc(&s).clone();
// The group's own name, trimmed, changes nothing.
assert_eq!(run(&mut s, "swatch.renameGroup", json!({"group": "Vivid Colors", "name": " Vivid Colors"}))["name"], "Vivid Colors");
assert_eq!(undo_len(&s), undo + 1);
let refused = [
json!({"group": "Vivid Colors", "name": "Grays"}),
json!({"group": "Vivid Colors", "name": "White"}),
json!({"group": "Vivid Colors", "name": "[None]"}),
json!({"group": "Vivid Colors", "name": "[Registration]"}),
json!({"group": "Vivid Colors", "name": ""}),
json!({"group": "Vivid Colors", "name": " "}),
json!({"group": "Vivid Colors"}),
json!({"group": "Vivid Colors", "name": null}),
json!({"group": "Vivid Colors", "name": 5}),
json!({"name": "Bold"}),
json!({"group": 5, "name": "Bold"}),
json!({"group": "Nope", "name": "Bold"}),
json!({"group": "White", "name": "Bold"}),
];
for p in refused {
assert!(s.execute("swatch.renameGroup", &p).is_err(), "{p}");
assert_eq!(*doc(&s), renamed, "{p}");
assert_eq!(undo_len(&s), undo + 1, "{p}");
}
}
/// A color group renamed while a drag is still in progress keeps its new name when the drag is
/// canceled: the drag becomes a step of its own first, and the rename is the next step.
#[test]
fn rename_group_during_a_drag_is_a_step_of_its_own() {
let mut s = session();
rect_filled(&mut s, json!({"swatch": "Bright Red"}));
let undo = undo_len(&s);
s.begin_interaction("Move").unwrap();
s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap();
run(&mut s, "swatch.renameGroup", json!({"group": "Brights", "name": "Vivid"}));
s.cancel_interaction().ok();
assert!(doc(&s).swatch_groups.iter().any(|g| g.name == "Vivid"), "canceling the drag keeps the rename");
assert_eq!(undo_len(&s), undo + 2, "the drag and the rename are two steps");
run(&mut s, "edit.undo", json!({}));
assert!(doc(&s).swatch_groups.iter().any(|g| g.name == "Brights"), "Undo takes back the rename alone");
assert_eq!(undo_len(&s), undo + 1);
}
#[test]
fn a_cmyk_document_starts_with_cmyk_swatches_and_stores_new_colours_as_cmyk() {
use vectorcraft_color::Color;
+246 -16
View File
@@ -119,6 +119,50 @@ fn average_brings_the_instances_under_the_brush_toward_their_mean() {
assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}");
}
/// `tool.setOption` refuses a Method, a Symbol Sprayer option or a checkbox value the Symbolism Tools
/// Options do not have, and sets none of the values given with it.
#[test]
fn bad_symbolism_tool_options_are_refused() {
let mut s = session();
let before = s.tool_options_of("symbolSizer");
for (values, want) in [
(json!({"proportional": false, "method": "smooth"}), "`method` must be one of userDefined, average, random"),
(json!({"sprayScrunch": "random"}), "`sprayScrunch` must be one of average, userDefined"),
(json!({"method": "average", "usePressure": 1}), "`usePressure` must be true or false"),
(json!({"affectsDensity": "yes"}), "`affectsDensity` must be true or false"),
] {
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": values}));
assert_eq!(r, Err(want.to_string()), "{values}");
assert_eq!(s.tool_options_of("symbolSizer"), before, "{values}");
}
s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "key": "method", "value": "random"})).unwrap();
assert_eq!(s.tool_options_of("symbolSizer")["method"], json!("random"));
}
/// Average opacities below the Symbol Screener's least opacity (5%) stay below it: with the Screener
/// the instances meet at their mean, and a sprayed instance takes the mean of those under the brush.
#[test]
fn average_keeps_opacities_below_the_screeners_least() {
let mut s = session();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let a = members(&s, set)[0];
let b = dot(&mut s, 220.0, 150.0);
for (id, opacity) in [(a, 0), (b, 2)] {
s.select(|_, sel| sel.set([id])).unwrap();
s.execute("transparency.set", &json!({"opacity": opacity})).unwrap();
}
s.select(|_, sel| sel.set([set])).unwrap();
// A new instance beside the invisible one takes its opacity.
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[185, 150]], "radius": 20})).unwrap();
let sprayed = *members(&s, set).last().unwrap();
assert_eq!(node(&s, sprayed).opacity, 0.0);
// The Screener with Average brings 0% and 2% toward 1%, not up to 5%.
s.select(|_, sel| sel.clear()).unwrap();
adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"}));
let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity);
assert!(pa > 0.0 && pa < 0.02 && pb < 0.02 && pb > 0.0, "{pa} {pb}");
}
/// Average over instances that already have the mean, or a stroke over no instance, changes
/// nothing and adds no undo step.
#[test]
@@ -233,6 +277,24 @@ fn random_changes_each_instance_by_its_own_share() {
assert_eq!(grown(Some("random")), random);
}
/// With Method Random the Symbol Styler gives each instance its share of the style scaled by the
/// brush strength: at Intensity 1 a tenth of what it gives at Intensity 10.
#[test]
fn random_style_follows_the_brush_strength() {
let styled = |intensity: u32| {
let mut s = session();
let ids = [(200.0, 150.0), (201.0, 150.0), (200.0, 151.0), (199.0, 150.0), (200.0, 149.0)].map(|(x, y)| dot(&mut s, x, y));
let p = json!({"tool": "style", "points": [[200, 150]], "radius": 1000, "intensity": intensity, "method": "random", "color": "#ff0000"});
adjust(&mut s, p);
ids.map(|id| f64::from(node(&s, id).appearance.fill().map_or(0.0, |f| f.opacity)))
};
let (full, low) = (styled(10), styled(1));
assert!(full.iter().any(|o| *o > 0.05), "{full:?}");
for (f, l) in full.iter().zip(&low) {
assert!((l - f * 0.1).abs() < 1e-3, "{low:?} against {full:?}");
}
}
/// A `method` that is none of the three is an error and changes nothing; the Symbol Shifter takes
/// one and shifts as it does without.
#[test]
@@ -266,12 +328,12 @@ fn tool_set_option_refuses_bad_symbolism_options() {
let mut s = session();
let before = s.tool_options_of("symbolSizer");
for (key, bad, want) in [
("method", json!("smooth"), "`method` must be userDefined, average or random, not \"smooth\""),
("sprayStain", json!("random"), "`sprayStain` must be average or userDefined, not \"random\""),
("method", json!("smooth"), "`method` must be one of userDefined, average, random"),
("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"),
("usePressure", json!("yes"), "`usePressure` must be true or false"),
("diameter", json!("big"), "`diameter` must be a number"),
("style", json!(3), "`style` must be a name or null"),
("diameter", json!(1), "tool `symbolSizer`: `diameter` must be a number from 2 to 2000"),
("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"),
("style", json!(3), "`style` must be a string or null"),
("diameter", json!(1), "`diameter` must be a number from 2 to 2000"),
] {
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}}));
assert_eq!(r, Err(want.to_string()), "{key}");
@@ -423,10 +485,10 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() {
s.execute("symbol.spray", &p).unwrap();
*members(s, set).last().unwrap()
};
// Average (the default): the new instance, sprayed beside it, looks like it.
// Average (the default): the new instance, sprayed beside it, looks like it, at its size.
let near = spray(&mut s, json!([[215, 150]]), json!({}));
let (w, o, f) = look(&s, near);
assert!((w / width - 1.0).abs() < 0.11, "{w} of {width}");
assert!((w / width - 1.0).abs() < 1e-9, "{w} of {width}");
assert_eq!((o, f), (opacity, stain.clone()));
// The averages of two instances that look alike are theirs.
let third = spray(&mut s, json!([[208, 165]]), json!({"attributes": {"size": "average", "screen": null}}));
@@ -434,10 +496,10 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() {
// Style: Average replaces a User Defined stain with the fill of the instances under the brush.
let mixed = spray(&mut s, json!([[205, 160]]), json!({"attributes": {"stain": "userDefined"}, "color": "#0000ff"}));
assert_eq!(look(&s, mixed).2.map(|(c, _)| c), stain.clone().map(|(c, _)| c));
// Outside the brush's radius of every instance, the plain values.
// Outside the brush's radius of every instance, the plain values: the symbol's own size.
let far = spray(&mut s, json!([[330, 250]]), json!({}));
let (w, o, f) = look(&s, far);
assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0 && f.is_none(), "{w} {o} {f:?}");
assert!((w / 20.0 - 1.0).abs() < 1e-9 && o == 1.0 && f.is_none(), "{w} {o} {f:?}");
// User Defined: the symbol's size and opaque; Style: Average still gives the fill under the brush.
let user = json!({"size": "userDefined", "screen": "userDefined", "stain": "userDefined", "spin": "userDefined"});
let plain = spray(&mut s, json!([[212, 140]]), json!({"attributes": user, "color": "#0000ff"}));
@@ -459,6 +521,77 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() {
assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush");
}
/// Size: Average is a size on the page, the same measure for every symbol: a 20 pt symbol sprayed
/// beside an 80 pt one is 80 pt, and the Sizer brings the two to 40 pt. With no instance under the
/// brush a sprayed instance has its symbol's own size, whatever `scale` is.
#[test]
fn average_sizes_are_sizes_on_the_page_for_every_symbol() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap();
s.execute("symbol.new", &json!({"name": "Big"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Big", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let big = members(&s, set)[0];
assert!((bounds(&s, big).width() - 80.0).abs() < 1e-9);
let spray = |s: &mut Session, at: Value| {
s.execute("symbol.spray", &json!({"name": "Dot", "points": at, "radius": 30, "scale": 2})).unwrap();
*members(s, set).last().unwrap()
};
let near = spray(&mut s, json!([[215, 150]]));
assert!((bounds(&s, near).width() - 80.0).abs() < 1e-9, "{}", bounds(&s, near).width());
let far = spray(&mut s, json!([[350, 40]]));
assert!((bounds(&s, far).width() - 20.0).abs() < 1e-9, "{}", bounds(&s, far).width());
// The Sizer: an unscaled Dot and an unscaled Big meet at the geometric mean of 20 and 80.
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap();
s.execute("symbol.new", &json!({"name": "Big"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let small = dot(&mut s, 200.0, 150.0);
let big = NodeId(s.execute("symbol.place", &json!({"name": "Big", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.clear()).unwrap();
let between = json!([[210, 150], [210, 150], [210, 150], [210, 150], [210, 150], [210, 150]]);
adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"}));
let (ws, wb) = (bounds(&s, small).width(), bounds(&s, big).width());
assert!(ws > 30.0 && wb < 55.0 && (ws * wb / 1600.0 - 1.0).abs() < 1e-9, "{ws} {wb}");
// A symbol without a recorded size is measured by its art: here 80 pt art drawn at its own size.
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 20, "height": 20})).unwrap();
s.execute("symbol.new", &json!({"name": "Loose"})).unwrap();
s.edit("Forget size", |d, _| {
if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) {
m.remove("Loose");
}
for sym in d.symbols.iter_mut().filter(|sym| sym.name == "Loose") {
std::sync::Arc::make_mut(&mut sym.art).transform(Affine::scale(4.0), false);
}
Ok(())
})
.unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let small = dot(&mut s, 200.0, 150.0);
let loose = NodeId(s.execute("symbol.place", &json!({"name": "Loose", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.clear()).unwrap();
// Its width as drawn, measured by its symbol's art.
let drawn = |s: &Session| {
let d = &s.doc().unwrap().doc;
node(s, loose).geometric_bounds_with(&d.symbol_boxes()).unwrap().width()
};
assert!((drawn(&s) - 80.0).abs() < 1e-9, "{}", drawn(&s));
adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"}));
let (ws, wl) = (bounds(&s, small).width(), drawn(&s));
assert!(ws > 30.0 && wl < 55.0, "{ws} {wl}");
// A new set sprayed with Size: Average is spaced by the size it is placed at, not by `scale`.
s.select(|_, sel| sel.clear()).unwrap();
let stroke: Vec<Value> = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 20.0])).collect();
let r = s.execute("symbol.spray", &json!({"name": "Dot", "points": stroke, "radius": 2, "scale": 100})).unwrap();
assert!(r["count"].as_u64().unwrap() > 5, "{r}");
// The 80 pt art of a symbol without a recorded size spaces new instances by its own size.
s.select(|_, sel| sel.clear()).unwrap();
let stroke: Vec<Value> = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 280.0])).collect();
let r = s.execute("symbol.spray", &json!({"name": "Loose", "points": stroke, "radius": 2})).unwrap();
assert!(r["count"].as_u64().unwrap() <= 5, "{r}");
}
/// Spin: Average turns a new instance to the mean direction of the instances under the brush, and
/// Scrunch: Average spaces new instances as those under the brush are spaced.
#[test]
@@ -507,6 +640,13 @@ fn bad_sprayer_attributes_are_refused() {
}
refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "keepModel": "yes"}), "`keepModel` must be true or false");
refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150, "x"]]}), "a point's pressure must be a number, not \"x\"");
// Style: User Defined with a style the document does not have; Average does not use it.
let user = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": "Nope"});
refused(&mut s, "symbol.spray", user, "unknown graphic style `Nope`");
let number = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": 3});
refused(&mut s, "symbol.spray", number, "`style` must be a graphic style's name, not 3");
let average = json!({"name": "Dot", "points": [[200, 150]], "style": "Nope"});
assert_eq!(s.execute("symbol.spray", &average).unwrap()["count"], 1);
let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"});
assert_eq!(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "attributes": all})).unwrap()["count"], 1);
}
@@ -537,15 +677,11 @@ fn set_density_spaces_the_instances_of_a_symbol_set() {
let r = s.execute("symbol.setDensity", &json!({"from": 9, "to": 5, "ids": [set.0, set.0]})).unwrap();
assert_eq!(r, json!({"ids": [set.0], "count": 8}));
assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9));
// The density the set has (5, a `from` of 7 notwithstanding), or a set of one instance: no
// instance moves and no undo step is added.
// The density the set has (5, a `from` of 7 notwithstanding): no instance moves and no undo
// step is added.
let steps = undo_len(&s);
assert_eq!(s.execute("symbol.setDensity", &json!({"from": 7, "to": 5})).unwrap(), json!({"ids": [], "count": 0}));
s.select(|_, sel| sel.clear()).unwrap();
let one = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 40]]})).unwrap()["id"].as_u64().unwrap());
let steps_with_one = undo_len(&s);
assert_eq!(s.execute("symbol.setDensity", &json!({"from": 1, "to": 10, "ids": [one.0]})).unwrap(), json!({"ids": [], "count": 0}));
assert_eq!((steps_with_one, undo_len(&s)), (steps + 1, steps + 1));
assert_eq!(undo_len(&s), steps);
// Undo puts a spaced set back.
s.execute("symbol.setDensity", &json!({"from": 5, "to": 1, "id": set.0})).unwrap();
assert!(centers(&s)[0].distance(was[0]) > 1.0);
@@ -628,6 +764,31 @@ fn a_copied_set_packs_from_the_density_of_its_source() {
}
}
/// A set of one instance takes the new density without moving, as one undo step, so a later change
/// packs it from that density; setting the density it already has adds no undo step.
#[test]
fn set_density_gives_a_set_of_one_instance_the_new_density() {
let mut s = session();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let steps = undo_len(&s);
assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [set.0], "count": 0}));
assert_eq!(undo_len(&s), steps + 1);
assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [], "count": 0}));
assert_eq!(undo_len(&s), steps + 1);
// A second instance, then from the set's 9 to 5: 0.65 / 0.25 of each distance from the middle.
s.select(|_, sel| sel.set([set])).unwrap();
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4, "density": 9})).unwrap();
let ids = members(&s, set);
assert_eq!(ids.len(), 2);
let was: Vec<Point> = ids.iter().map(|id| center(&s, *id)).collect();
let middle = Point::new((was[0].x + was[1].x) / 2.0, (was[0].y + was[1].y) / 2.0);
s.execute("symbol.setDensity", &json!({"from": 5, "to": 5, "ids": [set.0]})).unwrap();
for (id, before) in ids.iter().zip(&was) {
let want = middle + (*before - middle) * (0.65 / 0.25);
assert!(center(&s, *id).distance(want) < 1e-9, "{before:?} -> {:?}", center(&s, *id));
}
}
/// A locked instance of the set stays where it is, and the others move.
#[test]
fn set_density_leaves_a_locked_instance_in_place() {
@@ -774,6 +935,46 @@ fn the_shifter_moves_an_instance_without_a_size() {
assert!(state(&s) == before);
}
/// An instance with no size is shifted and screened as before; only Average, which needs its size,
/// leaves it as it is.
#[test]
fn an_instance_without_a_size_is_changed_by_every_method_but_average() {
// A Dot at 200, 150 whose size is 0, and Dots at the other centers.
let flat = |others: &[(f64, f64)]| {
let mut s = session();
let a = dot(&mut s, 200.0, 150.0);
for (x, y) in others {
dot(&mut s, *x, *y);
}
s.edit("Flatten", |d, _| {
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
*xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]);
}
Ok(())
})
.unwrap();
(s, a)
};
let (mut s, a) = flat(&[(210.0, 150.0)]);
let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [205, 150]], "radius": 40, "intensity": 10}));
assert_eq!(r["count"], 2);
assert!(center(&s, a).x > 200.5, "{:?}", center(&s, a));
let r = adjust(&mut s, json!({"tool": "screen", "points": [[205, 150]], "radius": 40, "intensity": 10}));
assert_eq!(r["count"], 2);
assert!(node(&s, a).opacity < 1.0);
// Average brings the other two toward their mean and leaves the one without a size as it is.
let (mut s, a) = flat(&[(190.0, 150.0), (210.0, 150.0)]);
adjust(&mut s, json!({"tool": "screen", "points": [[190, 150]], "radius": 2, "intensity": 10}));
let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 40, "intensity": 10, "method": "average"}));
assert_eq!(r["count"], 2);
assert_eq!(node(&s, a).opacity, 1.0);
// With only it under the brush there is no mean, and Average changes nothing.
let before = state(&s);
let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 5, "intensity": 10, "method": "average"}));
assert_eq!(r["count"], 0);
assert!(state(&s) == before);
}
/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes
/// the stain the mean picks, not its hidden paint.
#[test]
@@ -796,3 +997,32 @@ fn average_stain_replaces_a_stain_at_no_opacity() {
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
assert!(f.opacity > 0.0, "{}", f.opacity);
}
/// A stroke that leaves every instance under the brush as it is (each already at full stain, or
/// at the least opacity) counts none and adds no undo step.
#[test]
fn a_stroke_that_changes_no_instance_adds_no_undo_step() {
let mut s = session();
dot(&mut s, 200.0, 150.0);
let full = json!(vec![[200, 150]; 12]);
for tool in ["stain", "screen"] {
adjust(&mut s, json!({"tool": tool, "points": full, "radius": 40, "intensity": 10, "color": "#ff0000"}));
let before = state(&s);
let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150]], "radius": 40, "intensity": 10, "color": "#ff0000"}));
assert_eq!(r["count"], 0, "{tool}");
assert!(state(&s) == before, "{tool} changed the document");
}
}
/// An instance a stroke moves away and back to where it was is not counted, and the stroke adds
/// no undo step: the Shifter's drag out and back moves it 8 pt right, then 8 pt left.
#[test]
fn an_instance_moved_away_and_back_is_not_counted() {
let mut s = session();
let id = dot(&mut s, 200.0, 150.0);
let before = state(&s);
let r = adjust(&mut s, json!({"tool": "shift", "points": [[196, 166], [212, 166], [196, 166]], "radius": 40, "intensity": 10}));
assert_eq!(bounds(&s, id).center(), Point::new(200.0, 150.0));
assert_eq!(r["count"], 0);
assert!(state(&s) == before, "the stroke added an undo step");
}
+41 -1
View File
@@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() {
let mut s = Session::new();
let list = run(&mut s, "symbol.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
assert_eq!(libs.len(), 6, "{libs:?}");
assert_eq!(libs.len(), 7, "{libs:?}");
assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn")));
assert_eq!(
(libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()),
@@ -106,6 +106,10 @@ fn the_builtin_library_is_original_art_generated_in_code() {
(libs[5]["id"].as_str(), libs[5]["name"].as_str(), libs[5]["category"].as_str()),
(Some("weather-icons"), Some("Weather Icons"), Some("builtIn"))
);
assert_eq!(
(libs[6]["id"].as_str(), libs[6]["name"].as_str(), libs[6]["category"].as_str()),
(Some("media-controls"), Some("Media Controls"), Some("builtIn"))
);
let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"}));
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]);
@@ -245,6 +249,42 @@ fn weather_icons_library_lists_and_places() {
}
}
#[test]
fn media_controls_library_lists_and_places() {
let mut s = session();
let lib = run(&mut s, "symbol.library", json!({"library": "media-controls"}));
let symbols = lib["symbols"].as_array().unwrap();
assert_eq!(symbols.len(), 6, "media-controls must load with exactly 6 symbols");
let names: Vec<&str> = symbols.iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Play", "Pause", "Stop", "Skip Next", "Shuffle", "Repeat"]);
let mut placed = Vec::new();
for (i, name) in names.iter().enumerate() {
let r = run(
&mut s,
"symbol.addFromLibrary",
json!({"library": "media-controls", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}),
);
assert_eq!(r["added"], json!([name]));
placed.push(r["placed"].as_u64().unwrap());
}
let d = doc(&s);
for (i, name) in names.iter().enumerate() {
assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides");
assert!(matches!(
d.node(NodeId(placed[i])).map(|n| &n.kind),
Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == *name
));
let sym = d.symbols.iter().find(|s| s.name == *name).expect("symbol exists in document");
assert!(matches!(sym.art.kind, NodeKind::Path { .. }), "{name} art should be a path");
if let NodeKind::Path { path, .. } = &sym.art.kind {
assert!(!path.subpaths.is_empty(), "{name} path data must have subpaths");
for sp in &path.subpaths {
assert!(!sp.anchors.is_empty(), "{name} subpath must contain anchor points");
}
}
}
}
#[test]
fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() {
let dir = folder("user");
+31
View File
@@ -4129,3 +4129,34 @@ fn new_type_takes_the_normal_character_style_fill_not_the_current_fill() {
let made = s.execute("text.create", &json!({"x": 100, "y": 400, "text": "Green", "color": "#00ff00"})).unwrap();
assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
}
/// A client answers the question a Type tool click asks about type in a missing font through
/// `tool.setOption {key: "missingFontEdit", value: {token, ok}}`: OK starts the edit at the next poll.
#[test]
fn tool_set_option_answers_the_missing_font_question() {
let mut s = session();
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Hello", "size": 20, "font": "Missing Test Family 8408"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
let t = obj(&s, id);
let (a, b) = vectorcraft_text::caret_position(&vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t), 2);
let at = t.xf * a.midpoint(b);
let mut asked = vec![];
for k in [PointerKind::Down, PointerKind::Up] {
asked.extend(s.pointer(&PointerEvent::new(k, at.x + 0.1, at.y), v).unwrap());
}
let token = asked
.iter()
.find_map(|r| match r {
UiRequest::Dialog(k, p) if k == "missingFontEdit" => p["token"].as_u64(),
_ => None,
})
.unwrap_or_else(|| panic!("the missing-font question: {asked:?}"));
assert!(!s.tool_wants_text());
s.set_tool_option_cmd(&json!({"key": "missingFontEdit", "value": {"token": token, "ok": true}})).unwrap();
s.tool_poll(v, false).unwrap();
assert!(s.tool_wants_text());
assert_eq!(s.tool_options()["editing"], json!(id.0));
}
+35
View File
@@ -480,6 +480,41 @@ fn reflect_and_shear_tools() {
assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}");
}
/// Two clicks with the Reflect tool reflect the selection across the line through both points as
/// one undo step; with Alt on the second click, a copy is reflected and Undo removes it.
#[test]
fn two_reflect_clicks_reflect_across_their_line_as_one_undo_step() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
s.select_tool("reflect", ViewInfo::default()).unwrap();
let click = |s: &mut Session, x: f64, y: f64, alt: bool| {
drag_at(s, PointerKind::Down, (x, y), alt);
drag_at(s, PointerKind::Up, (x, y), alt);
};
let n = undo_len(&s);
click(&mut s, 300.0, 50.0, false);
assert_eq!(undo_len(&s), n);
assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0)));
click(&mut s, 300.0, 250.0, false);
assert!(close(bounds(&s, a), Rect::new(400.0, 100.0, 500.0, 150.0)), "{:?}", bounds(&s, a));
assert_eq!(undo_len(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0)));
let children = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
click(&mut s, 50.0, 300.0, false);
click(&mut s, 350.0, 300.0, true);
assert_eq!(children(&s), 2);
assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0)));
// The copy is selected and reflected across y = 300.
let copy = s.doc().unwrap().selection.objects.clone();
assert!(copy.len() == 1 && copy[0] != a, "{copy:?}");
assert!(close(bounds(&s, copy[0]), Rect::new(100.0, 450.0, 200.0, 500.0)), "{:?}", bounds(&s, copy[0]));
assert_eq!(undo_len(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(children(&s), 1);
}
/// 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.