Merge main into fix/smooth-keeps-closed-start

This commit is contained in:
dotCooCoo
2026-11-13 13:43:28 -08:00
205 changed files with 12742 additions and 672 deletions
+222 -1
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Node, OrientedBox};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_tools::bbox::Handle;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
@@ -190,6 +190,227 @@ fn free_transform_distort_starts_from_the_turned_box() {
}
}
/// Where the line through `a` and `b` crosses the line through `c` and `d`.
fn cross(a: Point, b: Point, c: Point, d: Point) -> Point {
let (r, q) = (b - a, d - c);
let t = ((c - a).x * q.y - (c - a).y * q.x) / (r.x * q.y - r.y * q.x);
a + r * t
}
/// The counter-clockwise angle of the direction from `from` to `to`.
fn direction(from: Point, to: Point) -> f64 {
-(to.y - from.y).atan2(to.x - from.x).to_degrees()
}
fn near_deg(a: f64, b: f64) -> bool {
vectorcraft_geom::normalize_deg(a - b).abs() < 1e-6
}
fn json_points(pts: [Point; 4]) -> Value {
json!(pts.map(|p| [p.x, p.y]))
}
/// `pts` turned by `deg` (counter-clockwise) about `c`.
fn turned(pts: [Point; 4], c: Point, deg: f64) -> [Point; 4] {
let a = Affine::translate(c.to_vec2()) * Affine::rotate(-deg.to_radians()) * Affine::translate(-c.to_vec2());
pts.map(|p| a * p)
}
/// A perspective quad for the 100 × 100 box at the origin: its top-right corner raised 20 pt.
const RAISED: [(f64, f64); 4] = [(0.0, 0.0), (100.0, -20.0), (100.0, 100.0), (0.0, 100.0)];
fn raised() -> [Point; 4] {
RAISED.map(|(x, y)| Point::new(x, y))
}
/// The angle a warp onto `quad` (from a box square to the page) turns an upright object's x axis
/// to, where the object's center lands at `center`: every horizontal line of the box is drawn
/// through the point where the lines of the quad's top and bottom sides cross.
fn upright_angle_after(quad: [Point; 4], center: Point) -> f64 {
direction(cross(quad[0], quad[1], quad[3], quad[2]), center)
}
/// Where a warped rectangle's center lands: where the diagonals of its warped corners cross.
fn warped_center(s: &Session, id: NodeId) -> Point {
let p = anchors(s, id);
assert_eq!(p.len(), 4, "{p:?}");
cross(p[0], p[2], p[1], p[3])
}
#[test]
fn distort_turns_an_upright_box_with_the_warp_at_its_center() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a]);
let quad = raised();
s.execute("object.distort", &json!({ "corners": json_points(quad) })).unwrap();
// The top tilts up to the right: a small counter-clockwise angle (atan 0.1 for this quad).
let want = upright_angle_after(quad, cross(quad[0], quad[2], quad[1], quad[3]));
assert!(near(want, 0.1_f64.atan().to_degrees()), "{want}");
assert!(near(angle(&s, a), want), "{} vs {want}", angle(&s, a));
// The Selection and Free Transform tools' box stands at it.
assert!(near(selection_box(&s).angle, want), "{:?}", selection_box(&s));
// Reset Bounding Box squares it to the page and leaves the art.
let pts = anchors(&s, a);
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
assert_eq!(angle(&s, a), 0.0);
assert_eq!(anchors(&s, a), pts);
// A warp that only stretches a turned object along its own axes keeps its angle exactly.
let mut s = session();
let t = turned_rect(&mut s);
let b = selection_box(&s);
let wide = OrientedBox { angle: b.angle, rect: Rect::new(b.rect.x0, b.rect.y0, b.rect.x1 + 50.0, b.rect.y1) };
let r = b.rect;
s.execute("object.distort", &json!({"corners": json_points(wide.corners()), "from": [r.x0, r.y0, r.x1, r.y1], "angle": b.angle})).unwrap();
assert_eq!(angle(&s, t), b.angle);
assert!(near(selection_box(&s).rect.width(), 150.0), "{:?}", selection_box(&s));
}
/// Every object's angle in `n`'s subtree, opacity mask art included, each with whether it is the
/// art of an unlinked mask (or inside one).
fn angles_with_links(n: &Node, unlinked: bool, out: &mut Vec<(f64, bool)>) {
out.push((n.bbox_angle, unlinked));
for c in n.children().into_iter().flatten() {
angles_with_links(c, unlinked, out);
}
if let Some(m) = &n.extras().mask {
angles_with_links(&m.art, unlinked || !m.linked, out);
}
}
fn group_angles(s: &Session, g: NodeId) -> Vec<(f64, bool)> {
let mut out = vec![];
angles_with_links(s.doc().unwrap().doc.node(g).unwrap(), false, &mut out);
out
}
fn selected(s: &Session) -> NodeId {
s.doc().unwrap().selection.objects[0]
}
#[test]
fn distort_turns_each_member_and_linked_mask_by_its_own_warp() {
let mut s = session();
// A path turned 20° with a linked mask turned with it.
let a = rect(&mut s, 100.0, 100.0, 60.0, 40.0);
let am = rect(&mut s, 100.0, 100.0, 60.0, 40.0);
sel(&mut s, &[a, am]);
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
// A path with an unlinked mask.
let u = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
let um = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
sel(&mut s, &[u, um]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
// A compound path turned 10°.
let c1 = rect(&mut s, 100.0, 200.0, 40.0, 40.0);
let c2 = rect(&mut s, 120.0, 220.0, 40.0, 40.0);
sel(&mut s, &[c1, c2]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = selected(&s);
s.execute("object.rotate", &json!({"angle": 10})).unwrap();
// A clip group.
let k1 = rect(&mut s, 250.0, 200.0, 50.0, 50.0);
let k2 = rect(&mut s, 260.0, 210.0, 50.0, 50.0);
sel(&mut s, &[k1, k2]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let clip = selected(&s);
sel(&mut s, &[a, u, compound, clip]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let before = group_angles(&s, g);
assert!(before.len() >= 10 && before.iter().any(|(a, _)| near(*a, 20.0)) && before.iter().any(|(_, u)| *u), "{before:?}");
// A warp that turns the group 30° about its center turns every object 30° more, except the
// art of the unlinked mask, which stays.
let b = s.doc().unwrap().doc.bounds_of(&[g], false).unwrap();
let n = undo_len(&s);
s.execute("object.distort", &json!({ "corners": json_points(turned(OrientedBox::aligned(b).corners(), b.center(), 30.0)) })).unwrap();
assert_eq!(undo_len(&s), n + 1, "one step");
let after = group_angles(&s, g);
assert_eq!(after.len(), before.len());
for ((old, unlinked), (new, _)) in before.iter().zip(&after) {
if *unlinked {
assert_eq!(new, old, "{before:?} → {after:?}");
} else {
assert!(near_deg(*new, old + 30.0), "{before:?} → {after:?}");
}
}
// Under a perspective warp each object follows the warp at its own center: two members of a
// group, one above the other, tilt by different amounts, and the group by the warp at its own
// center.
let mut s = session();
let p = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
let q = rect(&mut s, 0.0, 50.0, 100.0, 50.0);
sel(&mut s, &[p, q]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let quad = raised();
s.execute("object.distort", &json!({ "corners": json_points(quad) })).unwrap();
let (want_p, want_q) = (upright_angle_after(quad, warped_center(&s, p)), upright_angle_after(quad, warped_center(&s, q)));
assert!(near(angle(&s, p), want_p) && near(angle(&s, q), want_q), "{} {} vs {want_p} {want_q}", angle(&s, p), angle(&s, q));
assert!(want_p > want_q + 1.0, "{want_p} {want_q}");
let want_g = upright_angle_after(quad, cross(quad[0], quad[2], quad[1], quad[3]));
assert!(near(angle(&s, g), want_g), "{} vs {want_g}", angle(&s, g));
}
#[test]
fn mirrored_and_collapsing_distorts_keep_valid_angles() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
sel(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
// Corners swapped left for right mirror the art: the box stands at the mirrored angle.
let b = s.doc().unwrap().doc.bounds_of(&[a], false).unwrap();
let [tl, tr, br, bl] = OrientedBox::aligned(b).corners();
s.execute("object.distort", &json!({ "corners": json_points([tr, tl, bl, br]) })).unwrap();
assert!(near(angle(&s, a), -30.0), "{}", angle(&s, a));
// A warp that collapses the art to a point leaves the angle as it was.
let n = undo_len(&s);
let c = b.center();
match s.execute("object.distort", &json!({ "corners": json_points([c; 4]) })) {
Ok(_) => assert!(near(angle(&s, a), -30.0), "{}", angle(&s, a)),
Err(_) => {
assert_eq!(undo_len(&s), n);
assert!(near(angle(&s, a), -30.0));
}
}
}
#[test]
fn distort_angles_undo_redo_and_reopen_together() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a]);
let before = anchors(&s, a);
let n = undo_len(&s);
let b = Rect::new(0.0, 0.0, 100.0, 100.0);
s.execute("object.distort", &json!({ "corners": json_points(turned(OrientedBox::aligned(b).corners(), b.center(), 30.0)) })).unwrap();
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Free Distort"));
assert!(near(angle(&s, a), 30.0), "{}", angle(&s, a));
let warped = anchors(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((anchors(&s, a), angle(&s, a)), (before, 0.0));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(anchors(&s, a), warped);
assert!(near(angle(&s, a), 30.0));
// A native file keeps the angle.
let data = s.execute("document.save", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "warped.vectorcraft", "dataBase64": data})).unwrap();
assert!(near(angle(&s, a), 30.0));
sel(&mut s, &[a]);
let b = selection_box(&s);
assert!(near(b.angle, 30.0) && near(b.rect.width(), 100.0) && near(b.rect.height(), 100.0), "{b:?}");
// The next handle drag scales along the turned box: the Right handle 50 pt further out.
let right = b.to_doc() * Handle::Right.pos(b.rect);
let to = b.to_doc() * (Handle::Right.pos(b.rect) + vectorcraft_geom::Vec2::new(50.0, 0.0));
s.select_tool("selection", ViewInfo::default()).unwrap();
drag_with(&mut s, &[right, to, to], Mods::default());
let nb = selection_box(&s);
assert!(near(nb.angle, 30.0) && near(nb.rect.width(), 150.0) && near(nb.rect.height(), 100.0), "{nb:?}");
}
#[test]
fn transform_panel_sizes_follow_the_turned_box() {
let mut s = session();
+21
View File
@@ -721,3 +721,24 @@ fn other_documents_brushes_load_and_unreadable_files_are_errors() {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(vectorcraft_brush::library(&vectorcraft_format::load(&bytes).unwrap()).len(), 1);
}
/// A library file whose brushes repeat a name loads with the later brush numbered, and each one
/// can be added to a document by its own name.
#[test]
fn a_library_file_that_repeats_a_brush_name_loads_with_the_later_one_numbered() {
use vectorcraft_brush::{Brush, Calligraphic};
let nib = |size: f64| Brush { name: "Nib".into(), kind: BrushKind::Calligraphic(Calligraphic { size, ..Default::default() }) };
let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
vectorcraft_brush::store(&mut file, &[nib(1.0), nib(2.0)]);
let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
let mut s = session();
let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Nibs.vectorcraft"}));
let library = r["library"].as_str().unwrap().to_string();
let listed = run(&mut s, "brush.library", json!({ "library": library }));
let names: Vec<&str> = listed["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Nib", "Nib 2"]);
let r = run(&mut s, "brush.addFromLibrary", json!({"library": library, "name": "Nib 2"}));
assert_eq!(strs(&r["added"]), ["Nib 2"]);
let size = |b: Brush| if let BrushKind::Calligraphic(c) = b.kind { c.size } else { 0.0 };
assert_eq!(size(brush(&s, "Nib 2")), 2.0);
}
+31
View File
@@ -631,6 +631,37 @@ fn brush_options_rename_duplicate_and_delete_update_strokes() {
assert!(s.execute("brush.delete", &json!({"name": "5 pt. Round"})).is_err());
}
/// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name
/// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone.
#[test]
fn a_repeated_brush_name_is_numbered_when_the_document_opens() {
use vectorcraft_brush::{Brush, BrushKind, Calligraphic};
let nib = |size: f64| Brush { name: "Nib".into(), kind: BrushKind::Calligraphic(Calligraphic { size, ..Default::default() }) };
let mut s = session();
vectorcraft_brush::store(std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc), &[nib(1.0), nib(2.0)]);
let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
s.execute("brush.apply", &json!({"name": "Nib", "ids": [a.0]})).unwrap();
let saved = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].clone();
let mut o = Session::new();
o.execute("document.open", &json!({"name": "a.vectorcraft", "dataBase64": saved})).unwrap();
let names = |o: &mut Session| -> Vec<String> {
let list = o.execute("brush.list", &json!({})).unwrap();
list["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap().to_string()).collect()
};
assert_eq!(names(&mut o), ["Nib", "Nib 2"]);
assert_eq!(brush_of(&o, a).as_deref(), Some("Nib"));
assert_eq!(o.execute("brush.get", &json!({"name": "Nib"})).unwrap()["size"], json!(1.0));
assert_eq!(o.execute("brush.get", &json!({"name": "Nib 2"})).unwrap()["size"], json!(2.0));
let b = rect(&mut o, 80.0, 10.0, 50.0, 50.0);
o.execute("brush.apply", &json!({"name": "Nib 2", "ids": [b.0]})).unwrap();
o.execute("brush.options", &json!({"name": "Nib", "newName": "Pen"})).unwrap();
assert_eq!(names(&mut o), ["Pen", "Nib 2"]);
assert_eq!((brush_of(&o, a).as_deref(), brush_of(&o, b).as_deref()), (Some("Pen"), Some("Nib 2")));
o.execute("brush.delete", &json!({"name": "Nib 2"})).unwrap();
assert_eq!(names(&mut o), ["Pen"]);
assert_eq!((brush_of(&o, a).as_deref(), brush_of(&o, b)), (Some("Pen"), None));
}
/// `brush.move`, which the Brushes panel runs when a brush is dragged, reorders brushes among those of
/// their type in one undo step and refuses to move one into another type.
#[test]
+6 -3
View File
@@ -4134,7 +4134,10 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
sorted.sort();
assert_eq!(sorted, ["#000000", "#c82832", "#f0f0dc"], "{method}");
let n = node(&s, g);
assert_eq!(names(&n), order, "{method}");
// Overlapping fills the ring whole and draws the field inside it above the ring: that path starts a second
// group of the field's color, above the black one.
let want: Vec<String> = if method == "overlapping" { order.iter().chain(order.first()).cloned().collect() } else { order.clone() };
assert_eq!(names(&n), want, "{method}");
// Each group holds its color's paths, and in turn they are the paths of the trace without
// byColor, in their order.
let groups = n.children().unwrap();
@@ -4148,8 +4151,8 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
// Release to Layers: a sublayer for each color, in the same order.
let r = s.execute("layer.releaseToLayers", &json!({"id": g.0})).unwrap();
let subs = ids(&r);
assert_eq!(subs.len(), 3, "{method}");
for (sub, name) in subs.iter().zip(&order) {
assert_eq!(subs.len(), want.len(), "{method}");
for (sub, name) in subs.iter().zip(&want) {
let l = node(&s, *sub);
assert!(matches!(l.kind, NodeKind::Layer { .. }), "{method}");
assert_eq!(names(&l), std::slice::from_ref(name), "{method}");
+204
View File
@@ -1697,6 +1697,210 @@ fn smoothing_a_closed_path_away_from_its_first_anchor_keeps_it_first() {
assert_eq!(after.subpaths[0].anchors[0], before.subpaths[0].anchors[0]);
}
/// `path.smoothRegion` along `drag` with the Smooth tool's reach and default Fidelity → the ids changed.
fn smooth_pass_ids(s: &mut Session, drag: &[Point]) -> serde_json::Value {
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap()["ids"].clone()
}
/// The corner, in degrees, at each anchor between two segments of `p`'s first open subpath.
fn smooth_test_kinks(p: &PathData) -> Vec<f64> {
let sp = &p.subpaths[0];
(1..sp.segment_count())
.map(|i| {
let (a, b) = (sp.segment(i - 1), sp.segment(i));
let tin = if a.p3.distance(a.p2) > 1e-9 { a.p3 - a.p2 } else { a.p3 - a.p1 };
let tout = if b.p1.distance(b.p0) > 1e-9 { b.p1 - b.p0 } else { b.p2 - b.p0 };
tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees()
})
.collect()
}
/// A 200 pt segment rising to a sharp peak at (200, 125) in its middle, then a 100 pt line:
/// (100, 200) to (300, 200) to (400, 200).
fn long_peak_segment(s: &mut Session) -> NodeId {
let anchors = [
json!({"x": 100.0, "y": 200.0, "out": [200.0, 100.0]}),
json!({"x": 300.0, "y": 200.0, "in": [200.0, 100.0]}),
json!({"x": 400.0, "y": 200.0}),
];
smooth_test_path(s, &anchors, false)
}
/// The sharpest bend of `p` between x = 180 and 220: the most it turns, in radians per point, over
/// points about half a point apart.
fn sharpest_bend_near_200(p: &PathData) -> f64 {
use kurbo::ParamCurve;
let sp = &p.subpaths[0];
let pts: Vec<Point> = (0..sp.segment_count()).flat_map(|i| (0..=800).map(move |k| sp.segment(i).eval(f64::from(k) / 800.0))).collect();
pts.windows(3)
.filter(|w| (180.0..=220.0).contains(&w[1].x))
.map(|w| (w[1] - w[0], w[2] - w[1]))
.filter(|(u, v)| u.hypot() > 1e-6 && v.hypot() > 1e-6)
.map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs() / (0.5 * (u.hypot() + v.hypot())))
.fold(0.0, f64::max)
}
/// A drag along the middle of a long segment smooths the stretch under it although both of the
/// segment's anchors are out of reach; the rest of the segment and the line after it keep their shape.
#[test]
fn a_smooth_drag_along_a_segment_smooths_it_with_its_anchors_out_of_reach() {
use kurbo::ParamCurve;
let mut s = session();
let id = long_peak_segment(&mut s);
let before = path(&s, id);
let drag = smooth_drag_along(126.0, 185.0, 215.0);
assert_eq!(smooth_pass_ids(&mut s, &drag), json!([id.0]));
let after = path(&s, id);
let (b0, b1) = (sharpest_bend_near_200(&before), sharpest_bend_near_200(&after));
assert!(b1 < 0.97 * b0, "the peak's sharpest bend {b0} -> {b1}");
let kinks = smooth_test_kinks(&after);
// The anchors where the reach was cut join smoothly; the corner before the line stays.
assert!(kinks[..kinks.len() - 1].iter().all(|k| *k < 0.5), "{kinks:?}");
let a = &after.subpaths[0].anchors;
assert_eq!((a[0].p, a[0].h_out.y < 200.0), (Point::new(100.0, 200.0), true), "the first anchor keeps its place: {:?}", a[0]);
let (end, last) = (a[a.len() - 2], a[a.len() - 1]);
assert!(end.p == Point::new(300.0, 200.0) && !end.has_out(), "the segment's end keeps its place: {end:?}");
assert_eq!(last, before.subpaths[0].anchors[2], "and the line after it stays");
// Every point of the segment farther than the reach from the drag is still on the path.
let seg = before.subpaths[0].segment(0);
let sp = &after.subpaths[0];
let on_after: Vec<Point> = (0..sp.segment_count()).flat_map(|i| (0..=400).map(move |k| sp.segment(i).eval(f64::from(k) / 400.0))).collect();
let off_drag = |q: Point| {
drag.windows(2)
.map(|w| {
let ab = w[1] - w[0];
(w[0] + ab * ((q - w[0]).dot(ab) / ab.hypot2()).clamp(0.0, 1.0)).distance(q)
})
.fold(f64::INFINITY, f64::min)
};
for q in (0..=200).map(|k| seg.eval(f64::from(k) / 200.0)).filter(|q| off_drag(*q) > 14.0) {
let gap = on_after.iter().map(|r| r.distance(q)).fold(f64::INFINITY, f64::min);
assert!(gap < 1.0, "{q:?} is {gap} pt off the smoothed path");
}
}
/// A drag that reaches a segment at its first anchor, leaves it and comes back to its middle smooths
/// the middle too, and the stretch between stays as it was.
#[test]
fn a_smooth_drag_that_comes_back_to_a_segment_smooths_where_it_comes_back() {
use kurbo::ParamCurve;
let mut s = session();
let id = long_peak_segment(&mut s);
let before = path(&s, id);
let drag = [Point::new(100.0, 200.0), Point::new(100.0, 320.0), Point::new(185.0, 320.0), Point::new(185.0, 126.0), Point::new(215.0, 126.0)];
assert_eq!(smooth_pass_ids(&mut s, &drag), json!([id.0]));
let after = path(&s, id);
let (b0, b1) = (sharpest_bend_near_200(&before), sharpest_bend_near_200(&after));
assert!(b1 < 0.97 * b0, "the peak's sharpest bend {b0} -> {b1}");
let between = before.subpaths[0].segment(0).eval(0.3);
let sp = &after.subpaths[0];
let gap = (0..sp.segment_count())
.flat_map(|i| (0..=400).map(move |k| sp.segment(i).eval(f64::from(k) / 400.0)))
.map(|r| r.distance(between))
.fold(f64::INFINITY, f64::min);
assert!(gap < 0.5, "{between:?} is {gap} pt off the smoothed path");
}
/// A click on a curve 100,000 pt long, between the places a fixed number of samples along it would
/// look at, still finds the curve under it.
#[test]
fn a_smooth_drag_finds_a_very_long_curve_under_it() {
use kurbo::ParamCurve;
let mut s = session();
let anchors = [json!({"x": 0.0, "y": 0.0, "out": [30000.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [70000.0, -9000.0]})];
let id = smooth_test_path(&mut s, &anchors, false);
let at = path(&s, id).subpaths[0].segment(0).eval(0.5 + 0.5 / 1024.0);
assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0]));
}
/// A click just within the reach of a segment's peak, with both of the segment's anchors out of
/// reach, smooths the segment although only a few points of it are within the reach.
#[test]
fn a_smooth_click_that_only_just_reaches_a_segment_smooths_it() {
let mut s = session();
let id = long_peak_segment(&mut s);
let before = path(&s, id);
assert_eq!(smooth_pass_ids(&mut s, &[Point::new(200.0, 113.1)]), json!([id.0]));
assert_ne!(path(&s, id), before);
}
/// A drag that runs along a very long curve first and then crosses a second curve away from its
/// middle, with both of its anchors out of reach, smooths the second curve too: each curve in reach
/// gets the same share of the search, so the long one does not use it all.
#[test]
fn a_long_curve_searched_first_leaves_the_next_curve_its_share() {
let mut s = session();
let long = smooth_test_path(
&mut s,
&[json!({"x": 0.0, "y": 0.0, "out": [30000.0, 1.0]}), json!({"x": 100000.0, "y": 0.0, "in": [70000.0, 1.0]})],
false,
);
let next = smooth_test_path(
&mut s,
&[json!({"x": 100100.0, "y": -100.0, "out": [100130.0, 200.0]}), json!({"x": 100100.0, "y": 900.0, "in": [100130.0, 600.0]})],
false,
);
s.execute("select.set", &json!({"ids": [long.0, next.0]})).unwrap();
let before = path(&s, next);
let mut drag: Vec<Point> = (0..=1000).map(|i| Point::new(f64::from(i) * 100.0, 0.0)).collect();
drag.push(Point::new(100200.0, 0.0));
let ids = smooth_pass_ids(&mut s, &drag);
assert!(ids.as_array().is_some_and(|v| v.contains(&json!(next.0))), "{ids}");
assert_ne!(path(&s, next), before);
}
/// An open path of two anchors is smoothed: an S-curve smoothed along its whole length.
#[test]
fn smoothing_smooths_an_open_two_anchor_path() {
use kurbo::ParamCurve;
let mut s = session();
let anchors = [json!({"x": 100.0, "y": 200.0, "out": [170.0, 130.0]}), json!({"x": 200.0, "y": 200.0, "in": [130.0, 270.0]})];
let id = smooth_test_path(&mut s, &anchors, false);
let before = path(&s, id);
let seg = before.subpaths[0].segment(0);
let drag: Vec<Point> = (0..=20).map(|k| seg.eval(f64::from(k) / 20.0)).collect();
assert_eq!(smooth_pass_ids(&mut s, &drag), json!([id.0]));
let after = path(&s, id);
let (t0, t1) = (total_turning(&before), total_turning(&after));
assert!(t1 < t0, "open: turning {t0} -> {t1}");
let a = &after.subpaths[0].anchors;
assert_eq!((a[0].p, a[a.len() - 1].p), (Point::new(100.0, 200.0), Point::new(200.0, 200.0)), "the ends stay");
}
/// A closed path of two anchors is smoothed along the middle of one side and stays closed.
#[test]
fn smoothing_smooths_a_closed_two_anchor_path() {
use kurbo::ParamCurve;
let mut s = session();
let anchors = [
json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [100.0, 200.0]}),
json!({"x": 300.0, "y": 300.0, "in": [300.0, 160.0], "out": [300.0, 440.0]}),
];
let id = smooth_test_path(&mut s, &anchors, true);
let before = path(&s, id);
let top = before.subpaths[0].segment(0);
let mid = top.eval(0.5);
assert_eq!(smooth_pass_ids(&mut s, &[mid - kurbo::Vec2::new(10.0, 0.0), mid + kurbo::Vec2::new(10.0, 0.0)]), json!([id.0]));
let after = path(&s, id);
assert!(after.subpaths[0].closed && after != before, "{after:?}");
}
/// A drag that passes nowhere near a path's segments, or only over the middle of a straight
/// segment, leaves the path as it was.
#[test]
fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() {
let mut s = session();
let id = long_peak_segment(&mut s);
let before = path(&s, id);
assert_eq!(smooth_pass_ids(&mut s, &smooth_drag_along(260.0, 100.0, 400.0)), json!([]), "60 pt off the path");
assert_eq!(path(&s, id), before);
let line = smooth_test_path(&mut s, &[json!({"x": 100.0, "y": 400.0}), json!({"x": 300.0, "y": 400.0}), json!({"x": 300.0, "y": 450.0})], false);
let before = path(&s, line);
assert_eq!(smooth_pass_ids(&mut s, &smooth_drag_along(400.0, 190.0, 210.0)), json!([]), "a straight segment");
assert_eq!(path(&s, line), before);
}
#[test]
fn join_tool_joins_two_lines() {
let mut s = session();
+159 -1
View File
@@ -2,7 +2,7 @@
use serde_json::json;
use vectorcraft_doc::text::INLINE_CHAR;
use vectorcraft_doc::{NodeId, NodeKind, TextObject};
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
@@ -167,6 +167,164 @@ fn inline_graphics_follow_their_symbol() {
let _ = s.execute("document.serialize", &json!({"format": "pdf"})).unwrap();
}
/// The first text in tree `n`, its opacity mask art included.
fn first_text(n: &Node) -> Option<TextObject> {
if let NodeKind::Text(t) = &n.kind {
return Some((**t).clone());
}
if let Some(t) = n.extras().mask.as_deref().and_then(|m| first_text(&m.art)) {
return Some(t);
}
n.children().into_iter().flatten().find_map(|c| first_text(c))
}
/// The first text in the art of symbol `name`.
fn art_text(s: &Session, name: &str) -> TextObject {
let d = &s.doc().unwrap().doc;
first_text(&d.symbols.iter().find(|x| x.name == name).unwrap().art).unwrap()
}
/// The bounds of the first inline graphic in `t`.
fn inline_bounds(t: &TextObject) -> Option<vectorcraft_geom::Rect> {
t.runs.iter().find_map(|r| r.inline.as_ref()).unwrap().bounds
}
/// Redefines symbol `name` as a 40 × 20 ellipse.
fn redefine_as_wide_ellipse(s: &mut Session, name: &str) {
let e = s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap();
s.execute("select.set", &json!({"ids": [e["id"]]})).unwrap();
s.execute("symbol.update", &json!({"name": name})).unwrap();
}
/// A symbol made from type with an inline graphic: when the symbol the graphic shows changes, the
/// type in the symbol's art is laid out again, the symbol's art takes its new size, and an inline
/// graphic of that symbol follows. Undo, redo and opening a saved copy keep it so.
#[test]
fn inline_graphics_in_symbol_art_follow_their_symbol() {
let mut s = session();
circle_symbol(&mut s, "Dot", 10.0);
let id = text(&mut s, "ab");
s.execute("text.insertInline", &json!({"id": id.0, "at": 1, "symbol": "Dot", "scale": 1})).unwrap();
s.execute("symbol.new", &json!({"name": "Holder", "ids": [id.0]})).unwrap();
let line = text(&mut s, "x");
s.execute("text.insertInline", &json!({"id": line.0, "at": 0, "symbol": "Holder", "scale": 1})).unwrap();
let held = art_text(&s, "Holder");
let w0 = held.cached_bounds.unwrap().width();
let holder0 = s.doc().unwrap().doc.symbol_art_bounds("Holder").unwrap();
redefine_as_wide_ellipse(&mut s, "Dot");
let d = &s.doc().unwrap().doc;
let held = art_text(&s, "Holder");
let b = inline_bounds(&held).unwrap();
assert!((b.width() / b.height() - 2.0).abs() < 0.1, "{b:?}");
assert_eq!(Some(b), d.symbol_art_bounds("Dot"));
let w1 = held.cached_bounds.unwrap().width();
assert!((w1 - w0 - 20.0).abs() < 1.5, "{w0} → {w1}");
assert!(held.cached_ink.is_some() && !held.cached_baselines.is_empty());
let holder1 = d.symbol_art_bounds("Holder").unwrap();
assert!(holder1.width() > holder0.width() + 1.0, "{holder0:?} → {holder1:?}");
assert_eq!(inline_bounds(&obj(&s, line)), Some(holder1), "an inline graphic of the holder follows it");
// Undo and redo.
s.execute("edit.undo", &json!({})).unwrap();
assert!((art_text(&s, "Holder").cached_bounds.unwrap().width() - w0).abs() < 1e-6);
s.execute("edit.redo", &json!({})).unwrap();
assert!((art_text(&s, "Holder").cached_bounds.unwrap().width() - w1).abs() < 1e-6);
// Opening a saved copy measures it the same way.
let doc = (*s.doc().unwrap().doc).clone();
let mut back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
back.title = "copy".into();
let mut s2 = Session::new();
s2.add_document(back, None);
let held2 = art_text(&s2, "Holder");
assert_eq!(inline_bounds(&held2), s2.doc().unwrap().doc.symbol_art_bounds("Dot"));
assert!((held2.cached_bounds.unwrap().width() - w1).abs() < 1e-6);
assert_eq!(inline_bounds(&obj(&s2, line)), s2.doc().unwrap().doc.symbol_art_bounds("Holder"));
}
/// Type with an inline graphic in an opacity mask and in a pattern tile follows its symbol.
#[test]
fn inline_graphics_in_masks_and_pattern_tiles_follow_their_symbol() {
let mut s = session();
circle_symbol(&mut s, "Dot", 10.0);
let masked = text(&mut s, "ab");
s.execute("text.insertInline", &json!({"id": masked.0, "at": 1, "symbol": "Dot"})).unwrap();
let owner = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
s.edit("Mask", |d, _| {
let art = d.remove(masked)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
let tiled = text(&mut s, "cd");
s.execute("text.insertInline", &json!({"id": tiled.0, "at": 1, "symbol": "Dot"})).unwrap();
s.execute("object.pattern.make", &json!({"ids": [tiled.0], "name": "Tile", "edit": false})).unwrap();
redefine_as_wide_ellipse(&mut s, "Dot");
let d = &s.doc().unwrap().doc;
let want = d.symbol_art_bounds("Dot");
let mask = first_text(&d.node(owner).unwrap().extras().mask.as_deref().unwrap().art).unwrap();
assert_eq!(inline_bounds(&mask), want);
let tile = d.patterns.iter().find(|p| p.name == "Tile").unwrap().art.iter().find_map(|n| first_text(n)).unwrap();
assert_eq!(inline_bounds(&tile), want);
}
/// Symbol C shows B inline and B shows A: with the symbols listed C, B, A, a change to A reaches C
/// through B's new size.
#[test]
fn symbols_are_resolved_after_the_symbols_they_show_inline() {
let mut s = session();
circle_symbol(&mut s, "A", 10.0);
for (name, shows) in [("B", "A"), ("C", "B")] {
let t = text(&mut s, "z");
s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": shows})).unwrap();
s.execute("symbol.new", &json!({"name": name, "ids": [t.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
}
s.edit("Reverse the symbols", |d, _| {
d.symbols.reverse();
Ok(())
})
.unwrap();
let b0 = s.doc().unwrap().doc.symbol_art_bounds("B");
redefine_as_wide_ellipse(&mut s, "A");
let d = &s.doc().unwrap().doc;
assert_eq!(inline_bounds(&art_text(&s, "B")), d.symbol_art_bounds("A"));
assert_ne!(d.symbol_art_bounds("B"), b0);
assert_eq!(inline_bounds(&art_text(&s, "C")), d.symbol_art_bounds("B"));
}
/// A symbol whose art shows the symbol itself inline, directly or through another symbol, is an
/// empty slot, and stays one through later edits.
#[test]
fn a_symbol_that_shows_itself_inline_is_an_empty_slot() {
let mut s = session();
for name in ["Loop", "P", "Q"] {
circle_symbol(&mut s, name, 10.0);
}
for (name, shows) in [("Loop", "Loop"), ("P", "Q"), ("Q", "P")] {
let t = text(&mut s, "ab");
s.execute("text.insertInline", &json!({"id": t.0, "at": 1, "symbol": shows})).unwrap();
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("symbol.update", &json!({"name": name})).unwrap();
}
let line = text(&mut s, "x");
s.execute("text.insertInline", &json!({"id": line.0, "at": 0, "symbol": "P"})).unwrap();
for _ in 0..2 {
for name in ["Loop", "P", "Q"] {
assert_eq!(inline_bounds(&art_text(&s, name)), None, "{name}");
assert_eq!(s.doc().unwrap().doc.inline_art_bounds(name), None, "{name}");
}
assert_eq!(inline_bounds(&obj(&s, line)), None);
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
}
let _ = s.execute("document.serialize", &json!({"format": "png"})).unwrap();
// Redefined without the inline graphic, Q is on no cycle, and neither is P.
redefine_as_wide_ellipse(&mut s, "Q");
let d = &s.doc().unwrap().doc;
assert!(d.inline_art_bounds("P").is_some());
assert_eq!(inline_bounds(&obj(&s, line)), d.symbol_art_bounds("P"));
assert_eq!(inline_bounds(&art_text(&s, "P")), d.symbol_art_bounds("Q"));
assert_eq!(d.inline_art_bounds("Loop"), None);
}
/// A list paragraph that starts with an inline graphic draws its bullet before the graphic, and
/// live SVG text writes the bullet.
#[test]
+28
View File
@@ -464,6 +464,34 @@ fn linux_display_server_defaults_to_automatic_and_validates() {
assert_eq!(s.prefs.linux_display_server, "automatic");
}
/// Performance › Use Monitor Profile for Canvas: on by default and for preference files written
/// before it, a boolean only, saved, listed under Performance, and set without changing the
/// document.
#[test]
fn monitor_profile_display_is_on_by_default_and_changes_no_document() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
assert!(s.prefs.monitor_profile_display);
let old: Prefs = serde_json::from_value(json!({"gpuPerformance": true})).unwrap();
assert!(old.monitor_profile_display);
let (revision, doc) = (s.active().unwrap().revision, s.active().unwrap().doc.clone());
s.execute("prefs.set", &json!({"key": "monitorProfileDisplay", "value": false})).unwrap();
assert!(!s.prefs.monitor_profile_display);
assert_eq!(s.prefs.to_json()["monitorProfileDisplay"], false);
for bad in [json!("off"), json!(0), json!(null)] {
assert!(s.execute("prefs.set", &json!({"key": "monitorProfileDisplay", "value": bad})).is_err(), "{bad}");
assert!(!s.prefs.monitor_profile_display);
}
assert_eq!(s.active().unwrap().revision, revision);
assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &doc), "the document is not edited");
let l = s.execute("prefs.list", &json!({})).unwrap();
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "monitorProfileDisplay").unwrap().clone();
assert_eq!((row["category"].as_str(), row["label"].as_str()), (Some("Performance"), Some("Use Monitor Profile for Canvas")));
s.execute("prefs.reset", &json!({"category": "Performance"})).unwrap();
assert!(s.prefs.monitor_profile_display);
}
/// Linux Display Server's pen choice (#2028): set by value or by label, saved, and off by default.
#[test]
fn linux_display_server_has_a_choice_for_an_attached_pen() {
+91
View File
@@ -291,3 +291,94 @@ fn a_warp_on_a_group_bends_the_image_in_it() {
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
}
/// A selected embedded 40×40 px red image at half alpha filling [`FRAME`], with Effect › Warp ›
/// Arc at 50 %.
fn half_clear_arc(s: &mut Session) {
clear_arc(s, |_| 128);
}
/// [`half_clear_arc`] with each column `x` of pixels at alpha `alpha(x)`.
fn clear_arc(s: &mut Session, alpha: impl Fn(u32) -> u8) {
let img = image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([255, 0, 0, alpha(x)]));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.edit("Place", |d, sel| {
d.images.insert("half".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0);
let im =
vectorcraft_doc::ImageObject { key: "half".into(), width: 40, height: 40, xf, link: None, placement: Default::default(), pixels: None };
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap();
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
}
/// The points of a 50 × 50 grid over the bent image of [`half_clear_arc`], away from its outer
/// edges, where the document drawn on white at 8 px a point is not half red (its green is not in
/// `green`; half red over white is (255, 128, 128)): the first few.
fn not_half_red(s: &Session, green: std::ops::RangeInclusive<u8>) -> Vec<(f64, f64, [u8; 4])> {
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 300.0, 300.0), 8.0, true);
let mut out = vec![];
for i in 0..50 {
for j in 0..50 {
let (u, v) = (0.03 + 0.94 * f64::from(i) / 49.0, 0.03 + 0.94 * f64::from(j) / 49.0);
let p = arced(50.0, u, v);
let px = img.pixel((p.x * 8.0).floor() as u32, (p.y * 8.0).floor() as u32);
if !green.contains(&px[1]) && out.len() < 8 {
out.push((u, v, px));
}
}
}
out
}
/// The pieces a warp cuts a half transparent image into overlap: the image stays half
/// transparent there, on the canvas and in a PDF opened again.
#[test]
fn a_half_transparent_warped_image_has_no_darker_seams() {
let mut s = session();
half_clear_arc(&mut s);
assert_eq!(not_half_red(&s, 120..=136), vec![], "canvas");
// Opened again, each piece is drawn through masks of the pieces above it, and pixels on a
// triangle's antialiased edge come out a little lighter. Pieces whose alphas add up where they
// overlap draw a green of about 64 there.
let pdf = s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false})).unwrap();
let mut back = session();
back.execute("document.open", &json!({"name": "half.pdf", "dataBase64": pdf["dataBase64"]})).unwrap();
assert_eq!(not_half_red(&back, 120..=152), vec![], "pdf");
}
/// An image whose left half is opaque and whose right half is at half alpha keeps its opaque
/// pixels opaque where the pieces of a warp overlap, away from the partly transparent pixels, on
/// the canvas and in a PDF opened again.
#[test]
fn opaque_pixels_of_a_partly_transparent_warped_image_have_no_lighter_seams() {
let mut s = session();
clear_arc(&mut s, |x| if x < 20 { 255 } else { 128 });
// The points of a fine grid over the left 30 % of the bent image, away from its outer edges,
// where the document drawn on white at 8 px a point is not red: the first few.
let not_red = |s: &Session| {
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 300.0, 300.0), 8.0, true);
let mut out = vec![];
for i in 0..300 {
for j in 0..800 {
let (u, v) = (0.03 + 0.27 * f64::from(i) / 299.0, 0.03 + 0.94 * f64::from(j) / 799.0);
let p = arced(50.0, u, v);
let px = img.pixel((p.x * 8.0).floor() as u32, (p.y * 8.0).floor() as u32);
if px[1] > 6 && out.len() < 8 {
out.push((u, v, px));
}
}
}
out
};
assert_eq!(not_red(&s), vec![], "canvas");
let pdf = s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false})).unwrap();
let mut back = session();
back.execute("document.open", &json!({"name": "mixed.pdf", "dataBase64": pdf["dataBase64"]})).unwrap();
assert_eq!(not_red(&back), vec![], "pdf");
}
+20 -1
View File
@@ -571,6 +571,25 @@ fn distort_command_warps_the_linked_mask_of_a_path_in_a_group() {
assert_eq!(a.extras().mask.as_ref().unwrap().art.path_data(), a.path_data(), "and so is its mask");
}
/// Corners where the box already stands change nothing: no undo step, the document as it was. A
/// corner moved by a hundredth of a point is a warp.
#[test]
fn unchanged_distort_records_no_history() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let b = s.doc().unwrap().doc.bounds_of(&[a], false).unwrap();
let doc = s.doc().unwrap().doc.clone();
let n = undo_len(&s);
let at = |x1: f64| json!([[b.x0, b.y0], [x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]]);
assert_eq!(s.execute("object.distort", &json!({"corners": at(b.x1)})).unwrap()["ids"], json!([a.0]));
assert_eq!(undo_len(&s), n);
assert!(s.doc().unwrap().doc == doc, "the document is unchanged");
s.execute("object.distort", &json!({"corners": at(b.x1 + 0.01)})).unwrap();
assert_eq!(undo_len(&s), n + 1);
assert!(s.doc().unwrap().doc != doc);
}
#[test]
fn distort_perspective_midpoint_is_projective() {
// Distort a tiny probe at the centre of a 100×100 source box into a trapezoid: with a real
@@ -1239,7 +1258,7 @@ fn distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle() {
}
s.execute("object.distort", &json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": 90, "ids": [a.0]})).unwrap();
assert!(close(bounds(&s, a), original), "{:?}", bounds(&s, a));
assert_eq!(undo_len(&s), history + 1);
assert_eq!(undo_len(&s), history, "corners where the box stands change nothing");
// Without `from`, the box is the objects' bounds in the turned frame: the same box here.
s.execute("object.distort", &json!({"corners": corners, "angle": 90, "ids": [a.0]})).unwrap();
assert!(close(bounds(&s, a), original), "{:?}", bounds(&s, a));