Merge main into feat/font-menu-show-similar

This commit is contained in:
dotCooCoo
2026-11-15 16:48:53 -08:00
151 changed files with 8228 additions and 776 deletions
+38 -1
View File
@@ -4272,15 +4272,26 @@ fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
// `through` takes edge ids, with scope "connected" only.
// `through` takes the group's edge ids, each once, with scope "connected" only; a face's id, an
// unknown id or an edge given twice is refused and changes nothing.
let face = vectorcraft_tools::builder::faces(&node(&s, g)).first().map(|f| f.id).unwrap();
let before = s.doc().unwrap().doc.clone();
let depth = s.doc().unwrap().history.undo.len();
for p in [
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
json!({"group": g.0, "point": [15, 50], "through": []}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [face.0]}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [999_999_999]}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0, middle[1].0]}),
] {
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
}
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0]})).unwrap();
assert_eq!(r["count"], 3, "an edge of the group is taken");
}
/// A double-click whose second press lands on the next joined edge and is released back on the
@@ -4318,6 +4329,32 @@ fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joi
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
}
/// With Paint Fills and Paint Strokes both on, a double-click on an edge after a click that filled
/// a face whose fill was the edge's stroke paint paints the joined edges: the face is not sent as
/// an edge to join through.
#[test]
fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let [a, b] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0)])[..] else { panic!("two faces") };
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.set_tool_option("paintStrokes", &json!(true));
s.paint.fill = green.clone();
s.paint.stroke = green.clone();
for (kind, x) in [(PointerKind::Down, 25.0), (PointerKind::Up, 25.0), (PointerKind::Down, 50.0), (PointerKind::Up, 50.0)] {
s.pointer(&PointerEvent::new(kind, x, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, a), green, "the first click fills the face");
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 50.0, 25.0), v).unwrap();
assert!(all.iter().all(|e| node(&s, *e).appearance.stroke_paint() == green), "every joined edge is painted");
assert_eq!(fill_of(&s, b), black);
}
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
#[test]
+78
View File
@@ -768,6 +768,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() {
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again");
}
/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges
/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that
/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were.
#[test]
fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() {
let mut s = session();
let csv = ",North,South\nP,1,1";
s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap();
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
/// The fill of the legend label of graph `id` that says `name`.
fn label(s: &Session, id: NodeId, name: &str) -> Paint {
let mut out = None;
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == name
{
out = Some(t.first_style().fill.clone());
}
});
out.unwrap()
}
// The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black.
let mut wedges = vec![];
for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) {
c.walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
wedges.push(m.id.0);
}
});
}
assert!(!wedges.is_empty());
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge");
assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK));
copy(&mut s, &[g]);
for (cmd, choice, north) in [
("edit.pasteWithoutFormatting", "merge", Color::WHITE),
("edit.paste", "merge", Color::WHITE),
("edit.pasteWithoutFormatting", "add", Color::BLACK),
("edit.paste", "add", Color::BLACK),
] {
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0];
assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}");
assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}");
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it");
}
// A copy of the pie in the opacity mask of a rectangle follows the same way.
s.execute("document.activate", &json!({"index": 0})).unwrap();
let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0);
let art = {
let d = doc_mut(&mut s);
let pie = d.node(g).unwrap().clone();
d.reid(&pie)
};
doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
copy(&mut s, &[r]);
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0];
let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone();
let mut north = None;
mask.walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "North"
{
north = Some(t.first_style().fill.clone());
}
});
assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask");
}
/// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph
/// is pasted without formatting.
#[test]
+19
View File
@@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() {
}
}
/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the
/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click.
#[test]
fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() {
let mut s = new_doc();
set_angle(&mut s, 90.0);
let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6});
let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p));
assert_eq!(p["anchors"], json!(6));
let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(n.live_shape().is_none());
assert_eq!(n.path_data().unwrap().anchor_count(), 6);
let b = bounds(&s, id);
for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] {
assert!(close(got, want), "{b:?}");
}
}
/// The Line Segment tool's Shift steps of 45° count from the Constrain Angle.
#[test]
fn constrain_angle_steps_the_line_segment_tool() {
+20
View File
@@ -265,6 +265,26 @@ fn liquify_without_selection_hits_paths_under_the_brush() {
assert!(path(&s, b).bounds().unwrap().width() < 100.0);
}
/// The warning about objects under the brush that Liquify leaves as they are names their count
/// with the matching noun and verb.
#[test]
fn liquify_warns_about_one_or_several_skipped_objects() {
let mut s = session();
let text =
|s: &mut Session, x: i32| s.execute("text.create", &json!({"x": x, "y": 460, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap();
let pucker = json!({"tool": "pucker", "points": [[550, 450]], "diameter": 150, "intensity": 1});
let first = text(&mut s, 520);
s.execute("select.set", &json!({"ids": []})).unwrap();
let r = s.execute("object.liquify", &pucker).unwrap();
assert_eq!(r["skipped"], json!([first]));
assert_eq!(r["warning"], "Pucker left 1 object under the brush as it was (type): it reshapes paths only");
let second = text(&mut s, 560);
s.execute("select.set", &json!({"ids": []})).unwrap();
let r = s.execute("object.liquify", &pucker).unwrap();
assert_eq!(r["skipped"], json!([first, second]));
assert_eq!(r["warning"], "Pucker left 2 objects under the brush as they were (type): it reshapes paths only");
}
/// With nothing selected, a stroke leaves the art on a locked artboard as it is.
#[test]
fn liquify_without_selection_leaves_the_art_on_a_locked_artboard() {
+78
View File
@@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() {
assert!(paths(&s).is_empty());
}
/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the
/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a
/// shape wholly inside goes, and only the selected paths take part when something is selected. One
/// undo step puts everything back, and a rectangle that touches nothing adds no undo step.
#[test]
fn erase_region_rect_erases_everything_inside_it() {
let filled = |s: &Session, x: f64, y: f64| {
paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)))
};
let mut s = session();
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
rect(&mut s, 180.0, 140.0, 10.0, 10.0);
line(&mut s, 50.0, 150.0, 350.0, 150.0);
s.execute("select.none", &json!({})).unwrap();
let undo = undo_steps(&s);
let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap();
assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}");
assert_eq!(undo_steps(&s), undo + 1);
assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it");
assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled");
let ps = paths(&s);
assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}");
let open: Vec<f64> = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect();
assert_eq!(open.len(), 2, "the line is cut in two: {open:?}");
assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s).len(), 3);
assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0));
// A rectangle away from the art erases nothing and adds no undo step.
let undo = undo_steps(&s);
assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []}));
assert_eq!(undo_steps(&s), undo);
// With the line selected, only the line is erased.
let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0;
s.execute("select.set", &json!({"ids": [ln.0]})).unwrap();
let closed: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect();
s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap();
let after: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect();
assert_eq!(after, closed, "the unselected squares are unchanged");
let open: Vec<f64> = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect();
assert_eq!(open.len(), 2);
assert!((open.iter().sum::<f64>() - 270.0).abs() < 0.01, "{open:?}");
}
/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle
/// falls between the samples the path's length would give.
#[test]
fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() {
let mut s = session();
line(&mut s, 0.0, 100.0, 10000.0, 100.0);
s.execute("select.none", &json!({})).unwrap();
s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap();
let mut open: Vec<f64> = paths(&s).iter().map(|(_, pd)| pd.length()).collect();
open.sort_by(f64::total_cmp);
assert_eq!(open.len(), 2, "{open:?}");
assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}");
}
/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height
/// above 0, and `rect` given with `points`, and changes nothing.
#[test]
fn erase_region_rect_refuses_bad_values() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let shape = "rect is [x, y, width, height] in points, with a width and a height above 0";
for p in [
json!({"rect": [10, 10, 0, 20]}),
json!({"rect": [10, 10, 20, -5]}),
json!({"rect": [10, 10, 20]}),
json!({"rect": [10, "10", 20, 20]}),
json!({"rect": [1e308, 0, 1e308, 20]}),
json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}),
] {
refuses_with(&mut s, "path.eraseRegion", &p, shape);
}
refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both");
}
/// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is
/// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one
/// compound path; a drag through the whole ring leaves compound paths whose holes stay holes.
+230
View File
@@ -582,3 +582,233 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() {
}
let _ = std::fs::remove_dir_all(dir);
}
/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled
/// Poster.
fn template_session(dir: &std::path::Path) -> Session {
let mut s = session();
s.attach_metadata_templates_dir(dir.join("Metadata Templates"));
s
}
#[test]
fn a_saved_metadata_template_is_listed_and_applies_to_another_document() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template");
let mut s = template_session(&dir);
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet");
s.execute("file.info", &info()).unwrap();
let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap();
assert_eq!(r["name"], "Studio");
let path = dir.join("Metadata Templates").join("Studio.xmp");
assert!(path.is_file(), "saved into the folder: {r}");
let listed = s.execute("file.info.templates", &json!({})).unwrap();
assert_eq!(listed["templates"][0]["name"], "Studio");
assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1));
// A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file.
for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] {
assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}");
}
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1));
// Saving is not an edit of the document.
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
// Into a new document, by name, in one undo step.
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap();
assert_eq!(r["changed"], true);
let m = &s.doc().unwrap().doc.metadata;
assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4));
assert_eq!(m.keywords, ["fair", "Poster", "print"]);
assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada"));
assert_eq!(m.description, "A poster\nfor the fair");
assert_eq!(r["title"], "Poster", "the template carries the title of its own");
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
// Applied again, nothing changes and nothing is recorded.
let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap();
assert_eq!(r["changed"], false);
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.author, "");
// The same name replaces the template.
s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap();
let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(back.author.as_deref(), Some("Grace"));
assert_eq!(back.title, None, "an Untitled-N title is not written");
}
#[test]
fn a_metadata_template_merges_in_three_modes() {
let mut s = session();
s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap();
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
author: Some("Grace".into()),
description: Some("From the template".into()),
keywords: Some(vec!["print".into(), "Fair".into()]),
rating: Some(5),
copyrighted: Some(false),
..Default::default()
});
let merged =
|s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap();
// Clear and replace: the fields the template lacks are cleared; the title stays.
let r = merged(&mut s, "replace");
assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5)));
assert_eq!(
(r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()),
(json!(["print", "Fair"]), Some(""), Some("publicDomain"))
);
assert_eq!(r["title"], "Poster");
// Keep and replace: the template's fields replace those it has; the others stay.
let r = merged(&mut s, "keep");
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a")));
assert_eq!(r["keywords"], json!(["print", "Fair"]));
// Keep and append: keywords are added (each once), and only empty fields are filled.
let r = merged(&mut s, "append");
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template")));
assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain")));
// `apply: false` changed nothing; `base` merges into the given fields instead.
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada");
let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap();
assert_eq!(r["author"], "Grace");
// Applied: one undo step.
s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), 2);
assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, "");
}
#[test]
fn metadata_template_errors() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors");
let mut s = template_session(&dir);
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
let not_xmp = dir.join("note.xmp");
std::fs::write(&not_xmp, "<note>not metadata</note>").unwrap();
let big = dir.join("big.xmp");
std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap();
let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
for bad in [
json!({"data": xmp, "mode": "merge"}),
json!({"data": xmp}),
json!({"data": xmp, "mode": 3}),
json!({"mode": "keep"}),
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
json!({"name": "missing", "mode": "keep"}),
json!({"data": "Ada Lovelace", "mode": "keep"}),
json!({"data": xmp, "mode": "keep", "apply": "yes"}),
json!({"data": xmp, "mode": "keep", "base": [1]}),
json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}),
] {
assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}");
}
for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] {
assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), 0);
assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder");
// A link in the folder is not followed, by its name or its file name.
#[cfg(unix)]
{
let outside = dir.join("outside.xmp");
std::fs::write(&outside, &xmp).unwrap();
std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap();
std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap();
for name in ["Linked", "Linked.xmp"] {
assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}");
}
let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("not a file"), "{e}");
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]));
// A save by that name leaves the linked file as it was.
let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err();
assert!(e.to_string().contains("not a file"), "{e}");
assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp);
std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap();
}
// Without a folder (runs without preferences), a name is an error, the data comes back, and
// the list is empty.
let mut s = session();
assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err());
let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string();
assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada"));
assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []}));
}
#[test]
fn the_templates_folder_lists_only_xmp_files_and_can_be_made() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list");
let mut s = template_session(&dir);
let r = s.execute("file.info.templates", &json!({"create": true})).unwrap();
let folder = dir.join("Metadata Templates");
assert!(folder.is_dir());
assert_eq!(r["folder"], folder.to_str().unwrap());
for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] {
std::fs::write(folder.join(f), "x").unwrap();
}
std::fs::create_dir(folder.join("c.xmp")).unwrap();
// Other files, however many, leave the templates listed.
for i in 0..1000 {
std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap();
}
let names: Vec<String> = s.execute("file.info.templates", &json!({})).unwrap()["templates"]
.as_array()
.unwrap()
.iter()
.map(|t| t["name"].as_str().unwrap().to_string())
.collect();
assert_eq!(names, ["a", "b"]);
// A listed name opens whatever the case of its extension.
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
std::fs::write(folder.join("b.XMP"), xmp).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap();
assert_eq!(r["author"], "Grace");
// Its listed file name opens it too.
let listed = s.execute("file.info.templates", &json!({})).unwrap();
assert_eq!(listed["templates"][1]["file"], "b.XMP");
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
// A listed file name is taken before the name with `.xmp` added.
let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Ada");
// A name that is not a file name never opens the template its safe form names.
let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
std::fs::write(folder.join("a-b.xmp"), grace).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
for name in ["a/b", "a\\b", "a:b"] {
let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err();
assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}");
}
}
#[test]
fn the_largest_file_info_saves_a_template_that_imports() {
let mut s = session();
let text = "\"&".repeat(32_768);
let keywords: Vec<String> = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect();
let fields = json!({
"author": text, "authorTitle": text, "description": text, "copyrightNotice": text,
"copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted",
});
let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string();
assert!(data.len() > 1 << 20, "{} bytes", data.len());
let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap();
assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000)));
}
#[test]
fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() {
let mut m = DocMetadata::default();
let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() };
crate::cmd::fileinfo::read_pdf(&mut m, f);
assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3));
}
+35
View File
@@ -102,6 +102,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
assert!(!d.is_dirty(), "nothing to save");
}
/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a
/// stylistic set's name, and refuses a font that isn't available and params that aren't strings.
#[test]
fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() {
use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid};
FontDb::global().add_font(categories_font().expect("the test font builds"));
let mut s = Session::new();
let g = |c| u32::from(source_sans_gid(c).expect("a glyph"));
let mut figures = vec![g('7'), g('8')];
figures.sort_unstable();
let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap();
assert_eq!(r["family"], CATEGORIES_FAMILY);
assert_eq!(r["style"], "Regular");
assert_eq!(
r["categories"],
json!([
{"id": "ligatures", "glyphs": [g('L')]},
{"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]},
{"id": "smallCaps", "glyphs": [g('B')]},
{"id": "figures", "glyphs": figures},
])
);
assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r);
for (p, says) in [
(json!({}), "missing `family`"),
(json!({"family": 3}), "`family` must be a string"),
(json!({"family": "No Such Font"}), "is not available"),
(json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"),
(json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"),
] {
let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
}
/// Refreshing the font list while a background save writes the file leaves the document saved
/// once the file is written.
#[test]
+16
View File
@@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() {
assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none());
}
/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane.
#[test]
fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() {
let (mut s, _) = persp_session();
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap();
let at = Point::new(470.0, 300.0);
let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6});
let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap();
let n = undo_len(&s);
let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap());
assert_eq!(undo_len(&s), n + 1);
assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right));
assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6);
}
#[test]
fn the_canvas_draws_type_in_perspective_foreshortened() {
let (mut s, rect) = persp_session();
+301
View File
@@ -1158,3 +1158,304 @@ fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() {
assert!(!aligned(&s, off));
assert_eq!(not_aligned(&mut s, &[compound]), vec![other]);
}
/// The anchors of the paths in the art of symbol instance `inst`, where its transform places them.
fn placed_points(s: &Session, inst: u64) -> Vec<(f64, f64)> {
let d = &s.doc().unwrap().doc;
let NodeKind::SymbolInstance { symbol, xf } = &d.node(NodeId(inst)).unwrap().kind else { panic!("{inst} is not a symbol instance") };
let art = &d.symbols.iter().find(|x| &x.name == symbol).unwrap().art;
let mut out = vec![];
art.walk(&mut |n| {
if let Some(p) = n.path_data() {
out.extend(p.anchors().map(|(_, _, a)| {
let q = *xf * a.p;
(q.x, q.y)
}));
}
});
out
}
/// The transform of symbol instance `inst`.
fn instance_xf(s: &Session, inst: u64) -> vectorcraft_geom::Affine {
match &s.doc().unwrap().doc.node(NodeId(inst)).unwrap().kind {
NodeKind::SymbolInstance { xf, .. } => *xf,
_ => panic!("{inst} is not a symbol instance"),
}
}
/// Symbol Options › Align to Pixel Grid on a new symbol: the instance that replaces the selection
/// draws its art's edges on whole points, and goes back to them after a move by a fraction of a
/// point; a symbol made without it keeps the art where it was drawn.
#[test]
fn a_pixel_aligned_symbol_keeps_its_instance_on_whole_points() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let r = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(r["alignToPixelGrid"], true);
let inst = r["id"].as_u64().unwrap();
let pts = placed_points(&s, inst);
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
let list = s.execute("symbol.list", &json!({})).unwrap();
assert_eq!(list["symbols"][0]["alignToPixelGrid"], true);
path(&mut s, "M100.3 20.6 L140.7 20.6 L140.7 30.3 L100.3 30.3 Z", 2.0);
let plain = s.execute("symbol.new", &json!({"name": "Plain"})).unwrap();
assert_eq!(plain["alignToPixelGrid"], false);
let pts = placed_points(&s, plain["id"].as_u64().unwrap());
assert!(!whole(&pts), "{pts:?}");
}
/// A centered stroke of odd weight puts the art's edges on half points, so the stroke's own edges
/// fall on the grid.
#[test]
fn a_pixel_aligned_symbol_with_an_odd_stroke_goes_to_half_points() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let pts = placed_points(&s, inst);
assert!(halves(&pts), "{pts:?}");
}
/// Turning it on in Symbol Options snaps the instances placed at actual size and leaves a scaled
/// one where it is; instances placed later land on whole points; asking again for the value the
/// symbol has adds no undo step; a duplicate and a rename keep it, a delete clears it, and a value
/// that is not true or false is refused.
#[test]
fn symbol_options_align_to_pixel_grid_snaps_instances_at_actual_size() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("object.scale", &json!({"sx": 150, "sy": 150})).unwrap();
let scaled = instance_xf(&s, b);
assert!(!whole(&placed_points(&s, a)));
let r = s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(r["alignToPixelGrid"], true);
let pts = placed_points(&s, a);
assert!(whole(&pts), "{pts:?}");
assert_eq!(instance_xf(&s, b), scaled);
let c = s.execute("symbol.place", &json!({"name": "Px", "x": 50.3, "y": 60.6})).unwrap()["id"].as_u64().unwrap();
let pts = placed_points(&s, c);
assert!(whole(&pts), "{pts:?}");
let steps = undo_len(&s);
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(undo_len(&s), steps);
assert_eq!(s.execute("symbol.duplicate", &json!({"name": "Px"})).unwrap()["name"], "Px copy");
assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Px copy"));
s.execute("symbol.options", &json!({"name": "Px", "newName": "Grid"})).unwrap();
assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Grid"));
assert!(!s.doc().unwrap().doc.symbol_pixel_aligned("Px"));
s.execute("symbol.delete", &json!({"names": ["Grid", "Px copy"]})).unwrap();
assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_PIXEL_ALIGNED).is_none());
path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0);
assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": "yes"})).is_err());
assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": null})).is_err());
s.execute("symbol.new", &json!({"name": "Q"})).unwrap();
assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": 1})).is_err());
assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": null})).is_err());
}
/// An instance reflected across one axis goes back to whole points after a move; one turned a half
/// turn counts as rotated and moves by exactly the amount asked.
#[test]
fn a_reflected_instance_snaps_and_a_half_turned_one_does_not() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
let [.., e, f] = instance_xf(&s, inst).as_coeffs();
assert!(whole(&[(e, f)]), "{e} {f}");
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
s.execute("object.rotate", &json!({"angle": 180})).unwrap();
let [.., e0, f0] = instance_xf(&s, inst).as_coeffs();
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
let [.., e1, f1] = instance_xf(&s, inst).as_coeffs();
assert!((e1 - e0 - 0.3).abs() < 1e-9 && (f1 - f0 - 0.45).abs() < 1e-9, "{e0} {f0} -> {e1} {f1}");
}
/// An instance of a pixel-aligned symbol attached to a path goes back to whole points each time the
/// path places it.
#[test]
fn an_instance_on_a_path_stays_on_whole_points() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let spine = s.execute("path.create", &json!({"d": "M 0.3 100.4 L 300.3 100.4"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.objectsOnPath.attach", &json!({"path": spine, "ids": [inst]})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "attached: {pts:?}");
let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]);
s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "path edited: {pts:?}");
}
/// A path in the art of an opacity mask in a pixel-aligned symbol's art snaps with the rest of
/// the art.
#[test]
fn mask_art_in_a_pixel_aligned_symbol_snaps() {
let mut s = new_doc();
let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
}
s.execute("select.set", &json!({"ids": [r]})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let xf = instance_xf(&s, inst);
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let mut pts = vec![];
art.walk(&mut |n| {
if let Some(mask) = n.extras().mask.as_ref() {
mask.art.walk(&mut |c| {
if let Some(p) = c.path_data() {
pts.extend(p.anchors().map(|(_, _, a)| {
let q = xf * a.p;
(q.x, q.y)
}));
}
});
}
});
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
}
/// A path in the art of an unlinked opacity mask in a pixel-aligned symbol's art snaps as the mask
/// is drawn at the symbol's natural size.
#[test]
fn unlinked_mask_art_in_a_pixel_aligned_symbol_snaps_at_natural_size() {
let mut s = new_doc();
let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), false)));
}
s.execute("select.set", &json!({"ids": [r]})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
assert_ne!(s.doc().unwrap().doc.symbol_natural_xf("Px"), vectorcraft_geom::Affine::IDENTITY);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let sym = d.symbols.iter_mut().find(|x| x.name == "Px").unwrap();
std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask.as_mut().unwrap().linked = false;
}
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let d = &s.doc().unwrap().doc;
let xf = instance_xf(&s, inst);
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let mut pts = vec![];
art.walk(&mut |n| {
if let Some(mask) = n.extras().mask.as_ref() {
mask.art.walk(&mut |c| {
if let Some(p) = c.path_data() {
pts.extend(p.anchors().map(|(_, _, a)| {
let q = xf * a.p;
(q.x, q.y)
}));
}
});
}
});
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
}
/// A path in the art of an opacity mask on a path of a compound path in a pixel-aligned symbol's
/// art snaps with the rest of the art.
#[test]
fn mask_art_on_a_compound_paths_path_in_a_pixel_aligned_symbol_snaps() {
let mut s = new_doc();
let a = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let b = path(&mut s, "M50.3 20.6 L60.7 20.6 L60.7 30.3 L50.3 30.3 Z", 2.0);
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
let first = d.node(NodeId(c)).unwrap().children().unwrap()[0].id;
d.node_mut(first).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
}
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let xf = instance_xf(&s, inst);
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let mut pts = vec![];
art.walk(&mut |n| {
if let Some(mask) = n.extras().mask.as_ref() {
mask.art.walk(&mut |c| {
if let Some(p) = c.path_data() {
pts.extend(p.anchors().map(|(_, _, a)| {
let q = xf * a.p;
(q.x, q.y)
}));
}
});
}
});
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
}
/// An instance in the art of an object's opacity mask goes to whole points when its symbol is made
/// pixel-aligned.
#[test]
fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
let r = path(&mut s, "M80 180 L160 180 L160 240 L80 240 Z", 1.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let inst = d.remove(NodeId(b)).unwrap();
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*inst).clone(), true)));
}
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let d = &s.doc().unwrap().doc;
let mask = d.node(NodeId(r)).unwrap().extras().mask.clone().unwrap();
let NodeKind::SymbolInstance { xf, .. } = &mask.art.kind else { panic!("the mask art is not the instance") };
let [.., e, f] = xf.as_coeffs();
assert!(whole(&[(e, f)]), "{e} {f}");
}
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
/// on the pixel grid, so its instances stay on it.
#[test]
fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
let st = s.doc().unwrap();
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
s.execute("select.set", &json!({"ids": [part]})).unwrap();
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
assert!(s.doc().unwrap().doc.symbol_edit.is_some());
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
// The editing layer shows the art as it is stored.
let shown = points(&s, part);
assert!(whole(&shown), "{shown:?}");
s.execute("symbol.exitEditing", &json!({})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
}
+21
View File
@@ -380,6 +380,27 @@ fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
assert!((hue(&sb["map"][0]["to"]) - 0.0).abs() < 1.0 && (hue(&sb["map"][1]["to"]) - 120.0).abs() < 1.0, "hue kept");
}
/// A row with no current colors (New Row) keeps its new color through Randomize, and its color
/// goes to no row that holds current colors: the other rows shuffle their own colors only.
#[test]
fn randomize_leaves_an_empty_row_out() {
let mut s = session();
let map = json!([
{"from": [], "to": "rgb 0 255 0"},
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
]);
for seed in 0..16 {
let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed}));
assert_eq!(r["map"][0], map[0], "seed {seed}: the empty row keeps its color");
let mut tos: Vec<String> = [1, 2].iter().map(|i| r["map"][*i]["to"].as_str().unwrap().to_string()).collect();
tos.sort();
assert_eq!(tos, ["rgb 0 0 255", "rgb 255 0 0"], "seed {seed}: a permutation of the filled rows' colors");
}
let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true, "seed": 3}));
assert_eq!(sb["map"][0], map[0], "the empty row keeps its saturation and brightness");
}
#[test]
fn edit_group_rewrites_in_order_as_one_undo_step() {
let mut s = session();
+12
View File
@@ -120,6 +120,18 @@ fn missing_or_mismatched_answer_rolls_back() {
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing");
}
/// The error about answers left over names their count with the matching noun.
#[test]
fn unused_answers_are_counted_in_the_singular_and_the_plural() {
let mut s = one_doc();
let ok = json!({"kind": "alert", "value": "ok"});
for (extra, says) in [(1, "`answers` has 1 answer the script did not use"), (2, "`answers` has 2 answers the script did not use")] {
let given = Value::Array(vec![ok.clone(); extra + 1]);
let e = headless(&mut s, "alert('x');", given).unwrap_err().to_string();
assert!(e.contains(says), "{e}");
}
}
#[test]
fn invalid_answers_are_rejected_before_run() {
let mut s = one_doc();