Merge main into feat/color-wheel-document-colors

This commit is contained in:
dotCooCoo
2026-11-19 13:06:47 -08:00
186 changed files with 8174 additions and 557 deletions
+62 -7
View File
@@ -114,6 +114,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"bristle-brushes",
"paint",
"pattern-borders",
"decorative",
"scatter-shapes",
"stipple",
"game-trails",
@@ -127,6 +128,20 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
// None of them is a default brush.
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
for id in ids {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
}
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn the_builtin_libraries_list_their_brush_names_and_counts() {
let mut s = Session::new();
let list = run(&mut s, "brush.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
// 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"}));
@@ -135,6 +150,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"]
);
assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5));
assert_eq!((entry("decorative")["name"].as_str(), entry("decorative")["count"].as_u64()), (Some("Decorative"), Some(4)));
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<_>>(),
@@ -164,6 +180,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
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]}));
assert_eq!(strs(&added["added"]), ["Laser Bolt"]);
}
#[test]
fn every_builtin_library_brush_has_its_kind_and_draws() {
let s = Session::new();
// One kind of brush per library (Ink and Wash: art brushes and a calligraphic one), every
// brush drawing something.
for (id, kind) in [
@@ -174,6 +195,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("bristle-brushes", "bristle"),
("paint", "art"),
("pattern-borders", "pattern"),
("decorative", "pattern"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
("game-trails", "art"),
@@ -195,6 +217,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &stroke).is_empty(), "{} draws nothing", b.name);
}
}
}
#[test]
fn builtin_library_brushes_bring_the_resources_their_art_uses() {
let s = Session::new();
// The resources their art uses come with them: Striped Ribbon's pattern, Sparkles' symbol.
let (_, ribbons) = cmd::brushlib::library(&s, "art-ribbons").unwrap();
assert_eq!(art_patterns(ribbons.brush("Striped Ribbon").unwrap()), ["Pinstripes"]);
@@ -203,13 +230,6 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let BrushKind::Scatter(sparkles) = &shapes.brush("Sparkles").unwrap().kind else { panic!("not a scatter brush") };
assert!(matches!(&sparkles.art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Sparkle"));
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
// None of them is a default brush.
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
for id in ids {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
}
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
@@ -562,6 +582,41 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Decorative").unwrap();
let names = ["Leaf Vine", "Blossom Chain", "Pennant Garland", "Lantern String"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut signatures = std::collections::HashSet::new();
for b in &lib.brushes {
let BrushKind::Pattern(pattern) = &b.kind else { panic!("{} is not a pattern brush", b.name) };
assert_eq!(pattern.colorization, vectorcraft_brush::Colorization::Tints);
let points = |len: f64| anchors(&vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(len), &black_stroke()).iter().collect::<Vec<_>>());
let (one, four) = (points(48.0), points(192.0));
assert!(!one.is_empty() && four.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
// A path four tiles long places the motif four times, each copy one tile further along.
assert_eq!(four.len(), 4 * one.len(), "{} repeats its motif", b.name);
for (i, p) in four.iter().enumerate() {
let q = one[i % one.len()];
let shift = 48.0 * (i / one.len()) as f64;
assert!((p.x - q.x - shift).abs() < 1e-3 && (p.y - q.y).abs() < 1e-3, "{} copy {} at {p:?}, not {q:?}", b.name, i / one.len());
}
signatures.insert(one.iter().map(|p| ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)).collect::<Vec<_>>());
let before = undo_len(&s);
let applied = run(&mut s, "brush.addFromLibrary", json!({"library": "decorative", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!((strs(&applied["added"]), &applied["applied"]), (vec![b.name.as_str()], &json!([path])));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
assert_eq!(signatures.len(), names.len(), "each design produces a different repeating shape");
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 pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
+63 -1
View File
@@ -3434,6 +3434,65 @@ fn live_paint_bucket_gradient_preset_and_sampled_stop_follow_the_active_proxy()
assert_eq!(node(&s, rect), art, "the selection keeps its paint");
}
/// The Gradient panel's eyedropper, used on a stop of the Live Paint Bucket's gradient, samples the
/// color clicked into that stop of the bucket's fill, and the selection keeps its paint. A Cmd-click
/// with the bucket, or with the Eyedropper armed for it, which the selection tool takes, leaves the
/// bucket's colors as they were.
#[test]
fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_click() {
let v = ViewInfo::default();
let click = |s: &mut Session, mods: Mods| {
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 320.0, 320.0).with_mods(mods), v).unwrap();
}
};
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": false})).unwrap();
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.select_tool("livePaintBucket", v).unwrap();
s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap();
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
let art = node(&s, rect);
// The panel's eyedropper (`stop_eyedropper`): the Eyedropper, set to switch back to the bucket.
s.select_tool("eyedropper", v).unwrap();
s.set_tool_option("stop", &json!("livePaintBucket"));
assert_eq!(s.selected_stop(), Some(1), "the bucket's stop stays selected for the pick");
// A Cmd-click while the pick is armed selects the rectangle and leaves the bucket's gradient.
let fill = s.paint.fill.clone();
s.execute("select.set", &json!({"ids": []})).unwrap();
click(&mut s, Mods { cmd: true, ..Mods::default() });
assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click");
assert_eq!((s.paint.fill.clone(), s.selected_stop()), (fill, Some(1)), "the bucket's fill and stop stay");
click(&mut s, Mods::default());
let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") };
assert_eq!(g.gradient.stops[1].color, Color::from_hex("#00ff00").unwrap(), "the sampled stop");
assert_eq!(node(&s, rect), art, "the selection keeps its paint");
// A Cmd-click selects the rectangle; the bucket keeps its gradient.
s.select_tool("livePaintBucket", v).unwrap();
let fill = s.paint.fill.clone();
s.execute("select.set", &json!({"ids": []})).unwrap();
click(&mut s, Mods { cmd: true, ..Mods::default() });
assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click");
assert_eq!(s.paint.fill, fill, "the bucket's fill stays");
// Armed again, a Cmd-click on another object deselects the stop; the next click (a Shift-click,
// which would sample a color) ends the pick and leaves the bucket's gradient.
let other = self::rect(&mut s, 400.0, 400.0, 40.0, 40.0);
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
s.select_tool("eyedropper", v).unwrap();
s.set_tool_option("stop", &json!("livePaintBucket"));
for mods in [Mods { cmd: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() }] {
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 420.0, 420.0).with_mods(mods), v).unwrap();
}
}
assert_eq!(s.doc().unwrap().selection.objects, vec![other], "the Cmd-click selected the other object");
assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample");
}
/// 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.
@@ -9491,9 +9550,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() {
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])] {
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] {
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
}
// A null divider with another view is refused too, and the view stays.
assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err());
assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split);
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();
+21
View File
@@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() {
assert!(marked(b), "the opaque image it overlaps");
}
/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a
/// distorted plate image does not stop an image replacing the group.
#[test]
fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() {
let dir = temp_dir("replace-distorted");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
let group = r["ids"][0].clone();
let image = image_of(&s, &group).id;
let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap();
let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1);
let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]);
s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap();
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
let png = crate::tests_links::png(2, 2, [0, 0, 255]);
let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
assert!(out.is_ok(), "{out:?}");
}
#[test]
fn dcs_transparency_counts_characters_with_a_transparent_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
+75
View File
@@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
}
/// Update Links gives a distorted image its file's new pixels between the same corners: its
/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size,
/// and Link Info measures its scale at its middle.
#[test]
fn update_links_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-update");
let photo = dir.file("photo.png");
write(&photo, &png(20, 10, RED));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
let before = corners(&s);
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
// The far corner of the pixels as the transform alone places them.
let far = |s: &Session| {
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
};
let far_before = far(&s);
// Link Info measures the scale where the effective resolution is measured: at the middle.
let scale_matches_ppi = |s: &mut Session| {
let info = s.execute("links.info", &json!({"id": id.0})).unwrap();
for i in 0..2 {
let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap());
assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}");
}
};
scale_matches_ppi(&mut s);
// A copy in a symbol, distorted the same way, shows the same file.
let copy = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
let in_symbol = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
if let NodeKind::Image(im) = &n.kind {
out.push((n.is_distorted_image(), (im.width, im.height)));
}
});
out
};
let symbol_corners = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners()));
out
};
assert_eq!(in_symbol(&s), [(true, (20, 10))]);
let symbol_before = symbol_corners(&s);
assert_eq!(symbol_before.len(), 1);
write(&photo, &png(60, 20, BLUE));
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}");
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(n.is_distorted_image());
assert_eq!(corners(&s), before);
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
assert_eq!((im.width, im.height), (60, 20));
// The transform takes the new pixel size, so a placement by the transform keeps the old size.
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
let d = &s.doc().unwrap().doc;
assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped");
let mut clipped = false;
d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. }));
assert!(!clipped, "the symbol's image is not clipped");
assert_eq!(in_symbol(&s), [(true, (60, 20))]);
assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners");
scale_matches_ppi(&mut s);
}
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
+101
View File
@@ -59,6 +59,107 @@ fn a_whole_rectangle_rounds_all_corners_and_given_corners_alone() {
assert_eq!(corners(&s, id).1[3], CornerKind::Chamfer);
}
/// The Corner menus of Rectangle Properties: a kind for all four corners or one, set on corners
/// with no radius too and leaving the radii as they are, in one undo step; the kind the corners
/// already have adds no step.
#[test]
fn rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo() {
let (mut s, id) = session();
run(&mut s, json!({"corners": [1], "radius": 12}));
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = steps(&s);
run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"}));
assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]);
assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound; 4]);
assert_eq!(steps(&s), undo + 1);
run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"}));
run(&mut s, json!({"corners": [2], "kind": "invertedRound"}));
assert_eq!(steps(&s), undo + 1, "no step when nothing changes");
run(&mut s, json!({"corners": [2], "kind": "chamfer"}));
assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound, CornerKind::InvertedRound, CornerKind::Chamfer, CornerKind::InvertedRound]);
assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]);
assert_eq!(steps(&s), undo + 2);
}
/// A kind the corners already have leaves a rectangle saved stretched by an older version as it
/// is, alone or beside a rectangle the kind changes: its scale stays in its transform.
#[test]
fn a_kind_the_corners_have_leaves_a_stretched_rectangle() {
let (mut s, id) = session();
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
let stretched = LiveShape::Rectangle {
w: 50.0,
h: 60.0,
radii: [10.0; 4],
kinds: [CornerKind::Chamfer; 4],
radii_relative: false,
xf: Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(2.0, 1.0),
};
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, live: Some(live), .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not live") };
**live = stretched.clone();
*path = live.to_path();
}
let live = |s: &Session| node_path(s, id).1;
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = steps(&s);
run(&mut s, json!({"ids": [id.0], "kind": "chamfer"}));
assert_eq!(live(&s), Some(stretched.clone()));
assert_eq!(steps(&s), undo, "no step when nothing changes");
run(&mut s, json!({"ids": [id.0, other.0], "kind": "chamfer"}));
assert_eq!(live(&s), Some(stretched));
assert_eq!(corners(&s, other).1, [CornerKind::Chamfer; 4]);
assert_eq!(steps(&s), undo + 1);
}
/// A radius is stored on a corner that stores a larger radius drawn at the new value, alone or
/// beside another rectangle; the radius every target already stores adds no undo step.
#[test]
fn a_radius_reaches_a_rectangle_that_already_draws_it() {
let (mut s, id) = session();
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
// 80 pt on every corner draws at 30 pt, half the 60 pt side.
run(&mut s, json!({"ids": [id.0], "radius": 80}));
assert_eq!(corners(&s, id).0, [80.0; 4]);
let (path, live) = node_path(&s, id);
let drawn = LiveCorners::new(&path, live.as_ref()).unwrap().drawn_radius(0);
assert!((drawn - 30.0).abs() < 1e-9, "draws at {drawn}");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = steps(&s);
run(&mut s, json!({"ids": [id.0], "corners": [1], "radius": 30}));
assert_eq!(corners(&s, id).0, [80.0, 30.0, 80.0, 80.0]);
assert_eq!(steps(&s), undo + 1);
run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30}));
assert_eq!(corners(&s, id).0[0], 30.0);
assert_eq!(corners(&s, other).0[0], 30.0);
// The radius both already store adds no step.
run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30}));
assert_eq!(steps(&s), undo + 2);
}
/// `rectanglesOnly` sets the live rectangles among the selection and leaves a polygon as it is; an
/// action that records it holds no ids, so playing it sets the rectangles selected then.
#[test]
fn rectangles_only_sets_the_selected_rectangles_when_an_action_plays() {
let (mut s, id) = session();
let polygon = NodeId(s.execute("shape.polygon", &json!({"cx": 300, "cy": 300, "radius": 40, "sides": 6})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0, polygon.0]})).unwrap();
let start = s.journal.len();
run(&mut s, json!({"rectanglesOnly": true, "corners": [0], "kind": "chamfer"}));
assert_eq!(corners(&s, id).1[0], CornerKind::Chamfer);
let NodeKind::Path { live: Some(l), .. } = &s.doc().unwrap().doc.node(polygon).unwrap().kind else { panic!("not live") };
let LiveShape::Polygon { kinds, .. } = &**l else { panic!("not a polygon") };
assert!(kinds.iter().all(|k| *k == CornerKind::Round), "the polygon keeps its corners: {kinds:?}");
let action = s.journal_for_action(start);
assert_eq!(action.len(), 1);
assert_eq!(action[0].1.get("ids"), None);
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [other.0, polygon.0]})).unwrap();
s.replay(&action[0].0, &action[0].1).unwrap();
assert_eq!(corners(&s, other).1[0], CornerKind::Chamfer);
}
/// #938: `items` rounds several objects in one step, each its own corners (or all of them).
#[test]
fn items_round_several_objects_each_its_own_corners() {
+160
View File
@@ -1907,6 +1907,166 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() {
assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err());
}
/// The leaf objects of `n`, in paint order.
fn leaves_of(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::Node>) {
match n.children() {
Some(children) => children.iter().for_each(|c| leaves_of(c, out)),
None => out.push(n.clone()),
}
}
/// Apply the live Pathfinder effect `effect` with `params` to the selection, then expand its
/// appearance: the objects it draws.
fn live_pieces(s: &mut Session, effect: &str, params: Value) -> Vec<vectorcraft_doc::Node> {
let g = ids(&s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap())[0];
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
let mut out = vec![];
leaves_of(&node(s, g), &mut out);
out
}
/// The parameters of the first effect of the selected object.
fn first_effect_params(s: &Session) -> Value {
let st = s.doc().unwrap();
st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[0].params.clone()
}
/// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those its params
/// give aside, and its journal entry carries them.
#[test]
fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("object.pathfinder.options", &json!({"precision": 1, "removeRedundantPoints": true, "removeUnpainted": true})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap();
let all = json!({"precision": 1.0, "removeRedundantPoints": true, "removeUnpainted": true});
assert_eq!(first_effect_params(&s), all);
assert_eq!(s.journal.last().unwrap().1["params"], all, "the journal entry gives the options it used");
s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"precision": 0.5}})).unwrap();
let st = s.doc().unwrap();
let mix = &st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[1].params;
assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true}));
}
/// A live Pathfinder effect evaluates with its own options as the panel's operations do with
/// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled
/// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing.
#[test]
fn a_pathfinder_effect_evaluates_with_its_own_options() {
for (precision, faces) in [(0.01, 3), (1.0, 2)] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(live_pieces(&mut s, "pathfinder.divide", json!({"precision": precision})).len(), faces, "precision {precision}");
}
for on in [false, true] {
let mut s = session();
filled_and_unfilled(&mut s);
let divided = live_pieces(&mut s, "pathfinder.divide", json!({"removeUnpainted": on}));
let unfilled = divided.iter().filter(|n| n.appearance.fill_paint().is_none()).count();
assert_eq!((unfilled, divided.len() - unfilled), (if on { 0 } else { 2 }, 1), "removeUnpainted {on}");
}
for on in [false, true] {
let mut s = session();
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let united = live_pieces(&mut s, "pathfinder.add", json!({"removeRedundantPoints": on}));
let count = united[0].path_data().unwrap().anchor_count();
assert!(if on { count == 4 } else { count > 4 }, "removeRedundantPoints {on}: {count} anchors");
}
}
/// An effect saved before Pathfinder effects kept their own options draws as one given their
/// defaults, so older documents look as they did.
#[test]
fn a_pathfinder_effect_saved_without_options_draws_as_before() {
let draw = |params: Value| {
let mut s = session();
filled_and_unfilled(&mut s);
let g = ids(&s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap())[0];
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = params;
Ok(())
})
.unwrap();
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
serde_json::to_value(node(&s, g)).unwrap()
};
assert_eq!(draw(json!({})), draw(json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false})));
}
/// `effect.setParams` edits a Pathfinder effect's options as one undo step, records none for the
/// values it already evaluates with, and refuses values out of range or of the wrong type.
#[test]
fn pathfinder_effect_options_edit_as_one_step_and_refuse_bad_values() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
let before = steps(&s);
let same = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 0.01, "removeUnpainted": false}})).unwrap();
assert_eq!((same, steps(&s)), (json!({"ids": []}), before), "the values it has: no step");
// An effect saved without options evaluates with the defaults: given them, it is unchanged.
let g = s.doc().unwrap().selection.objects[0];
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = json!({});
Ok(())
})
.unwrap();
let before = steps(&s);
let defaults = json!({"index": 0, "params": {"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}});
assert_eq!(s.execute("effect.setParams", &defaults).unwrap(), json!({"ids": []}));
assert_eq!(steps(&s), before);
s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 2, "removeRedundantPoints": true}})).unwrap();
assert_eq!(steps(&s), before + 1, "one step");
assert_eq!(first_effect_params(&s), json!({"precision": 2, "removeRedundantPoints": true}));
let kept = doc(&s);
for bad in [
json!({"precision": 0}),
json!({"precision": 11}),
json!({"precision": "1 pt"}),
json!({"precision": null}),
json!({"removeRedundantPoints": "yes"}),
json!({"removeUnpainted": 1}),
] {
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": bad})).is_err(), "setParams {bad}");
assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.trim", "params": bad})).is_err(), "apply {bad}");
assert_eq!(doc(&s), kept, "{bad} changes nothing");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first_effect_params(&s), json!({}), "undo restores the options");
}
/// A precision that Scale Strokes & Effects took past the range evaluates at its bound, and setting
/// the bound is still an edit: a later scale then starts from the value set.
#[test]
fn a_precision_set_after_a_scale_past_its_range_is_kept() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.add", "params": {"precision": 8}})).unwrap();
let precision = |s: &Session| first_effect_params(s)["precision"].as_f64();
s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap();
assert_eq!(precision(&s), Some(16.0));
let steps = s.doc().unwrap().history.undo.len();
let out = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 10}})).unwrap();
assert_ne!(out, json!({"ids": []}), "an edit");
assert_eq!((precision(&s), s.doc().unwrap().history.undo.len()), (Some(10.0), steps + 1));
s.execute("object.scale", &json!({"sx": 50, "strokes": true})).unwrap();
assert_eq!(precision(&s), Some(5.0));
// The value it stores is still no edit.
let steps = s.doc().unwrap().history.undo.len();
assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 5}})).unwrap(), json!({"ids": []}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
}
/// A single group containing multiple overlapping paths is accepted by Crop.
#[test]
fn crop_operates_on_a_single_selected_group_of_paths() {
+20
View File
@@ -1590,6 +1590,26 @@ fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
}
/// A distorted image is read where its pixels are drawn, between its corners.
#[test]
fn theme_picker_reads_a_distorted_image_where_it_is_drawn() {
let mut s = session();
let (id, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
let (x, y0, y1) = (b.x1 + 20.0, b.y0, b.y1);
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "object.distort", json!({"corners": [[x + 40.0, y0], [x + 60.0, y0], [x + 100.0, y1], [x, y1]]}));
// The lower left of the trapezoid, outside the rectangle the image was placed in: red.
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [x + 2.0, y1 - 4.0, x + 20.0, y1 - 1.0]}]})), ["rgb 255 0 0"]);
// Where the image was: nothing.
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [b.x0 + 1.0, b.y0 + 1.0, b.x1 - 1.0, b.y1 - 1.0]}]})).is_empty());
// A marquee reaching past the horizon its sides meet at (a quarter of its height above its
// top) still reads every pixel it covers.
let h = y1 - y0;
let mut both = pick_theme(&mut s, json!({"picks": [{"rect": [x - 10.0, y0 - h, x + 110.0, y1 + 1.0]}]}));
both.sort();
assert_eq!(both, ["rgb 0 0 255", "rgb 255 0 0"]);
}
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
#[test]
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
@@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() {
assert!(state(&s) == before);
}
/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque
/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke
/// that changes no instance adds no undo step.
#[test]
fn an_instance_left_as_it_is_is_not_counted() {
let mut s = session();
let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap();
let before = state(&s);
let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true}));
assert_eq!(r["count"], 0, "Alt on an opaque instance");
let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10}));
assert_eq!(r["count"], 0, "an instance at 5%");
assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history");
// A stroke over both counts only the instance it changes.
let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10}));
assert_eq!(r["count"], 1);
assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05);
}
/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and
/// the Symbol Screener's instances take the mean of the instances under the brush.
#[test]
fn average_keeps_a_mean_opacity_below_five_percent() {
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 first = members(&s, set)[0];
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap();
s.select(|_, sel| sel.set([set])).unwrap();
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap();
let sprayed = *members(&s, set).last().unwrap();
assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity);
// Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it.
let mut s = session();
let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0));
s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap();
s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).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 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}");
}
/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing.
#[test]
fn average_evens_out_the_stain_and_the_spacing() {
@@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() {
assert_eq!(center(&s, a), Point::new(200.0, 150.0));
}
/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the
/// tool's options stay as they were.
#[test]
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 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 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}");
assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}");
}
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap();
assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined")));
// Every option the options dialog sends is taken, together.
let all = json!({
"diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false,
"sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined",
"sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true,
});
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap();
for (key, v) in all.as_object().unwrap() {
assert_eq!(&r[key], v, "{key}");
}
}
/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is
/// not used. A pressure that isn't a number is an error.
#[test]
@@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() {
json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}),
"a point's pressure must be a number, not \"hard\"",
);
// Also on a point without coordinates, beside one that has them.
refused(
&mut s,
"symbol.adjust",
json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}),
"a point's pressure must be a number, not \"bad\"",
);
}
for key in ["usePressure", "proportional", "affectsDensity"] {
let mut p = json!({"tool": "size", "points": [[200, 150]]});
@@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() {
assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a));
}
/// A set duplicated packs from the density recorded for its source, and a pasted set from the
/// density its source had at Copy: after Cut, after the source is given another density, and in
/// another document.
#[test]
fn a_copied_set_packs_from_the_density_of_its_source() {
for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] {
let mut s = session();
let row: Vec<Value> = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect();
let set =
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.set([set])).unwrap();
let first = match copy {
"duplicate" => "edit.duplicate",
"cut" => "edit.cut",
_ => "edit.copy",
};
s.execute(first, &json!({})).unwrap();
if copy == "changed after copy" {
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap();
}
if copy == "other document" {
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
}
if copy != "duplicate" {
s.execute("edit.paste", &json!({})).unwrap();
}
let copied = s.doc().unwrap().selection.objects.clone();
assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}");
let ids = members(&s, copied[0]);
let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::<Vec<_>>();
let was = xs(&s);
let middle = was.iter().sum::<f64>() / 4.0;
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap();
for (before, after) in was.iter().zip(xs(&s)) {
assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}");
}
}
}
/// 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]
@@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() {
assert!(state(&s) == before);
}
/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen
/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives
/// each instance a share of that amount.
#[test]
fn the_styler_applies_the_style_by_the_brushs_strength() {
let styled = |extra: Value, x: f64| {
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
adjust(&mut s, p);
node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity)
};
let near = |a: f32, b: f32| (a - b).abs() < 1e-6;
assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center");
assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5));
assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge");
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25));
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0));
assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style");
// Random: instances the same distance from the point take different amounts, each from none to
// the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge).
let mut s = session();
let ring: Vec<NodeId> = (0..6)
.map(|i| {
let a = f64::from(i) * std::f64::consts::TAU / 6.0;
dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin())
})
.collect();
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"}));
let amounts: Vec<f32> = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect();
assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}");
assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}");
assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}");
}
/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one
/// at no opacity is passed over and counts as no stain in the mean amount.
#[test]
fn average_spray_passes_over_a_stain_at_no_opacity() {
use vectorcraft_color::{Color, Paint};
let mut s = session();
let set =
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let ids = members(&s, set);
assert_eq!(ids.len(), 2);
s.edit("Stains", |d, _| {
for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] {
let n = d.node_mut(id).unwrap();
n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_)));
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
f.opacity = amount;
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
}
Ok(())
})
.unwrap();
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap();
let new: Vec<NodeId> = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect();
assert_eq!(new.len(), 1);
let f = node(&s, new[0]).appearance.fill().cloned().unwrap();
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity);
}
/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves
/// any other, and counts it.
#[test]
fn the_shifter_moves_an_instance_without_a_size() {
let mut s = session();
let a = dot(&mut s, 200.0, 150.0);
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();
let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10}));
assert_eq!(r["count"], 1);
assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a));
// Average has no mean of such instances to move toward: it leaves them as they are.
let (before, x) = (state(&s), center(&s, a).x);
let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10}));
assert_eq!(r["count"], 0);
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]
@@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() {
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]
fn average_stain_replaces_a_stain_at_no_opacity() {
use vectorcraft_color::{Color, Paint};
let mut s = session();
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0));
s.edit("Stains", |d, _| {
for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] {
let n = d.node_mut(id).unwrap();
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
f.opacity = amount;
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
}
Ok(())
})
.unwrap();
adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10}));
let f = node(&s, a).appearance.fill().cloned().unwrap();
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]
+272
View File
@@ -0,0 +1,272 @@
//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking
//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler
//! keeping their amount while the color or style changes.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_geom::Point;
use crate::*;
/// A document with the 20 pt square symbol "Dot" and nothing selected.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
s
}
/// An instance of Dot centered on (`x`, `y`), not selected.
fn dot(s: &mut Session, x: f64, y: f64) -> NodeId {
let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.clear()).unwrap();
id
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn center(s: &Session, id: NodeId) -> Point {
match node(s, id).kind {
NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO,
other => panic!("not an instance: {other:?}"),
}
}
fn width(s: &Session, id: NodeId) -> f64 {
node(s, id).geometric_bounds().unwrap().width()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn state(s: &Session) -> (Document, usize) {
((*s.doc().unwrap().doc).clone(), undo_len(s))
}
fn adjust(s: &mut Session, p: Value) -> Value {
s.execute("symbol.adjust", &p).unwrap()
}
/// The children of symbol set `set`, in stacking order (the first is at the back).
fn members(s: &Session, set: NodeId) -> Vec<NodeId> {
node(s, set).children().unwrap().iter().map(|c| c.id).collect()
}
/// The instance's fill: its color as RGB and its amount.
fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> {
node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity))
}
/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected.
fn row(s: &mut Session) -> (NodeId, Vec<NodeId>) {
let pts: Vec<Value> = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap());
let ids = members(s, set);
assert_eq!(ids.len(), 4);
(set, ids)
}
/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in
/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas.
#[test]
fn shift_click_with_the_shifter_changes_the_stacking_order() {
let mut s = session();
let (set, ids) = row(&mut s);
let centers: Vec<Point> = ids.iter().map(|id| center(&s, *id)).collect();
let click = |s: &mut Session, x: f64, alt: bool| {
adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone()
};
let steps = undo_len(&s);
assert_eq!(click(&mut s, 120.0, false), 1);
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
assert_eq!(undo_len(&s), steps + 1, "one undo step");
assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::<Vec<_>>(), centers, "nothing moves on the canvas");
assert_eq!(click(&mut s, 120.0, false), 1);
assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]);
// Already in front of the others: nothing changes and no undo step is added.
let before = state(&s);
assert_eq!(click(&mut s, 120.0, false), 0);
assert!(state(&s) == before);
// Alt sends it back one place at a time; at the back it stays.
assert_eq!(click(&mut s, 120.0, true), 1);
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
click(&mut s, 120.0, true);
click(&mut s, 120.0, true);
assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]);
assert_eq!(click(&mut s, 120.0, true), 0);
// Two instances under the brush move together past the next one.
s.execute("edit.undo", &json!({})).unwrap();
let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true}));
assert_eq!(both["count"], 2);
assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]);
// Without Shift a drag moves the instances, as before.
adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10}));
assert!(center(&s, ids[3]).x > centers[3].x);
}
/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even
/// with Resizing Affects Density.
#[test]
fn shift_with_the_sizer_keeps_the_density() {
let at = |affects: bool, shift: bool| {
let mut s = session();
let a = dot(&mut s, 220.0, 150.0);
adjust(
&mut s,
json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}),
);
(center(&s, a), width(&s, a))
};
let (moved, _) = at(true, false);
assert!(moved.x > 220.5, "{moved:?}");
let (kept, grown) = at(true, true);
assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}");
// It resizes as the Sizer does with Resizing Affects Density off.
assert_eq!(at(false, false), (kept, grown));
assert_eq!(at(false, true), (kept, grown));
}
/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill
/// color; an instance without a stain is left as it is.
#[test]
fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() {
let mut s = session();
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
let (red, amount) = fill(&s, a).unwrap();
assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}");
// A second fill below the stain, which Shift leaves as it is.
s.edit("Add fill", |d, _| {
let n = d.node_mut(a).unwrap();
let lower = n.appearance.fill().unwrap().clone();
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower }));
Ok(())
})
.unwrap();
let lower = node(&s, a).appearance.items[0].clone();
let stain = |s: &mut Session, x: f64| {
adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true}))
};
assert_eq!(stain(&mut s, 100.0)["count"], 1);
let (color, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount, "the amount stays");
assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}");
assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays");
// More strokes go on toward blue, with the amount still the same.
for _ in 0..30 {
stain(&mut s, 100.0);
}
let (bluer, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount);
assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}");
// Alt has no effect with Shift.
let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true});
adjust(&mut s, green.clone());
let plain = fill(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
let mut with_alt = green;
with_alt["alt"] = json!(true);
adjust(&mut s, with_alt);
assert_eq!(fill(&s, a), plain);
// No stain on b: nothing changes and no undo step is added.
let before = state(&s);
assert_eq!(stain(&mut s, 300.0)["count"], 0);
assert!(state(&s) == before && fill(&s, b).is_none());
}
/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its
/// fill toward the selected style's fill.
#[test]
fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() {
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
// A red stain at part strength.
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
let (red, amount) = fill(&s, a).unwrap();
assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}");
// Half the brush's strength at a point 2.5 pt from the instance: half way to blue.
adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
let (mixed, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount);
assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}");
// At the brush's center with full intensity it takes the style's fill.
adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
let (blue, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount);
assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}");
}
/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes
/// the new paint at once, at any strength, and keeps its amount.
#[test]
fn shift_changes_a_paint_that_has_no_form_in_between() {
use vectorcraft_color::Paint;
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
s.edit("Pattern fill", |d, _| {
let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() });
f.opacity = 0.4;
d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
Ok(())
})
.unwrap();
// Low intensity, near the brush's edge: far below half strength.
let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true}));
assert_eq!(r["count"], 1);
let f = node(&s, a).appearance.fill().cloned().unwrap();
assert_eq!(f.opacity, 0.4, "the amount stays");
assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint);
}
/// A style name the document has no style for (the Styler's style from another document, or one
/// since renamed or deleted) moves the fill toward the document's first style after the default
/// one, as no name does, and the stain's amount stays.
#[test]
fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() {
use vectorcraft_color::{Color, Paint};
let styled = |style: Option<&str>| {
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true});
if let Some(n) = style {
p["style"] = json!(n);
}
let stained = node(&s, a).appearance.fill().map(|f| f.opacity);
adjust(&mut s, p);
let f = node(&s, a).appearance.fill().cloned().unwrap();
assert_eq!(Some(f.opacity), stained, "the amount stays");
let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint();
(f.paint, first)
};
let (missing, first) = styled(Some("No Such Style"));
let (none, _) = styled(None);
assert_eq!(missing, none);
// The paint is the first style's, not the active fill color.
assert_eq!(none, first);
assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
}
/// A `shift` that is not true, false or null is refused and changes nothing.
#[test]
fn a_bad_shift_is_refused() {
let mut s = session();
dot(&mut s, 100.0, 150.0);
for tool in ["shift", "size", "stain", "style"] {
let before = state(&s);
let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}");
assert!(state(&s) == before);
}
}
+400
View File
@@ -754,6 +754,406 @@ fn distort_perspective_midpoint_is_projective() {
assert!((c.y - 100.0 / 6.0).abs() < 1e-3, "{c:?}");
}
/// A 2 × 2 px image placed at (0, 0)–(100, 100), selected.
fn placed_image(s: &mut Session) -> NodeId {
s.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![]));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 2,
height: 2,
xf: vectorcraft_geom::Affine::scale(50.0),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap()
}
fn corners(s: &Session, id: NodeId) -> [Point; 4] {
s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap()
}
fn assert_corners(got: [Point; 4], want: [(f64, f64); 4]) {
for (g, (x, y)) in got.iter().zip(want) {
assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?} against {want:?}");
}
}
/// Perspective Distort and Free Distort put an image's corners exactly on the handles, in one
/// undo step; the image is bounded and clicked by its corners, and a move takes them along.
#[test]
fn distort_puts_an_images_corners_on_the_handles() {
for want in [[(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)], [(10.0, 5.0), (90.0, 0.0), (120.0, 110.0), (0.0, 100.0)]] {
let mut s = session();
let img = placed_image(&mut s);
let undo = undo_len(&s);
let corners_json: Vec<[f64; 2]> = want.iter().map(|(x, y)| [*x, *y]).collect();
s.execute("object.distort", &json!({ "corners": corners_json })).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert_corners(corners(&s, img), want);
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
let b = bounds(&s, img);
let xs = want.map(|c| c.0);
let ys = want.map(|c| c.1);
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
assert!(near(b.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(b.x1, xs.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
assert!(near(b.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(b.y1, ys.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
assert_corners(corners(&s, img), want.map(|(x, y)| (x + 10.0, y + 20.0)));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
}
// Clicks: inside the trapezoid hits the image; inside its old square but outside the
// trapezoid does not.
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let doc = &s.doc().unwrap().doc;
let opt = vectorcraft_doc::hit::HitOptions::default();
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(50.0, 50.0), opt).map(|h| h.leaf), Some(img));
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(5.0, 10.0), opt).map(|h| h.leaf), None);
}
/// Distorted together with a path, the image's corners and the path's anchors follow one warp.
#[test]
fn distort_moves_an_image_and_a_path_as_one() {
let mut s = session();
let img = placed_image(&mut s);
let path = rect(&mut s, 100.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [200, 100], [50, 100]]})).unwrap();
let d = &s.doc().unwrap().doc;
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
let q = corners(&s, img);
// The image's right edge and the path's left edge were one line, and stay one where the warp
// moves it.
assert!(q[2].distance(Point::new(100.0, 100.0)) > 1.0, "{q:?}");
for p in [q[1], q[2]] {
assert!(anchors.iter().any(|a| a.distance(p) < 1e-9), "{p:?} not in {anchors:?}");
}
}
/// Corners that would fold an image over are refused: nothing changes and no undo step is kept.
/// A distorted image keeps its distortion where commands that cannot keep it are asked to work.
#[test]
fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
let mut s = session();
let img = placed_image(&mut s);
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [0, 100], [100, 100]]})).unwrap_err().to_string();
assert!(e.contains("convex"), "{e}");
assert_eq!(undo_len(&s), undo);
assert_eq!(s.doc().unwrap().doc, before);
// Three corners on one line give no perspective map at all.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [100, 50], [0, 100]]})).unwrap_err().to_string();
assert!(e.contains("convex"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
// A convex shape too small for a perspective map: the corners could not reach the handles.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1e-7, 0], [8e-8, 1e-7], [0, 1e-7]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
// The same shape far from the origin: its distance from it does not hide the missed corner.
let x = 1_000_000.0;
let e = s.execute("object.distort", &json!({"corners": [[x, 0], [x + 1e-7, 0], [x + 8e-8, 1e-7], [x, 1e-7]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
// A long, thin shape with one side all but gone.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1_000_000, 0], [1_000_000, 1e-19], [0, 1]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
// A small shape near the edge of the canvas is still distorted.
let o = vectorcraft_doc::MAX_COORD - 2.0;
let far = [[o, o], [o + 1.0, o], [o + 0.2130712, o + 1.0], [o, o + 1.0]];
s.execute("object.distort", &json!({ "from": [0, 0, 100, 100], "corners": far })).unwrap();
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(undo_len(&s), undo);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
for (cmd, params) in [
("object.cropImage", json!({})),
("imageTrace.make", json!({})),
("links.relink", json!({"path": "/nowhere/pic.png"})),
// Refused before the folder is searched, so a file missing there does not hide it.
("links.relink", json!({"folder": "/nowhere"})),
("links.embed", json!({"ids": [img.0]})),
("links.unembed", json!({})),
// Refused before any file is written.
("links.unembed", json!({"folder": "/nowhere"})),
("object.createObjectMosaic", json!({})),
("object.mesh.create", json!({})),
(
"file.place",
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
// Every command gives the one shared refusal, which the complete-message catalogs translate.
assert!(e.contains("is an image changed by Perspective Distort or Free Distort, which this command does not work on"), "{cmd}: {e}");
}
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
assert_eq!(undo_len(&s), undo + 1);
// Type replaces a distorted image by its bounds, which the corners give: not refused.
let text = json!({"replace": true, "name": "note.txt", "dataBase64": vectorcraft_format::base64_encode(b"Hello")});
let out = s.execute("file.place", &text).unwrap();
let id = NodeId(out["ids"][0].as_u64().unwrap());
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Text(_)));
}
/// Create Gradient Mesh on a path and a distorted image converts the path and names the image it
/// left as it is, with the shared refusal.
#[test]
fn mesh_create_reports_the_distorted_image_it_skips() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let path = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
let out = s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}");
let skipped = out["skipped"].as_array().expect("the skipped image");
assert_eq!(skipped.len(), 1, "{out}");
assert_eq!(skipped[0]["id"], json!(img.0));
assert!(skipped[0]["reason"].as_str().unwrap().contains("Perspective Distort or Free Distort"), "{out}");
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
// Without a distorted image, no `skipped`.
let other = rect(&mut s, 400.0, 0.0, 100.0, 100.0);
let out = s.execute("object.mesh.create", &json!({"ids": [other.0], "rows": 1, "cols": 1})).unwrap();
assert!(out.get("skipped").is_none(), "{out}");
}
/// A blend takes the warp's affine approximation whole, so an image inside it does not stop a
/// distort whose corners an image could not follow.
#[test]
fn distort_of_a_blend_holding_an_image_is_not_refused() {
let mut s = session();
let img = placed_image(&mut s);
let r = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
let out = s.execute("object.blend.make", &json!({"ids": [img.0, r.0]})).unwrap();
let blend = NodeId(out["id"].as_u64().unwrap());
let undo = undo_len(&s);
s.execute("object.distort", &json!({"ids": [blend.0], "corners": [[0, 0], [300, 0], [100, 50], [0, 100]]})).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
}
/// The Control bar's Mask clips a distorted image to the shape between its corners.
#[test]
fn mask_on_a_distorted_image_follows_its_corners() {
let mut s = session();
let img = placed_image(&mut s);
let want = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let out = s.execute("object.maskImage", &json!({})).unwrap();
let path = NodeId(out["path"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
assert_eq!(anchors.len(), 4, "{anchors:?}");
for (x, y) in want {
assert!(anchors.iter().any(|a| a.distance(Point::new(x, y)) < 1e-9), "{x},{y} not in {anchors:?}");
}
assert!(d.node(img).unwrap().is_distorted_image());
}
/// A Transform effect moves a distorted image's corners with it: expanded, the image stands
/// where the effect drew it.
#[test]
fn a_transform_effect_moves_a_distorted_images_corners() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let mut found = vec![];
for layer in &s.doc().unwrap().doc.layers {
layer.walk(&mut |n| {
if let Some(q) = n.image_corners() {
found.push(q);
}
});
}
let want = [(240.0, 0.0), (260.0, 0.0), (300.0, 100.0), (200.0, 100.0)];
assert!(found.iter().any(|q| q.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-6)), "{found:?}");
}
/// A Transform effect after a Warp effect moves a distorted image's warped pixels once: the art
/// stands where the Warp alone draws it, moved by the Transform.
#[test]
fn a_transform_after_a_warp_moves_a_distorted_image_once() {
let expanded_bounds = |transform: bool| {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "warp.bulge", "params": {"bend": 50}})).unwrap();
if transform {
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
}
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let mut images = None;
for layer in &s.doc().unwrap().doc.layers {
layer.walk(&mut |n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
let r = im.xf.transform_rect_bbox(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)));
images = Some(images.map_or(r, |b: vectorcraft_geom::Rect| b.union(r)));
}
});
}
images.expect("the warped pieces")
};
let (alone, moved) = (expanded_bounds(false), expanded_bounds(true));
assert!((moved.x0 - alone.x0 - 200.0).abs() < 1e-6 && (moved.x1 - alone.x1 - 200.0).abs() < 1e-6, "{alone:?} {moved:?}");
assert!((moved.y0 - alone.y0).abs() < 1e-6 && (moved.y1 - alone.y1).abs() < 1e-6, "{alone:?} {moved:?}");
}
/// A raster effect's baked pixels already show the distortion: the image that replaces a
/// distorted one is placed by its own transform.
#[test]
fn baked_raster_effect_pixels_replace_a_distortion() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let v = s.doc().unwrap().doc.node(img).unwrap().clone();
let baked = Node::new(NodeId(99), v.kind.clone());
let out = crate::cmd::rasterfx::replace_with_image(v, baked);
assert!(!out.is_distorted_image());
assert!(out.extras().image_quad.is_none());
}
/// A distorted image is saved with its corners and reads back the same.
#[test]
fn a_distorted_image_saves_and_reads_back() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let doc = &s.doc().unwrap().doc;
let bytes = vectorcraft_format::save(doc, false);
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(img).unwrap().image_corners(), doc.node(img).unwrap().image_corners());
assert!(back.node(img).unwrap().is_distorted_image());
assert!(String::from_utf8_lossy(&bytes).contains("image_quad"));
// An image without a distortion is saved without the field, and opens as it was.
let mut plain = session();
let img = placed_image(&mut plain);
let doc = &plain.doc().unwrap().doc;
let bytes = vectorcraft_format::save(doc, false);
assert!(!String::from_utf8_lossy(&bytes).contains("image_quad"));
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(img), doc.node(img));
// Corners in a file that fold the image over leave it placed by its transform.
let mut bad = (**doc).clone();
bad.node_mut(img).unwrap().extras_mut().image_quad =
Some(Box::new([(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)].map(|(x, y)| Point::new(x, y))));
let back = vectorcraft_format::load(&vectorcraft_format::save(&bad, false)).unwrap();
assert!(!back.node(img).unwrap().is_distorted_image());
assert_corners(back.node(img).unwrap().image_corners().unwrap(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
}
/// A distort whose corners cross the warp's horizon at the image is refused with that reason, and
/// a distort that leaves a distorted image where it is records nothing.
#[test]
fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing() {
let mut s = session();
let img = placed_image(&mut s);
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
// The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
// y = 15, inside the image.
let e = s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
assert!(e.contains("horizon"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let b = bounds(&s, img);
let at = [[b.x0, b.y0], [b.x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]];
s.execute("object.distort", &json!({ "from": [b.x0, b.y0, b.x1, b.y1], "corners": at })).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
}
/// Image info gives a distorted image's resolution at its middle, not the resolution it had
/// before the distort.
#[test]
fn image_info_measures_a_distorted_image_at_its_middle() {
let mut s = session();
placed_image(&mut s);
// 2 pixels across 100 pt: 1.44 ppi.
let ppi = |s: &mut Session| {
let out = s.execute("image.info", &json!({})).unwrap();
[out["ppi"][0].as_f64().unwrap(), out["ppi"][1].as_f64().unwrap()]
};
assert!((ppi(&mut s)[0] - 1.44).abs() < 1e-9);
// The top squeezed to half the width: the middle of the pixels spans less than 100 pt across,
// so the resolution across there is higher.
s.execute("object.distort", &json!({ "corners": [[25, 0], [75, 0], [100, 100], [0, 100]] })).unwrap();
let [x, _] = ppi(&mut s);
assert!(x > 1.44 * 1.1, "{x}");
}
/// Rasterize draws a distorted image's pixels between its corners, and the image it makes is a
/// plain one.
#[test]
fn rasterize_draws_a_distorted_image_between_its_corners() {
let mut s = session();
let img = placed_image(&mut s);
let mut png = std::io::Cursor::new(vec![]);
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();
s.edit("Pixels", |d, _| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png.into_inner()));
Ok(())
})
.unwrap();
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("select.set", &json!({ "ids": [img.0] })).unwrap();
let out = s.execute("object.rasterize", &json!({ "ppi": 72, "background": "transparent", "addAround": 0 })).unwrap();
let d = &s.doc().unwrap().doc;
let id = NodeId(out["id"].as_u64().unwrap());
let n = d.node(id).unwrap();
assert!(!n.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &n.kind else { panic!("an image") };
// The raster covers the corners' bounds.
let b = n.geometric_bounds().unwrap();
assert!([b.x0, b.y0, b.x1 - 100.0, b.y1 - 100.0].iter().all(|v| v.abs() <= 1.0), "{b:?}");
let px = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
let (w, h) = px.dimensions();
let rgba = px.to_rgba8();
let alpha = |x: f64, y: f64| {
let p = im.xf.inverse() * Point::new(x, y);
assert!(p.x >= 0.0 && p.y >= 0.0 && p.x < f64::from(w) && p.y < f64::from(h), "({x}, {y}) is outside the raster: {p:?}");
let (i, j) = (p.x as u32, p.y as u32);
rgba[((j * w + i) * 4 + 3) as usize]
};
assert_eq!(alpha(50.0, 90.0), 255, "inside the corners");
assert_eq!(alpha(10.0, 10.0), 0, "inside the old rectangle, outside the corners");
}
/// A Free Transform drag in Free Distort mode on an image puts the dragged corner where the drag
/// ends, in one undo step, also when a position on the way would have folded the image.
#[test]
fn free_transform_distort_drag_on_an_image_is_one_undo_step() {
let mut s = session();
let img = placed_image(&mut s);
let undo = undo_len(&s);
let v = ViewInfo::default();
s.select_tool("freeTransform", v).unwrap();
s.set_tool_option("mode", &json!("distort"));
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
// Past the top left corner: the image would fold over.
s.pointer(&PointerEvent::new(PointerKind::Drag, -50.0, -50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 120.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 120.0), v).unwrap();
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (130.0, 120.0), (0.0, 100.0)]);
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
assert_eq!(undo_len(&s), undo + 1);
}
#[test]
fn free_transform_distort_mode_via_pointer() {
let mut s = session();