Merge main into fix/aligned-paint-rows-of-design-art

This commit is contained in:
dotCooCoo
2026-11-14 19:10:09 -08:00
357 changed files with 26728 additions and 3919 deletions
+36
View File
@@ -301,6 +301,42 @@ fn an_export_preset_sets_the_shared_settings() {
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["prefix"], "p_");
}
/// `openLocation` (Open Location after Export) is remembered in the document's export settings,
/// outside presets; null removes it, and only true or false is taken.
#[test]
fn open_location_is_remembered_in_the_export_settings() {
let mut s = session();
let open = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["openLocation"].clone();
let r = run(&mut s, "assets.settings.set", json!({"openLocation": false}));
assert_eq!(open(&mut s), false);
assert!(r["settings"].get("openLocation").is_none(), "{r}");
// Create Sub-folders, on for a document without settings, stays on.
assert_eq!(r["settings"]["subfolders"], true, "{r}");
run(&mut s, "document.exportPresets.save", json!({"name": "Kept", "settings": {"formats": [{"format": "svg"}]}}));
run(&mut s, "assets.settings.set", json!({"exportPreset": "Kept"}));
assert_eq!(open(&mut s), false, "a preset leaves it as it is");
run(&mut s, "assets.settings.set", json!({"openLocation": null}));
assert_eq!(open(&mut s), Value::Null);
for bad in [json!({"openLocation": "yes"}), json!({"openLocation": 1}), json!({"subfolders": "no"})] {
assert!(s.execute("assets.settings.set", &bad).is_err(), "{bad}");
}
}
/// Create Sub-folders turned off on its own ends a remembered folder per format or item, so Export
/// for Screens opens with it off too; given with an export preset, the preset's folders stay.
#[test]
fn create_sub_folders_off_alone_ends_a_folder_per_format_or_item() {
let mut s = session();
let folders = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["folders"].clone();
run(&mut s, "document.exportPresets.save", json!({"name": "Items", "settings": {"formats": [{"format": "svg"}], "folders": "item"}}));
for preset in ["Logo Package", "Items"] {
run(&mut s, "assets.settings.set", json!({"exportPreset": preset, "subfolders": false}));
assert_ne!(folders(&mut s), "none", "{preset}");
run(&mut s, "assets.settings.set", json!({"subfolders": false}));
assert_eq!(folders(&mut s), "none", "{preset}");
}
}
/// An export preset applied to the shared settings keeps its folders, with Create Sub-folders on
/// for a folder per row; with Create Sub-folders off every file goes into the folder itself,
/// mobile and density rows too.
+33
View File
@@ -218,6 +218,39 @@ fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path(
}
}
#[test]
fn reverse_path_direction_turns_a_compound_paths_own_width_profile_and_pen_records() {
use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
let mut s = session();
let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 50.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
run(&mut s, "object.compoundPath.make", json!({}));
let compound = s.doc().unwrap().selection.objects[0];
// A lone rectangle of the same shape, whose strokes Reverse Path Direction already turns.
let lone = rect(&mut s, 0.0);
let profile = WidthProfile { points: vec![(0.0, 0.2, 0.6), (0.3, 1.0, 0.4), (1.0, 0.5, 0.9)] };
let pressure = PressureProfile { points: vec![(0.0, 0.1), (0.25, 0.9), (1.0, 0.4)] };
let bearing = AngleProfile { points: vec![(0.0, 10.0), (0.6, 80.0), (1.0, 170.0)] };
s.edit("set", |d, _| {
for id in [compound, lone] {
let st = d.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
st.profile = Some(profile.clone());
st.pressure = Some(pressure.clone());
st.bearing = Some(bearing.clone());
}
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [compound.0, lone.0]}));
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 3);
let stroke = |id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone();
let (got, want) = (stroke(compound), stroke(lone));
assert_ne!(want.profile.as_ref(), Some(&profile), "the lone rectangle's profile turned");
assert_eq!(got.profile, want.profile, "both members turned alike, so the compound path's profile turns as the rectangle's does");
assert_eq!(got.pressure, want.pressure);
assert_eq!(got.bearing, want.bearing);
}
#[test]
fn attributes_survive_a_native_round_trip() {
let mut s = session();
+155 -1
View File
@@ -666,7 +666,7 @@ fn expanding_a_reflected_symbol_instance_keeps_its_box() {
for reset in [false, true] {
let (mut s, inst) = turned_instance(0.0);
s.execute("object.rotate", &json!({"angle": 150})).unwrap();
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap();
assert!(near(angle(&s, inst), -170.0), "{}", angle(&s, inst));
if reset {
s.execute("object.resetBoundingBox", &json!({})).unwrap();
@@ -719,10 +719,164 @@ fn page_flips_keep_an_upright_box_upright() {
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
assert_eq!(angle(&s, a), 0.0);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
// A named axis is the turned box's own: the box keeps its angle.
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
assert!(near(angle(&s, a), 30.0));
s.execute("object.reflect", &json!({"axis": "vertical", "basis": "page"})).unwrap();
assert!(near(angle(&s, a), -30.0));
}
fn same_matrix(a: Affine, b: Affine) -> bool {
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y))
}
/// After a rotation, Scale and a named Reflect act along the turned bounding box until Reset
/// Bounding Box; `basis: "page"` keeps the page's axes, and Transform Again repeats the matrix the
/// transform applied on the page.
#[test]
fn scale_and_reflect_follow_the_turned_box() {
let mut s = session();
let a = turned_rect(&mut s);
let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap();
let c = Point::new(200.0, 200.0);
let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO };
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let b = selection_box(&s);
assert!(near(b.angle, 45.0) && near(angle(&s, a), 45.0), "{b:?}");
assert!(near(b.rect.width(), 200.0) && near(b.rect.height(), 50.0), "{b:?}");
assert!(b.center().distance(c) < 1e-6, "{b:?}");
let want = Affine::translate(c.to_vec2()) * frame.conjugate(Affine::scale_non_uniform(2.0, 1.0)) * Affine::translate(-c.to_vec2());
let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") };
assert!(same_matrix(m, want), "{m:?}");
// The recorded step names its basis, so a replay acts in the same frame.
let steps = s.journal_for_action(0);
assert!(steps.iter().any(|(id, p)| id == "object.scale" && p["basis"] == "box"), "{steps:?}");
// Reflected across the box's vertical axis through its left side: the box keeps its angle and
// size, and its centre moves a width to the left along the box.
let left = b.reference_point(3);
s.execute("object.reflect", &json!({"axis": "vertical", "origin": [left.x, left.y]})).unwrap();
let r = selection_box(&s);
let moved = c + (frame.to_doc() * Point::new(-200.0, 0.0)).to_vec2();
assert!(near(r.angle, 45.0) && near(r.rect.width(), 200.0) && near(r.rect.height(), 50.0), "{r:?}");
assert!(r.center().distance(moved) < 1e-6, "{r:?}");
// Across its horizontal axis through its centre: the box stays where it is.
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
assert!(selection_box(&s).center().distance(moved) < 1e-6 && near(angle(&s, a), 45.0));
// Unknown bases are errors and change nothing.
let n = undo_len(&s);
assert!(s.execute("object.scale", &json!({"sx": 50, "basis": "turned"})).is_err());
assert!(s.execute("object.reflect", &json!({"axis": "vertical", "basis": 1})).is_err());
assert!(s.execute("object.reflect", &json!({"axis": 30, "basis": "turned"})).is_err());
assert_eq!(undo_len(&s), n);
// On the page's axes, the box no longer stands at 45°.
s.execute("object.scale", &json!({"sx": 50, "sy": 100, "basis": "page"})).unwrap();
assert!(!near(angle(&s, a), 45.0));
// Transform Again repeats the page matrix after Reset Bounding Box too.
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") };
s.execute("object.resetBoundingBox", &json!({})).unwrap();
let before = s.doc().unwrap().doc.node(a).unwrap().clone();
s.execute("object.transformAgain", &json!({})).unwrap();
let mut want = before;
want.transform(m, false);
let (got, want) = (page(&s, &[a]), want.geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap());
assert!([got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().all(|d| d.abs() < 1e-6), "{got:?} {want:?}");
}
/// A saved step without `basis` was recorded before Scale and Reflect followed the turned box, so a
/// replay of it acts along the page's axes, as it did then, and its new journal entry says so. A
/// step recorded now names its basis and replays along the box. A call without `basis` that is not
/// a replay acts along the box.
#[test]
fn saved_steps_without_a_basis_replay_on_the_page() {
// The turned rectangle after `run` runs on it: its page bounds and its box's angle.
let after = |run: &dyn Fn(&mut Session)| {
let mut s = session();
let a = turned_rect(&mut s);
run(&mut s);
let st = (s.doc().unwrap().doc.bounds_of(&[a], false).unwrap(), angle(&s, a));
(st, s.journal.last().unwrap().clone())
};
let same = |(r, a): (Rect, f64), (q, b): (Rect, f64)| [r.x0 - q.x0, r.y0 - q.y0, r.x1 - q.x1, r.y1 - q.y1, a - b].iter().all(|d| d.abs() < 1e-6);
for (id, p) in [("object.scale", json!({"sx": 200, "sy": 100})), ("object.reflect", json!({"axis": "vertical"}))] {
let mut on_page = p.clone();
on_page["basis"] = json!("page");
let (page, _) = after(&|s| {
s.execute(id, &on_page).unwrap();
});
let (old, (_, noted)) = after(&|s| {
s.replay(id, &p).unwrap();
});
assert!(same(old, page), "{id}: {old:?} {page:?}");
assert_eq!(noted["basis"], "page", "{id}");
let (boxed, (recorded_id, recorded)) = after(&|s| {
s.execute(id, &p).unwrap();
});
assert!(!same(boxed, page) && near(boxed.1, 45.0), "{id}: {boxed:?}");
assert_eq!(recorded["basis"], "box", "{id}");
let (replayed, _) = after(&|s| {
s.replay(&recorded_id, &recorded).unwrap();
});
assert!(same(replayed, boxed), "{id}: {replayed:?} {boxed:?}");
}
}
/// Once Reset Bounding Box squares the box, and for objects standing at different angles, Scale
/// acts along the page's axes.
#[test]
fn scale_follows_the_page_after_a_reset_and_for_mixed_angles() {
let mut s = session();
let a = turned_rect(&mut s);
s.execute("object.resetBoundingBox", &json!({})).unwrap();
let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap();
let w = page(&s, &[a]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let r = page(&s, &[a]);
assert!(near(r.width(), 2.0 * w.width()) && near(r.height(), w.height()), "{w:?} {r:?}");
assert_eq!(angle(&s, a), 0.0);
// A turned rectangle with an upright one: the box is square to the page.
let b = turned_rect(&mut s);
let u = rect(&mut s, 400.0, 100.0, 50.0, 50.0);
sel(&mut s, &[b, u]);
let w = page(&s, &[b, u]);
s.execute("object.scale", &json!({"sx": 100, "sy": 200})).unwrap();
let r = page(&s, &[b, u]);
assert!(near(r.width(), w.width()) && near(r.height(), 2.0 * w.height()), "{w:?} {r:?}");
}
/// With anchors selected, Scale and a named Reflect move the anchors along the page's axes, but
/// with Transform Objects off they move the whole objects' pattern tiles, along the turned box.
#[test]
fn pattern_only_transforms_of_selected_anchors_follow_the_turned_box() {
let c = Point::new(200.0, 200.0);
let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO };
let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2());
let last = |s: &Session| match s.doc().unwrap().last_transform.clone() {
Some(LastTransform::Matrix(m, _)) => m,
other => panic!("no matrix to repeat: {other:?}"),
};
let scale = Affine::scale_non_uniform(2.0, 1.0);
let flip = Affine::scale_non_uniform(-1.0, 1.0);
for (cmd, p, m) in [("object.scale", json!({"sx": 200, "sy": 100}), scale), ("object.reflect", json!({"axis": "vertical"}), flip)] {
for objects in [false, true] {
let mut s = session();
let a = turned_rect(&mut s);
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
let mut p = p.clone();
p["origin"] = json!([c.x, c.y]);
p["objects"] = json!(objects);
p["patterns"] = json!(true);
s.execute(cmd, &p).unwrap();
let want = if objects { about(m) } else { about(frame.conjugate(m)) };
assert!(same_matrix(last(&s), want), "{cmd} objects {objects}: {:?}", last(&s));
}
}
}
#[test]
fn groups_type_and_multiple_selections_keep_their_angle() {
let mut s = session();
File diff suppressed because it is too large Load Diff
+68
View File
@@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() {
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art));
assert!(b.x1 < 95.0, "{b:?}");
assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text");
// An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame.
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap();
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow");
// Release gives the text back.
select(&mut s, &[g]);
s.execute("object.clippingMask.release", &json!({})).unwrap();
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
}
#[test]
fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() {
// The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The
// hidden rectangle does not clip, so clicks inside the clip group still count the type by its
// frame, the counter of the "O" included.
let mut s = session();
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap());
let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap());
let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap();
let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap());
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap();
select(&mut s, &[art, t]);
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
// Make Clipping Mask takes no group on top, so the group goes in place of the type.
let mut d = (*s.doc().unwrap().doc).clone();
let mut rect = (*d.remove(r).unwrap()).clone();
rect.visible = false;
let text = d.remove(t).unwrap();
let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]);
d.insert(Some(g), 0, group).unwrap();
let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf);
let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame");
assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text");
}
#[test]
fn clicks_follow_the_region_a_clipping_paths_effects_give_it() {
// Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves
// 50 pt right: the art shows on the right half, as clicks find it.
let mut s = session();
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap());
let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap());
select(&mut s, &[art, clip]);
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap();
let r = render(&s);
assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region");
assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path");
assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place");
let d = &s.doc().unwrap().doc;
let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None);
assert_eq!(at(75.0), [g]);
assert!(at(25.0).is_empty());
// A marquee across the art's edge reaches it within the moved region only.
let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true);
assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region");
assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place");
// The same with a sublayer that clips by its first object.
let mut d = (**d).clone();
let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec();
let top = d.layers[0].id;
d.remove(g).unwrap();
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
(*children, *clip) = (members, true);
}
d.insert(Some(top), 0, sublayer).unwrap();
let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf);
assert_eq!(leaf(75.0), Some(art));
assert_eq!(leaf(25.0), None);
}
#[test]
fn make_refuses_a_top_object_that_cannot_clip() {
let mut s = session();
+20 -1
View File
@@ -1,6 +1,6 @@
//! Width points, Liquify, Puppet Warp and Perspective Grid commands and tools.
use serde_json::json;
use serde_json::{Value, json};
use vectorcraft_geom::{PathData, Point, Rect, Shape};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
@@ -625,6 +625,25 @@ fn attach_projects_onto_the_plane_and_releases() {
assert_eq!(path(&s, a).bounds().unwrap(), Rect::new(450.0, 300.0, 550.0, 400.0));
}
#[test]
fn a_repeated_id_attaches_moves_and_transforms_an_object_once() {
let edited = |cmd: &str, ids: &[u64], extra: Value| {
let mut s = session();
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
let a = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
let ids: Vec<u64> = ids.iter().map(|_| a.0).collect();
let mut p = json!({"ids": ids, "plane": "right"});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
s.execute(cmd, &p).unwrap();
path(&s, a)
};
let moved = json!({"from": [480.0, 330.0], "to": [500.0, 350.0], "constrain": true});
let scaled = json!({"matrix": [1.5, 0.0, 0.0, 1.5, 10.0, 0.0]});
for (cmd, extra) in [("perspective.attach", json!({})), ("perspective.move", moved), ("perspective.transform", scaled)] {
assert_eq!(edited(cmd, &[0, 0], extra.clone()), edited(cmd, &[0], extra), "{cmd}");
}
}
#[test]
fn rectangle_tool_draws_in_perspective_on_the_active_plane() {
let mut s = session();
+3 -2
View File
@@ -219,9 +219,10 @@ fn rotate_reflect_and_scale_carry_unplaced_gradients() {
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let g = fill_geom(&s, id);
assert!((g.end.x - g.start.x).abs() < 1e-9 && (g.length() - 100.0).abs() < 1e-9, "vertical after a 90° turn: {g:?}");
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap();
let r = fill_geom(&s, id);
// The vertical vector is centred on the object, so the reflection swaps its ends.
// The vertical vector is centred on the object, so the reflection across the page's
// horizontal axis swaps its ends.
assert!(r.start.distance(g.end) < 1e-9 && r.end.distance(g.start) < 1e-9, "{g:?} → {r:?}");
// A circle's radial gradient becomes an ellipse under a non-uniform scale.
+1 -1
View File
@@ -406,7 +406,7 @@ fn a_batch_step_records_what_it_took_from_the_preferences() {
]);
s.execute("command.batch", &json!({ "commands": steps })).unwrap();
let p = &s.journal.last().unwrap().1;
assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false}));
assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false, "basis": "box"}));
// Replayed with other preferences, the scale still scales the stroke.
let r = replayed(&s);
assert!(!r.prefs.scale_strokes);
+36 -1
View File
@@ -248,7 +248,42 @@ fn the_list_shows_each_image_with_its_status() {
assert_eq!(run(&mut s, "links.list", json!({"show": "missing"}))["links"][0]["id"], linked.0);
assert_eq!(run(&mut s, "links.list", json!({"sort": "name"}))["links"][0]["name"], "a.png");
assert!(s.execute("links.list", &json!({"show": "broken"})).is_err());
assert!(s.execute("links.list", &json!({"sort": "size"})).is_err());
assert!(s.execute("links.list", &json!({"sort": "date"})).is_err());
}
#[test]
fn sort_by_size_lists_the_smallest_file_first() {
let dir = Folder::new("list-size");
let files = [("a.png", png(600, 300, RED)), ("b.png", png(10, 10, BLUE)), ("c.png", png(100, 100, RED)), ("d.png", png(10, 10, BLUE))];
let mut s = session();
for (name, bytes) in &files {
let path = dir.file(name);
write(&path, bytes);
place(&mut s, &path);
}
let e = dir.file("e.png");
write(&e, &png(1, 1, RED));
place_embedded(&mut s, &e);
let names = |s: &mut Session| -> Vec<String> {
let l = run(s, "links.list", json!({"sort": "size"}));
l["links"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap_or_default().to_string()).collect()
};
// Smallest first, equal sizes by name, the embedded image (no file) last.
let mut want: Vec<(usize, &str)> = files.iter().map(|(n, b)| (b.len(), *n)).collect();
want.sort();
assert!(want[0].0 < want[2].0 && want[2].0 < want[3].0, "{want:?}");
let mut want: Vec<String> = want.iter().map(|(_, n)| n.to_string()).collect();
want.push("e.png".into());
assert_eq!(names(&mut s), want);
// A missing file sorts by the size the document keeps of it.
std::fs::remove_file(dir.file("a.png")).unwrap();
assert_eq!(names(&mut s), want);
// A modified file sorts by its size now.
let bigger = png(900, 900, BLUE);
assert!(bigger.len() > files[0].1.len());
write(&dir.file("c.png"), &bigger);
let got = names(&mut s);
assert_eq!(got[got.len() - 2..], ["c.png".to_string(), "e.png".to_string()]);
}
#[test]
+147 -1
View File
@@ -2234,6 +2234,10 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")),
("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")),
("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")),
("type.smartPunctuation", json!({"fiLigatures": 1}), switch("fiLigatures")),
("type.smartPunctuation", json!({"flLigatures": "true"}), switch("flLigatures")),
("type.smartPunctuation", json!({"spaces": "on"}), switch("spaces")),
("type.smartPunctuation", json!({"fractions": [true]}), switch("fractions")),
("type.smartPunctuation", json!({"scope": 5}), scope.clone()),
("type.smartPunctuation", json!({"scope": "page"}), scope),
("type.changeCase", json!({"case": 5}), string("case")),
@@ -3563,12 +3567,154 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() {
for id in [t, r] {
select_with_a_step_to_redo(&mut s, &[id]);
let before = history(&s);
assert_eq!(s.execute("type.smartPunctuation", &json!({})).unwrap(), json!({"changed": 0}), "{id:?}");
let r = s.execute("type.smartPunctuation", &json!({})).unwrap();
assert_eq!(r["changed"], 0, "{id:?}");
assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}");
assert_eq!(history(&s), before, "{id:?}");
}
assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…");
}
/// Does the face text `font` draws with have a glyph for every character of `chars`?
fn font_covers(font: &str, chars: &str) -> bool {
let face = vectorcraft_text::FontDb::global().face(font, "Regular");
face.is_some_and(|f| chars.chars().all(|c| f.covers(c)))
}
/// Every option on: the ligatures, Smart Spaces and Expert Fractions, each counted on its own, in
/// one undo step. Fractions next to a digit, a slash or a decimal part are left as they are.
#[test]
fn smart_punctuation_ligatures_spaces_and_fractions_are_counted() {
let mut s = session();
assert!(font_covers("Source Sans 3", "\u{FB00}\u{FB01}\u{FB02}\u{FB03}\u{FB04}½¾"), "Source Sans 3 draws the ligatures and fractions");
let words = "An office's fluffy flow. Then 1/2 and 3/4, not 1/25, 1/2/26 or 1/2.5.";
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let undo = history(&s).0;
let all = json!({"fiLigatures": true, "flLigatures": true, "quotes": true, "spaces": true, "dashes": true, "ellipsis": true, "fractions": true});
let r = s.execute("type.smartPunctuation", &all).unwrap();
assert_eq!(plain(&s, t), "An o\u{FB03}ce’s \u{FB02}u\u{FB00}y \u{FB02}ow. Then ½ and ¾, not 1/25, 1/2/26 or 1/2.5.");
let replaced = json!({"fiLigatures": 2, "flLigatures": 2, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2});
assert_eq!(r, json!({"changed": 1, "replaced": replaced}));
assert_eq!(history(&s).0, undo + 1);
}
/// The ff, fl, ffl option alone leaves fi and ffi as letters (ffi keeps its ff ligature, counted
/// with this option), and the other options are off unless asked for.
#[test]
fn smart_punctuation_fl_ligatures_alone() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "office fit baffle. 1/2", "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"flLigatures": true})).unwrap();
assert_eq!(plain(&s, t), "o\u{FB00}ice fit ba\u{FB04}e. 1/2");
assert_eq!(r["replaced"], json!({"fiLigatures": 0, "flLigatures": 2, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0}));
}
/// A ligature or a fraction the run's font has no glyph for stays as its letters, while the run's
/// other replacements still happen.
#[test]
fn smart_punctuation_skips_ligatures_and_fractions_the_font_lacks() {
let mut s = session();
let mono = "JetBrains Mono";
assert!(!font_covers(mono, "\u{FB01}") && !font_covers(mono, "⅐"), "{mono} has no fi ligature or one-seventh");
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "fit 1/7 a--b", "font": mono})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fiLigatures": true, "fractions": true})).unwrap();
assert_eq!(plain(&s, t), "fit 1/7 a–b");
let counts = (&r["replaced"]["fiLigatures"], &r["replaced"]["fractions"], &r["replaced"]["dashes"]);
assert_eq!(counts, (&json!(0), &json!(0), &json!(1)));
}
/// A fraction at the end of a run is checked against the start of the next run: 1/25 and 1/2.5
/// split after their 1/2 stay as they are, and a 1/2 the next run's space ends is replaced.
#[test]
fn expert_fractions_look_past_the_end_of_a_run() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "1/25 1/2.5 1/2 x", "font": "Source Sans 3"})).unwrap());
for (start, end) in [(0, 3), (5, 8), (11, 14)] {
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": start, "end": end, "size": 30})).unwrap();
}
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
assert_eq!(plain(&s, t), "1/25 1/2.5 ½ x");
assert_eq!(r["replaced"]["fractions"], 1);
}
/// An inline graphic separates the text on either side of it: the space after it is not a second
/// space after the period before it, and the digit before it does not stop a fraction after it.
#[test]
fn an_inline_graphic_separates_smart_spaces_and_fractions() {
let mut s = session();
let r = rect(&mut s, 600.0, 500.0, 10.0, 10.0);
sel(&mut s, &[r]);
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "A. B 71/2", "font": "Source Sans 3"})).unwrap());
s.execute("text.insertInline", &json!({"id": t.0, "at": 7, "symbol": "Mark"})).unwrap();
s.execute("text.insertInline", &json!({"id": t.0, "at": 3, "symbol": "Mark"})).unwrap();
let texts = |s: &Session| match node(s, t).kind {
NodeKind::Text(o) => o.runs.iter().map(|r| if r.inline.is_some() { "[g]".to_string() } else { r.text.clone() }).collect::<String>(),
_ => String::new(),
};
assert_eq!(texts(&s), "A. [g] B 7[g]1/2");
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fractions": true})).unwrap();
assert_eq!(texts(&s), "A. [g] B 7[g]½");
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fractions"]), (&json!(0), &json!(1)));
}
/// Smart Spaces keeps one space after each period, also when the spaces start in the next run,
/// and leaves single spaces and spaces after other characters alone.
#[test]
fn smart_spaces_keeps_one_space_after_a_period() {
let mut s = session();
let t = text(&mut s, "A. B. C. D E");
// "C." is in a run of its own, and the spaces after it start the next one.
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": 8, "end": 10, "size": 30})).unwrap();
assert!(matches!(node(&s, t).kind, NodeKind::Text(ref o) if o.runs.len() > 1));
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "quotes": false, "dashes": false, "ellipsis": false})).unwrap();
assert_eq!(plain(&s, t), "A. B. C. D E");
assert_eq!(r["replaced"]["spaces"], 2);
}
/// Ruby stays on the characters it was set on when Smart Punctuation makes the text before them
/// longer (curly quotes) or shorter (Smart Spaces), and no replacement takes in characters on both
/// sides of a ruby span's end: the fi with ruby on its i stays as letters, and a second space after
/// a period with ruby of its own stays.
#[test]
fn smart_punctuation_keeps_ruby_on_its_characters() {
let mut s = session();
let spans = |s: &Session, t| match node(s, t).kind {
NodeKind::Text(o) => o.ruby.iter().map(|r| (r.start, r.end)).collect::<Vec<_>>(),
_ => vec![],
};
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "'A'. base fit X. Y", "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
for (start, end) in [(1, 2), (6, 10), (12, 13), (18, 19)] {
s.execute("type.ruby", &json!({"text": "r", "start": start, "end": end})).unwrap();
}
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fiLigatures": true})).unwrap();
assert_eq!(plain(&s, t), "‘A’. base fit X. Y");
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fiLigatures"]), (&json!(1), &json!(0)));
let text = plain(&s, t);
let on: Vec<&str> = spans(&s, t).into_iter().map(|(a, b)| &text[a..b]).collect();
assert_eq!(on, ["A", "base", "i", " "]);
}
/// Expert Fractions leaves a fraction next to a digit of another script as it is.
#[test]
fn expert_fractions_skip_fractions_next_to_digits_of_any_script() {
let mut s = session();
let words = "\u{662}1/2 1/2\u{662} 1/2.\u{662} 1/2";
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
assert_eq!(plain(&s, t), "\u{662}1/2 1/2\u{662} 1/2.\u{662} ½");
assert_eq!(r["replaced"]["fractions"], 1);
}
#[test]
fn convert_point_area_roundtrip() {
let mut s = session();
+72
View File
@@ -775,6 +775,78 @@ fn create_outlines_draws_the_type_objects_own_paint() {
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
}
/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled
/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20
/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space).
fn transformed_gradient_type(s: &mut Session, fill: Value) -> NodeId {
let t = run(s, "text.create", json!({"x": 30, "y": 110, "text": "HIH", "size": 40}))["id"].as_u64().unwrap();
run(s, "select.set", json!({"ids": [t]}));
run(s, "type.ruby", json!({"text": "ab"}));
run(s, "text.setFormat", json!({"ids": [t], "underline": true, "strikethrough": true}));
run(s, "paint.setFill", fill);
run(s, "paint.setStroke", json!({"color": "#008000"}));
run(s, "stroke.set", json!({"weight": 2}));
run(s, "object.scale", json!({"ids": [t], "sx": 150, "sy": 150}));
run(s, "object.rotate", json!({"ids": [t], "angle": 20}));
NodeId(t)
}
/// Create Outlines draws what the type drew: a gradient on the characters that has no vector of
/// its own keeps one gradient across every glyph, ruby glyph and bar, fitted to the layout's box,
/// and one with a vector keeps it where it was, both with the type's scale and rotation. The
/// characters' stroke keeps the weight it was drawn at.
#[test]
fn create_outlines_keeps_a_character_gradient_across_the_type() {
let placed = json!({"gradient": {"kind": "linear", "start": [40, 100], "end": [110, 100],
"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}});
for fill in [red_blue(), placed] {
let mut s = session();
let t = transformed_gradient_type(&mut s, fill.clone());
let NodeKind::Text(text) = &node(&s, t).kind else { panic!("not type") };
assert!(!text.ruby.is_empty() && text.runs.iter().all(|r| r.style.underline && r.style.strikethrough), "{fill}");
// The characters' stroke is kept in text space and drawn scaled by the type's transform.
let weight = text.runs[0].style.stroke_layer().width;
let drawn = weight * vectorcraft_doc::Scaling::factor(text.xf).unwrap_or(1.0);
assert!((drawn - weight).abs() > 0.1, "the type's transform scales: {weight} {drawn}");
let before = render(&s);
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 60, "{fill}: {n} pixels differ");
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
// Every glyph, ruby glyph and bar takes the same gradient, placed, and the stroke at the
// weight it was drawn at.
let mut gradients = vec![];
let mut widths = vec![];
node(&s, NodeId(g)).walk(&mut |c: &Node| {
if let Paint::Gradient(gr) = c.appearance.fill_paint() {
gradients.push(gr.clone());
}
widths.extend(c.appearance.stroke().map(|st| st.width));
});
assert!(gradients.len() >= 6, "{fill}: three glyphs, ruby and two bars: {}", gradients.len());
assert!(gradients.iter().all(|gr| gr.is_placed() && *gr == gradients[0]), "{fill}: {gradients:?}");
assert!(widths.len() == gradients.len() && widths.iter().all(|w| (w - drawn).abs() < 1e-9), "{fill}: {drawn} {widths:?}");
}
}
/// Expand outlines the type before its fills expand, so a gradient on its characters that has no
/// vector of its own expands across the whole type, as the canvas draws it, and the query reports
/// it.
#[test]
fn expand_keeps_a_character_gradient_across_the_type() {
let mut s = session();
transformed_gradient_type(&mut s, red_blue());
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(true), json!(true), json!(true)), "{info}");
let before = render(&s);
run(&mut s, "object.expand", json!({}));
let after = render(&s);
assert_eq!(gradients_and_type(&s), (0, 0), "outlined and expanded");
let d = mean_diff(&before, &after);
assert!(d < 0.5, "{d}");
}
/// `object.expand.info` reports the type object's own stroke, pattern fill and gradient fill, which
/// Object turns into paths of its whole outline: a gradient only when that outline's box needs no
/// more runs than are written.
+273
View File
@@ -0,0 +1,273 @@
//! Automatic Plane Positioning: Shift held over an anchor point of art in perspective or over a
//! gridline intersection moves the active plane through it for now (`perspective.plane.infer`),
//! the two Perspective Grid Options that turn the targets on and off, and what ends it.
use serde_json::json;
use vectorcraft_geom::{Point, Vec2};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::tests_persp_select::{attached, bounds_of, drag, grid, persp_session, plane_pts, undo_len};
use crate::*;
fn shift() -> Mods {
Mods { shift: true, ..Default::default() }
}
/// The top anchor of path `id` (on the right wall at depth 0): its page point and its height.
fn top_anchor(s: &Session, id: NodeId) -> (Point, f64) {
let page: Vec<Point> = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
let plane = plane_pts(s, id, Plane::Right, 0.0);
page.into_iter().zip(plane).map(|(p, q)| (p, q.y)).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap()
}
fn hover(s: &mut Session, p: Point, mods: Mods) {
s.pointer(&PointerEvent::new(PointerKind::Move, p.x, p.y).with_mods(mods), ViewInfo::default()).unwrap();
}
fn revision(s: &Session) -> u64 {
s.doc().unwrap().revision
}
#[test]
fn shift_over_an_anchor_holds_the_active_plane_at_its_height_until_an_object_is_drawn() {
let (mut s, id) = persp_session();
let v = ViewInfo::default();
let (anchor, height) = top_anchor(&s, id);
assert!(height > 10.0, "{height}");
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
s.select_tool("perspectiveSelection", v).unwrap();
let steps = undo_len(&s);
// Without Shift the pointer only hovers.
hover(&mut s, anchor, Mods::default());
assert_eq!(grid(&s).inferred, None);
hover(&mut s, anchor, shift());
let g = grid(&s);
assert!(g.inferred.is_some());
assert!((g.offset(Plane::Ground) - height).abs() < 1e-6, "{} {height}", g.offset(Plane::Ground));
assert_eq!((g.ground_offset, g.shown_planes(), undo_len(&s)), (0.0, vec![Plane::Ground], steps));
// Held there already, another hover over the anchor changes nothing.
let rev = revision(&s);
hover(&mut s, anchor, shift());
assert_eq!(revision(&s), rev);
// The Rectangle tool draws on the plane where it is held, and the plane stays put for the drag.
s.select_tool("rectangle", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 400.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 470.0, 430.0), v).unwrap();
assert!(grid(&s).inferred.is_some(), "held while the object is drawn");
s.pointer(&PointerEvent::new(PointerKind::Up, 470.0, 430.0), v).unwrap();
let drawn = s.doc().unwrap().selection.objects[0];
assert_ne!(drawn, id);
let (plane, depth) = attached(&s, drawn).unwrap();
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
// Drawn, the plane is back in its place and the other planes show: one undo step for the drag.
let g = grid(&s);
assert_eq!((g.inferred, g.offset(Plane::Ground), g.shown_planes().len(), undo_len(&s)), (None, 0.0, 3, steps + 1));
// Undoing the drag holds the plane again; Escape with the Perspective Selection tool ends that.
s.execute("edit.undo", &json!({})).unwrap();
assert!(grid(&s).inferred.is_some());
s.select_tool("perspectiveSelection", v).unwrap();
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert_eq!(grid(&s).inferred, None);
}
#[test]
fn shift_during_a_drag_still_constrains_the_move() {
let (mut s, id) = persp_session();
let v = ViewInfo::default();
s.select_tool("perspectiveSelection", v).unwrap();
let before = plane_pts(&s, id, Plane::Right, 0.0);
let h = grid(&s).homography(Plane::Right).unwrap();
// From the middle of the object, along the wall and a little up.
let start = bounds_of(&before).center();
let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap());
drag(&mut s, &[from, to, to], shift());
assert_eq!(grid(&s).inferred, None, "with a button down Shift constrains the move");
for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) {
assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "{a:?} → {b:?}");
}
}
#[test]
fn a_gridline_intersection_brings_each_plane_made_active_through_it() {
let (mut s, _) = persp_session();
let (g, steps) = (grid(&s), undo_len(&s));
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
let at = g.to_page(Plane::Left, Point::new(3.0 * g.cell, 2.0 * g.cell)).unwrap();
let r = s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y], "tolerance": 1})).unwrap();
assert_eq!((r["active"].as_bool(), r["source"].as_str(), r["plane"].as_str()), (Some(true), Some("gridline"), Some("left")));
for (got, want) in r["point"].as_array().unwrap().iter().zip([0.0, 2.0 * g.cell, 3.0 * g.cell]) {
assert!((got.as_f64().unwrap() - want).abs() < 1e-6, "{r}");
}
for (plane, want) in [("ground", 2.0 * g.cell), ("right", 3.0 * g.cell), ("left", 0.0)] {
s.execute("perspective.plane.set", &json!({"plane": plane})).unwrap();
let r = s.execute("perspective.plane.infer", &json!({})).unwrap();
assert!((r["offset"].as_f64().unwrap() - want).abs() < 1e-6 && r["active"] == json!(true) && r.get("source").is_none(), "{plane}: {r}");
}
let held = grid(&s);
assert_eq!((held.left_offset, held.right_offset, held.ground_offset, undo_len(&s)), (0.0, 0.0, 0.0, steps));
// Nothing within reach leaves the plane where it is held.
let rev = revision(&s);
let mid = held.to_page(Plane::Left, Point::new(3.5 * g.cell, 2.5 * g.cell)).unwrap();
let r = s.execute("perspective.plane.infer", &json!({"at": [mid.x, mid.y], "tolerance": 0.5})).unwrap();
assert!(r["active"] == json!(true) && r.get("source").is_none() && revision(&s) == rev, "{r}");
// With no active plane nothing is held.
s.execute("perspective.plane.set", &json!({"plane": "none"})).unwrap();
assert_eq!(grid(&s).inferred, None);
assert!(s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y]})).is_err(), "no active plane");
assert_eq!(s.execute("perspective.plane.infer", &json!({})).unwrap()["active"], json!(false));
}
#[test]
fn the_two_options_turn_the_targets_on_and_off_and_are_kept() {
let (mut s, id) = persp_session();
assert!(s.prefs.perspective_widget.anchor_point && s.prefs.perspective_widget.gridline_intersection, "both on by default");
let (anchor, _) = top_anchor(&s, id);
let infer = |s: &mut Session| s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01}));
assert_eq!(infer(&mut s).unwrap()["source"], json!("anchor"));
s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap();
let r = s.execute("perspective.widget.options", &json!({"anchorPoint": false})).unwrap();
assert_eq!((r["anchorPoint"].as_bool(), r["gridlineIntersection"].as_bool(), r["show"].as_bool()), (Some(false), Some(true), Some(true)));
assert!(infer(&mut s).unwrap().get("source").is_none(), "the anchor is no target now");
assert_eq!(grid(&s).inferred, None);
let back: Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
assert!(!back.perspective_widget.anchor_point && back.perspective_widget.gridline_intersection);
s.execute("perspective.widget.options", &json!({"gridlineIntersection": false})).unwrap();
assert!(infer(&mut s).is_err(), "both off");
for bad in [json!({"anchorPoint": "yes"}), json!({"gridlineIntersection": 1})] {
assert!(s.execute("perspective.widget.options", &bad).is_err(), "{bad}");
}
assert!(!s.prefs.perspective_widget.anchor_point, "a refused value changes nothing");
s.execute("prefs.set", &json!({"key": "perspectiveWidget", "value": {"anchorPoint": true}})).unwrap();
assert!(s.prefs.perspective_widget.anchor_point && !s.prefs.perspective_widget.gridline_intersection);
// Preferences saved before the options existed read as both on.
let old: vectorcraft_tools::distort::perspective::widget::WidgetOptions = serde_json::from_value(json!({"show": false})).unwrap();
assert!(old.anchor_point && old.gridline_intersection && !old.show);
}
#[test]
fn bad_params_are_refused_and_leave_the_grid_as_it_is() {
let (mut s, id) = persp_session();
let (anchor, _) = top_anchor(&s, id);
let rev = revision(&s);
for bad in [
json!({"at": "here"}),
json!({"at": [1]}),
json!({"at": [anchor.x, anchor.y], "tolerance": -1}),
json!({"at": [anchor.x, anchor.y], "tolerance": "wide"}),
json!({"at": [anchor.x, anchor.y], "clear": true}),
json!({"clear": "yes"}),
] {
assert!(s.execute("perspective.plane.infer", &bad).is_err(), "{bad}");
}
assert_eq!((grid(&s).inferred, revision(&s)), (None, rev));
// Clearing when nothing is held changes nothing.
assert_eq!(s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap()["active"], json!(false));
assert_eq!(revision(&s), rev);
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
assert!(s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y]})).is_err(), "hidden grid");
}
/// A session whose ground plane is held at the height of the attached rectangle's top anchor.
fn held_session() -> (Session, NodeId, f64) {
let (mut s, id) = persp_session();
let (anchor, height) = top_anchor(&s, id);
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
let r = s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})).unwrap();
assert_eq!(r["source"], json!("anchor"));
(s, id, height)
}
#[test]
fn attaching_an_object_ends_it_and_the_object_sits_where_the_plane_was_held() {
let (mut s, _, height) = held_session();
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
let flat = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.attach", &json!({"ids": [flat.0]})).unwrap();
let (plane, depth) = attached(&s, flat).unwrap();
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
assert_eq!((grid(&s).inferred, grid(&s).ground_offset), (None, 0.0));
// An attach of nothing, or to a plane it doesn't hold, leaves it held.
let (mut s, ..) = held_session();
s.execute("perspective.attach", &json!({"ids": []})).unwrap();
assert!(grid(&s).inferred.is_some());
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
let other = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.attach", &json!({"ids": [other.0], "plane": "right"})).unwrap();
assert_eq!(attached(&s, other).map(|a| a.0), Some(Plane::Right));
assert!(grid(&s).inferred.is_some());
// A move of an object already in perspective leaves it held; one brought into perspective ends it.
let (mut s, id, height) = held_session();
s.execute("perspective.move", &json!({"ids": [id.0], "from": [460, 400], "to": [470, 400]})).unwrap();
assert!(grid(&s).inferred.is_some());
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
let flat = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.move", &json!({"ids": [flat.0], "from": [430, 410], "to": [440, 410]})).unwrap();
let (plane, depth) = attached(&s, flat).unwrap();
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
assert_eq!(grid(&s).inferred, None);
}
#[test]
fn moving_a_plane_hiding_the_grid_and_reopening_the_file_end_it() {
// A moved plane moves from where it is held and is placed there for good, in one undo step;
// undoing the move holds it again.
let (mut s, _, height) = held_session();
let steps = undo_len(&s);
s.execute("perspective.plane.move", &json!({"plane": "ground", "by": 10})).unwrap();
let g = grid(&s);
assert_eq!((g.inferred, undo_len(&s)), (None, steps + 1));
assert!((g.ground_offset - (height + 10.0)).abs() < 1e-6, "{}", g.ground_offset);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).inferred.is_some(), grid(&s).ground_offset), (true, 0.0));
// A refused move leaves it held.
let (mut s, ..) = held_session();
assert!(s.execute("perspective.plane.move", &json!({"plane": "ground", "offset": 1, "objects": "all"})).is_err());
assert!(grid(&s).inferred.is_some());
// A plane dragged while it is held, then the drag canceled, is held again.
let (mut s, ..) = held_session();
s.begin_interaction("Move Plane").unwrap();
s.preview("perspective.plane.move", &json!({"plane": "ground", "by": 20})).unwrap();
assert_eq!(grid(&s).inferred, None);
s.cancel_interaction().unwrap();
assert!(grid(&s).inferred.is_some());
// Move Plane to Match Object.
let (mut s, id, _) = held_session();
s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap();
assert_eq!((grid(&s).inferred, grid(&s).plane), (None, Plane::Right));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).inferred.is_some(), grid(&s).plane), (true, Plane::Ground), "undo holds it again");
// With the plane placed at the object already, matching only puts the held plane back there.
s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap();
assert!(grid(&s).inferred.is_some());
let steps = undo_len(&s);
s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap();
assert_eq!((grid(&s).inferred, grid(&s).offset(Plane::Right), undo_len(&s)), (None, 0.0, steps));
// Hide Grid.
let (mut s, ..) = held_session();
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
assert_eq!(grid(&s).inferred, None);
// The grid's definition changing leaves it held, and it is not `perspective.grid.set`'s to set.
let (mut s, ..) = held_session();
let held = grid(&s).inferred;
s.execute("perspective.grid.set", &json!({"cell": 31, "inferred": [1, 2, 3]})).unwrap();
assert_eq!(grid(&s).inferred, held);
// `perspective.grid.set` hiding the grid or choosing no plane ends it.
for patch in [json!({"visible": false}), json!({"plane": "none"})] {
let (mut s, ..) = held_session();
s.execute("perspective.grid.set", &patch).unwrap();
assert_eq!(grid(&s).inferred, None, "{patch}");
}
// Another preset leaves it held, as other changes to the grid's definition do.
let (mut preset, ..) = held_session();
let before = grid(&preset).inferred;
preset.execute("perspective.grid.preset", &json!({"kind": 3})).unwrap();
assert_eq!((grid(&preset).kind, grid(&preset).inferred), (3, before));
// A file saved while a plane is held opens with the plane in its place.
let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false);
let back = vectorcraft_format::load(&saved).unwrap();
assert!(PerspectiveGrid::positioning(&back), "the saved file still holds the point");
s.add_document(back, None);
assert_eq!(grid(&s).inferred, None);
assert_eq!(grid(&s).cell, 31.0);
}
+4 -1
View File
@@ -520,7 +520,10 @@ fn the_plane_widget_stays_on_screen_and_takes_clicks_with_any_tool() {
click(&mut s, q, view);
assert_eq!(grid(&s).plane, Plane::Ground);
// Perspective Grid Options move it to another corner or hide it.
assert_eq!(run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), json!({"show": true, "position": "bottomRight"}));
assert_eq!(
run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})),
json!({"show": true, "position": "bottomRight", "anchorPoint": true, "gridlineIntersection": true})
);
let r = face(&s, view, WidgetCorner::BottomRight, Plane::Left);
assert!(r.x > 100.0 + 450.0 && r.y > 50.0 + 300.0, "{r:?}");
click(&mut s, r, view);
@@ -599,6 +599,100 @@ fn with_link_a_pdf_page_places_linked() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// The colour at the centre of `r` in `doc`.
fn colour_at(doc: &Document, r: Rect) -> [u8; 3] {
let img = vectorcraft_render::Renderer::new().render_region(doc, r, 1.0, true);
let [red, g, b, _] = img.pixel((r.width() / 2.0) as u32, (r.height() / 2.0) as u32);
[red, g, b]
}
#[test]
fn link_pages_opens_each_picked_pdf_page_as_a_linked_placed_document() {
let dir = Folder::new("open-pdf-link-pages");
let src = dir.file("flyer.pdf");
pdf_source(&src, "pdf", &[RED, BLUE, RED], 0);
let mut s = Session::new();
let r = s.execute("document.open", &json!({"path": src, "linkPages": true, "pages": "2-3"})).unwrap();
assert_eq!((r["format"].as_str(), r["restored"].as_bool()), (Some("pdf"), Some(false)), "{r}");
let st = s.doc().unwrap();
assert_eq!(st.path, None, "Save asks for a name instead of writing over the PDF");
let d = &st.doc;
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(136.0, 0.0, 236.0, 50.0)]);
let layers: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(layers, ["Page 2", "Page 3"]);
let mut ids = vec![];
for (layer, (page, board)) in d.layers.iter().zip([(2, boards[0]), (3, boards[1])]) {
let kids = layer.children().unwrap();
assert_eq!(kids.len(), 1);
let p = placed(&s, kids[0].id);
assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(page), false), "{p:?}");
assert_eq!(bounds(&s, kids[0].id), board);
ids.push(kids[0].id);
}
assert!(near(colour_at(d, boards[0]), BLUE));
assert!(near(colour_at(d, boards[1]), RED));
let links = s.execute("links.list", &json!({})).unwrap()["links"].clone();
assert_eq!(links.as_array().map(Vec::len), Some(2), "{links}");
assert!(links.as_array().unwrap().iter().all(|row| row["document"] == true && row["status"] == "ok"), "{links}");
// Embed makes a page editable art.
s.execute("links.embed", &json!({"ids": [ids[0].0]})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(ids[0]).unwrap().kind_label(), "Clip Group");
assert_eq!(bounds(&s, ids[0]), boards[0]);
assert!(near(colour_at(d, boards[0]), BLUE));
// Every page, with the art's bounds as the artboard.
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards.len(), 3);
assert!(d.layers.iter().flat_map(|l| l.children().unwrap()).all(|n| matches!(&n.kind, NodeKind::PlacedDocument(p) if p.bounding)));
}
#[test]
fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
use vectorcraft_testkit::pdf::{PdfPage, pdf};
let dir = Folder::new("open-pdf-link-pages-cmyk");
let src = dir.file("cmyk.pdf");
let page = || PdfPage::new(100.0, 50.0, "0 0.5 1 0 k 0 0 100 50 re f");
write(&src, &pdf(&[page(), page(), page()], None));
let mut s = Session::new();
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.color_mode, vectorcraft_doc::ColorMode::Cmyk, "pages painted in CMYK open as a CMYK document");
let blobs: Vec<_> = d.images.values().map(|b| b.bytes.clone()).collect();
assert_eq!(blobs.len(), 3);
assert!(blobs.iter().all(|b| std::sync::Arc::ptr_eq(b, &blobs[0])), "one copy of the file for every page");
s.execute("document.open", &json!({"path": src, "linkPages": true, "colorMode": "rgb"})).unwrap();
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
}
#[test]
fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() {
let dir = Folder::new("open-pdf-link-pages-refused");
let src = dir.file("flyer.pdf");
pdf_source(&src, "pdf", &[RED, BLUE], 0);
let bytes = std::fs::read(&src).unwrap();
let logo = dir.file("logo.vectorcraft");
source(&logo, 100.0, 50.0, RED, 0);
let mut s = Session::new();
let cases = [
(json!({"name": "flyer.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "linkPages": true}), "needs the file's path"),
(json!({"path": logo, "linkPages": true}), "isn't a PDF"),
(json!({"path": src, "linkPages": true, "password": "secret"}), "password"),
(json!({"path": src, "linkPages": true, "textAs": "outlines"}), "textAs: outlines"),
(json!({"path": src, "linkPages": "yes"}), "linkPages must be true or false"),
(json!({"path": src, "linkPages": true, "pages": "3"}), "pages:"),
];
for (p, says) in cases {
let e = s.execute("document.open", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
assert!(s.documents().is_empty(), "nothing opened");
// Off, the pages open as editable art.
s.execute("document.open", &json!({"path": src, "linkPages": false})).unwrap();
assert!(!s.doc().unwrap().doc.has_placed());
}
#[test]
fn a_changed_pdf_is_modified_and_update_links_reads_it_again() {
let dir = Folder::new("placed-pdf-update");
+1
View File
@@ -1700,6 +1700,7 @@ fn filters_set_effects_and_stroke_styles() {
("test.engine.badn", json!([{"id": "plugin.test.engine.fx", "params": {"n": "two"}}]), "`n`"),
("test.engine.file", json!([{"id": "distort.glass", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"),
("test.engine.file2", json!([{"id": "texture.texturizer", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"),
("test.engine.file3", json!([{"id": "artistic.roughPastels", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"),
("test.engine.two3d", json!([{"id": "threeD.extrude"}, {"id": "threeD.extrude"}]), "one 3D effect"),
] {
let e = filter(&mut s, name, fx).unwrap_err().to_string();
+53 -4
View File
@@ -143,19 +143,22 @@ fn listed_applied_edited_and_undone() {
}
}
// Numbers far out of range are stored as given and read clamped; the canvas still draws.
// Radial Blur's Blur Center is refused outside 0 to 1 instead.
let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY");
for (id, _) in EFFECTS {
let defaults = vectorcraft_render::effects::default_params(id).unwrap();
let junk: serde_json::Map<String, Value> = defaults
.as_object()
.unwrap()
.iter()
.filter(|(_, v)| v.is_number())
.filter(|(k, v)| v.is_number() && !center(id, k))
.enumerate()
.map(|(i, (k, _))| (k.clone(), json!(if i % 2 == 0 { 1e308 } else { -1e308 })))
.collect();
assert!(!junk.is_empty(), "{id}");
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": junk})).unwrap();
}
assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err());
let _ = render(&s);
let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone();
assert_eq!(n.appearance.effects.len(), 3);
@@ -320,8 +323,7 @@ fn glass_loads_a_texture_saves_it_and_draws_it() {
assert_eq!(doc.node(NodeId(g)).unwrap().appearance.effects[0].params, glass_params(&s, g));
assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels);
// The same file by path, through Effect Options, stores the same texture.
let dir = std::env::temp_dir().join(format!("vc-glass-texture-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dir = vectorcraft_testkit::TempDir::new("glass-texture");
let path = dir.join("rings.png");
std::fs::write(&path, &png).unwrap();
let (mut t, h) = striped();
@@ -331,7 +333,7 @@ fn glass_loads_a_texture_saves_it_and_draws_it() {
assert_eq!(glass_params(&t, h)["textureImage"], json!(stored));
assert_eq!(glass_params(&t, h)["texture"], json!("loaded"));
assert_eq!(render(&t).pixels, loaded.pixels);
let _ = std::fs::remove_dir_all(&dir);
drop(dir);
// The stored string is taken as it is (as effect.list gives it, and a graphic style copies it).
t.execute("effect.apply", &json!({"effect": "distort.glass", "ids": [h], "params": {"textureImage": stored, "texture": "frosted"}})).unwrap();
let second = t.doc().unwrap().doc.node(NodeId(h)).unwrap().appearance.effects[1].params.clone();
@@ -388,6 +390,53 @@ fn texturizer_loads_a_texture_and_draws_it() {
assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels);
}
/// Effect › Artistic › Rough Pastels › Load Texture: an image file, given as bytes or by path, is
/// stored with the effect and picked; it draws as the surface, a save and open keeps it, a file
/// that isn't an image is refused without a change, and undo takes it away.
#[test]
fn rough_pastels_loads_a_texture_saves_it_and_draws_it() {
let png = rings_png();
let data = vectorcraft_format::base64_encode(&png);
let (mut s, g) = striped();
let file = json!({"name": "rings.png", "dataBase64": data});
s.execute("effect.apply", &json!({"effect": "artistic.roughPastels", "ids": [g], "params": {"relief": 20, "textureImage": file}})).unwrap();
let p = glass_params(&s, g);
assert_eq!(p["texture"], json!("loaded"), "loading a texture picks it");
let stored = p["textureImage"].as_str().unwrap().to_string();
assert_eq!(vectorcraft_render::effects::pixel::texture(&stored).unwrap().size(), (12, 10));
let loaded = render(&s);
for (_, builtin) in vectorcraft_render::effects::pixel::TEXTURES {
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"texture": builtin}})).unwrap();
assert!(mean_diff(&loaded, &render(&s)) > 0.001, "{builtin}");
}
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"texture": "loaded"}})).unwrap();
assert_eq!(render(&s).pixels, loaded.pixels, "the texture stayed with the effect");
let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!(doc.node(NodeId(g)).unwrap().appearance.effects[0].params, glass_params(&s, g));
assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels);
// A file that isn't an image changes nothing.
let junk = vectorcraft_format::base64_encode(b"not an image");
let before = glass_params(&s, g);
let e = s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"textureImage": {"dataBase64": junk}}})).unwrap_err();
assert!(e.to_string().contains("textureImage"), "{e}");
let e = s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"textureImage": 5}})).unwrap_err();
assert!(e.to_string().contains("textureImage"), "{e}");
assert_eq!(glass_params(&s, g), before);
// The same file by path, through Effect Options, stores the same texture; undo takes it away.
let dir = vectorcraft_testkit::TempDir::new("rough-pastels-texture");
let path = dir.join("rings.png");
std::fs::write(&path, &png).unwrap();
let (mut t, h) = striped();
t.execute("effect.apply", &json!({"effect": "artistic.roughPastels", "ids": [h], "params": {"relief": 20}})).unwrap();
assert!(glass_params(&t, h).get("textureImage").is_none());
t.execute("effect.setParams", &json!({"index": 0, "ids": [h], "params": {"textureImage": {"path": path.to_string_lossy()}}})).unwrap();
drop(dir);
assert_eq!((&glass_params(&t, h)["textureImage"], &glass_params(&t, h)["texture"]), (&json!(stored), &json!("loaded")));
assert_eq!(render(&t).pixels, loaded.pixels);
t.execute("edit.undo", &json!({})).unwrap();
assert!(glass_params(&t, h).get("textureImage").is_none(), "undone");
}
#[test]
fn spin_blur_reaches_past_the_corners() {
let (mut s, g) = striped();
+1 -1
View File
@@ -216,7 +216,7 @@ fn the_journal_records_the_scale_options_used() {
run(&mut s, "object.scale", json!({"sx": 150}));
let (cmd, p) = s.journal.last().unwrap().clone();
assert_eq!(cmd, "object.scale");
assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true}));
assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true, "basis": "box"}));
// An explicit value stays; moves don't scale, so they record nothing.
run(&mut s, "object.scale", json!({"sx": 150, "strokes": true}));
assert_eq!(s.journal.last().unwrap().1["strokes"], json!(true));
+176
View File
@@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() {
assert_eq!((out.contains("<image"), out.contains("<feBlend")), (image, !image), "{mode}: {out}");
}
}
/// The `defaults` of `svgFilter.list`: each one's name and whether the document holds it.
fn defaults(s: &mut Session) -> Vec<(String, bool)> {
let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default();
listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect()
}
/// Every document lists the default filters without holding them; applying one adds the effect and
/// the document's copy in one undo step.
#[test]
fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() {
use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS;
let mut s = session();
let listed = defaults(&mut s);
assert_eq!(listed.len(), DEFAULT_FILTERS.len());
assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them");
assert!(names(&mut s).is_empty());
let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap();
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false}));
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = steps(&s);
let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"}));
assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0)));
assert_eq!(steps(&s), before + 1, "the effect and the copy are one step");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
assert_eq!(names(&mut s), ["Soft Shadow"]);
assert_eq!(drawn(&s, a), json!(soft.xml));
assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true)));
// Applied again, the document's copy is the filter: nothing more is added.
run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]}));
assert_eq!(names(&mut s), ["Soft Shadow"]);
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect");
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
run(&mut s, "edit.redo", json!({}));
assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml)));
// Nothing to apply it to: no copy and no step.
let mut s = session();
assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected");
assert!(names(&mut s).is_empty());
assert_eq!(steps(&s), 0);
assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly");
}
/// With a full history, applying a default lets one old step go, as any edit does: the copy joins
/// the step that applied it, and one Undo takes both back.
#[test]
fn a_default_applied_with_a_full_history_is_still_one_step() {
let mut s = session();
s.active_mut().unwrap().history.limit = 3;
let a = rect(&mut s, 10.0);
rect(&mut s, 30.0);
rect(&mut s, 50.0);
assert_eq!(steps(&s), 3);
run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]}));
// The application takes one place in the history: only the oldest step went.
assert_eq!(steps(&s), 3);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
run(&mut s, "edit.undo", json!({}));
assert!(names(&mut s).is_empty(), "the copy is undone with the effect");
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
}
/// Edit SVG Filter on a default saves the edited copy in the document under the default's name;
/// the document's filter then stands in the default's place, and deleting it lists the default again.
#[test]
fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() {
use vectorcraft_render::effects::svg_filter::defaults::default_filter;
let mut s = session();
let glow = default_filter("Glow").unwrap();
// Saved with its own code: nothing to keep, and no undo step.
run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"}));
assert_eq!((names(&mut s).len(), steps(&s)), (0, 0));
let edited = r#"<filter id="Renamed"><feGaussianBlur stdDeviation="9"/></filter>"#;
assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow");
assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1));
assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter");
let kept = r#"<filter id="Glow"><feGaussianBlur stdDeviation="9"/></filter>"#;
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name");
// Applying the name now applies the document's filter.
let a = rect(&mut s, 10.0);
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]}));
assert_eq!(drawn(&s, a), json!(kept));
// Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default.
run(&mut s, "svgFilter.delete", json!({"name": "Glow"}));
assert_eq!(drawn(&s, a), json!(""));
assert!(defaults(&mut s).contains(&("Glow".to_string(), false)));
// The default itself is not deleted.
let before = steps(&s);
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter"));
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named"));
assert_eq!(steps(&s), before);
// Applied again, the default is copied back, and the object that named it draws with it.
let b = rect(&mut s, 50.0);
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]}));
assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml)));
assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application");
// A new filter may take a default's name the document does not hold.
let mut s = session();
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Invert"><feOffset dx="1"/></filter>"#}));
assert!(defaults(&mut s).contains(&("Invert".to_string(), true)));
// An unknown name is still refused.
assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\""));
}
/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in
/// the same undo step; any other effect keeps its place.
#[test]
fn apply_with_an_index_replaces_an_applied_filter() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]}));
run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]}));
let before = steps(&s);
let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null}));
assert_eq!(r["ids"], json!([a.0]));
assert_eq!(steps(&s), before + 1, "one step");
let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone();
assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather"));
assert_eq!(names(&mut s), ["Shift", "Invert"]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&mut s), ["Shift"]);
assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift");
// Not an SVG filter, no effect there, or not an index: refused, and the default is not copied.
let before = steps(&s);
for (index, why) in [
(json!(1), "applied SVG filter"),
(json!(7), "applied SVG filter"),
(json!("x"), "`index`"),
(json!(-1), "`index`"),
(json!(null), "`index`"),
] {
let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null}));
assert!(e.contains(why), "{index}: {e}");
}
assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before));
}
/// A default needs room in the document: at 64 filters applying one is refused, and a filter the
/// document holds still applies.
#[test]
fn a_full_document_refuses_a_default_it_does_not_hold() {
let mut s = session();
let a = rect(&mut s, 10.0);
for i in 0..64 {
run(&mut s, "svgFilter.define", json!({"xml": format!("<filter id=\"f{i}\"><feOffset/></filter>")}));
}
let before = steps(&s);
assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters"));
let edited = r#"<filter id="Glow"><feOffset dx="2"/></filter>"#;
assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters"));
assert_eq!(steps(&s), before);
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]}));
}
/// A default applied in one document is written to SVG as a filter and read back from the native
/// format with the document's copy.
#[test]
fn an_applied_default_survives_svg_export_and_a_native_round_trip() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]}));
let out = svg(&mut s);
assert!(out.contains("<feColorMatrix") && out.contains("saturate"), "{out}");
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
assert!(back.any_node(|n| n.appearance.effects.iter().any(|e| e.id == "svg.filter")), "SVG import reads the filter back");
let doc = s.doc().unwrap().doc.clone();
let again = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(again.svg_filters, doc.svg_filters);
assert_eq!(again.svg_filters[0].name, "Grayscale");
}
+103 -41
View File
@@ -2265,6 +2265,36 @@ fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n'));
}
#[test]
fn remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames() {
for command in ["object.lock", "object.hide"] {
for held_first in [false, true] {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
let (held, other) = if held_first { (a, b) } else { (b, a) };
let unrelated = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap();
let unrelated = NodeId(unrelated);
s.execute(command, &json!({"ids": [held.0]})).unwrap();
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let case = format!("{command}, held first: {held_first}");
let steps = undo_labels(&s).len();
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step");
assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed");
let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text());
assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "{case}: every frame's returns go");
assert_eq!(obj(&s, unrelated).plain_text(), "One\nTwo", "{case}: other type is as it was");
// No return is left: another call fails and adds no undo step.
assert!(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).is_err());
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text");
}
}
}
#[test]
fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
@@ -2306,41 +2336,72 @@ fn convert_to_text_takes_the_whole_story_that_select_all_selected() {
}
}
/// Whether no paragraph of type `id` is a list.
fn no_list(s: &Session, id: NodeId) -> bool {
let t = obj(s, id);
(0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none())
}
/// The bullets held as characters in the frames `ids`.
fn bullet_chars(s: &Session, ids: &[NodeId]) -> usize {
ids.iter().map(|id| obj(s, *id).plain_text().matches("\u{2022}\t").count()).sum()
}
#[test]
fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() {
// Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story.
for named in [false, true] {
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
s.execute("object.lock", &json!({"ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
// The first frame ends with a paragraph return, so the paragraph that starts the locked
// frame takes in the first frame's empty last part and starts its text there.
let in_a = obj(&s, a).plain_text();
assert!(in_a.ends_with('\n'));
let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count();
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})");
assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert");
assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0)));
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted");
let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count();
assert_eq!(markers, own, "the locked frame's first paragraph keeps its list");
// The converted text is longer, so the story flows on into the locked frame; its own
// paragraphs stay a list.
let last = tb.paragraph_count() - 2;
assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})");
assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n"));
assert!(s.tool_options().get("story").is_some(), "the whole story stays selected");
fn convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames() {
// Over MCP without ids, as the Paragraph panel sends it with every frame of the story, and with
// ids naming only the held frame.
for command in ["object.lock", "object.hide"] {
for held_first in [false, true] {
for call in ["none", "story", "held"] {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
let (held, other) = if held_first { (a, b) } else { (b, a) };
let unrelated =
s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap();
let unrelated = NodeId(unrelated);
s.execute("text.setFormat", &json!({"ids": [unrelated.0], "list": "bullet"})).unwrap();
let unrelated_before = obj(&s, unrelated);
s.execute(command, &json!({"ids": [held.0]})).unwrap();
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let case = format!("{command}, held first: {held_first}, ids: {call}");
let p = match call {
"none" => json!({}),
"story" => json!({"ids": [a.0, b.0]}),
_ => json!({"ids": [held.0]}),
};
let steps = undo_labels(&s).len();
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step");
assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed");
assert!(no_list(&s, held), "{case}: the held frame leaves its list");
assert_eq!(obj(&s, unrelated), unrelated_before, "{case}: other type is as it was");
if call == "held" {
// The other frame's paragraphs whose text starts there keep their list.
assert!(!no_list(&s, other), "{case}: the frame not named keeps its list");
continue;
}
assert!(no_list(&s, other), "{case}: the other frame leaves its list");
assert_eq!(bullet_chars(&s, &[a, b]), 12, "{case}: each paragraph's bullet is held once as characters");
assert!(s.tool_options().get("story").is_some(), "{case}: the whole story stays selected");
// Nothing is a list any more: another call changes nothing and adds no undo step.
s.execute("text.convertListToText", &p).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text");
assert!(!no_list(&s, a) && !no_list(&s, b), "{case}: undo restores the lists");
}
}
}
}
#[test]
fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() {
for named in [false, true] {
fn convert_to_text_of_the_whole_story_converts_a_paragraph_that_runs_across_a_locked_frame() {
// The paragraph that runs from the first frame into the second starts in the locked frame, or
// ends in it.
for (named, lock_first) in [(false, true), (true, true), (false, false), (true, false)] {
let mut s = session();
let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40));
let a = NodeId(
@@ -2354,22 +2415,23 @@ fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked
s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap();
let in_a = obj(&s, a).plain_text();
assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second");
s.execute("object.lock", &json!({"ids": [a.0]})).unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let (locked, other) = if lock_first { (a, b) } else { (b, a) };
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let case = format!("ids named: {named}, first frame locked: {lock_first}");
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})");
// The two paragraphs that start in the editable frame, and the empty one that ends the story.
assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert");
assert_eq!(r["ids"], json!([a.0, b.0]), "{case}: both frames are changed");
// The five paragraphs with text, and the empty one that ends the story.
assert_eq!(r["converted"], json!(6), "{case}: every paragraph of the story converts");
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was");
assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list");
assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list");
assert!(!tb.plain_text().starts_with('\u{2022}'));
assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2);
assert!(no_list(&s, a) && no_list(&s, b), "{case}: the story leaves its list");
assert_eq!(bullet_chars(&s, &[a, b]), 5, "{case}: each paragraph's bullet is held once as characters");
assert!(ta.plain_text().contains("\u{2022}\tGamma"), "{case}: the paragraph across the frames takes its bullet where its text starts");
assert!(!tb.plain_text().starts_with('\u{2022}'), "{case}");
}
}
+290 -80
View File
@@ -2284,7 +2284,7 @@ fn a_variable_library_defines_text_variables_and_data_sets() {
assert_eq!(r["variables"], json!(["Name", "Note"]));
assert_eq!((r["deleted"].clone(), r["deletedDataSets"].clone()), (json!([]), json!([])));
assert_eq!(r["names"], json!(["Row 1", "Row 2"]));
assert_eq!((r["skipped"].clone(), r.get("warning")), (json!([]), None));
assert_eq!((r.get("skipped"), r.get("warning")), (None, None));
let listed = s.execute("variable.list", &json!({})).unwrap();
assert_eq!(listed["variables"], json!([{"name": "Name", "kind": "text", "bindings": 0}, {"name": "Note", "kind": "text", "bindings": 0}]));
let sets = s.execute("dataset.list", &json!({})).unwrap();
@@ -2405,13 +2405,14 @@ fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() {
s.execute("variable.loadLibrary", &json!({"xml": other})).unwrap();
assert_eq!(super::history(&s), (undo + 1, 0, true));
// While the variables are locked, a library without text variables still loads its data sets,
// and loading it again changes nothing.
// While the variables are locked, a library of the variables the document has, with their
// kinds, still loads its data sets, and loading it again changes nothing.
let mut s = session();
let t = text(&mut s, "Alice");
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let xml = library(&[("Shown", "other")], &[("B", &[])]);
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
super::select_with_a_step_to_redo(&mut s, &[t]);
let before = super::history(&s);
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
@@ -2432,22 +2433,89 @@ fn a_refused_variable_library_deletes_nothing() {
assert_eq!(s.doc().unwrap().doc.variables, before);
}
/// A library's variables of other kinds are left out with their values, named in `skipped` and
/// in a warning that gives each kind once with its count; its text variables load.
/// A library of every kind, in the layout the public grammar gives: visibility (`visibility`),
/// image (`fileref`) and graph (`graphdata`) variables beside a text variable, a variable without a
/// `trait` and one whose `trait` VectorCraft doesn't know, with values in the forms
/// [`a_variable_library_defines_every_kind_with_its_values`] reads.
fn every_kind_library() -> String {
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<!DOCTYPE svg [<!ENTITY ns_vars \"http://ns.adobe.com/Variables/1.0/\"><!ENTITY ns_custom \"http://ns.adobe.com/GenericCustomNamespace/1.0/\">]>\n\
<svg><variableSets xmlns=\"&ns_vars;\"><variableSet varSetName=\"binding1\" locked=\"none\"><variables>\
<variable varName=\"Name\" trait=\"textcontent\"/><variable varName=\"Shown\" trait=\"visibility\"/>\
<variable varName=\"Photo\" trait=\"fileref\"/><variable varName=\"Chart\" trait=\"graphdata\"/>\
<variable varName=\"Loose\"/><variable varName=\"Odd\" trait=\"somethingelse\"/></variables>\
<v:sampleDataSets xmlns:v=\"&ns_vars;\" xmlns=\"&ns_custom;\">\
<v:sampleDataSet dataSetName=\"A\"><Name><p>Bravo</p></Name><Shown>true</Shown>\
<Photo>\n\t\tfile:////Users/me/Art%20Work/logo%23one.png\n\t\t</Photo>\
<Chart><data numDataColumns=\"3\"><propertyRow key=\"name\"><value></value><value type=\"string\">North</value><value type=\"string\">South</value></propertyRow>\
<values><row><value key=\"name\" type=\"string\">Q1</value><value>10</value><value>2.5</value></row>\
<row><value key=\"name\">2024</value><value></value><value>-4</value></row></values></data></Chart>\
<Loose></Loose><Odd>ignored</Odd></v:sampleDataSet>\
<v:sampleDataSet dataSetName=\"B\"><Shown> FALSE </Shown><Photo>C:\\Art\\logo.png</Photo>\
<Chart><data numDataColumns=\"2\"><values><row><value key=\"name\"></value><value>7</value><value>8</value></row></values></data></Chart></v:sampleDataSet>\
<v:sampleDataSet dataSetName=\"C\"><Shown/><Photo> </Photo><Chart>\n</Chart></v:sampleDataSet>\
</v:sampleDataSets></variableSet></variableSets></svg>\n"
.to_string()
}
/// Load Variable Library defines a library's variables of every kind, unbound, with their values:
/// a visibility value from `true` or `false` in any case, an image value from a file's absolute
/// path or a `file:` URL (escapes decoded, the white space round it left out, the file not read),
/// and a graph value from a `data` element, as the CSV Graph Data takes (series from its
/// `propertyRow`, a category from each row's `key="name"` value, blanks where a row has no
/// number). A variable without a `trait`, or with one VectorCraft doesn't know, is defined of
/// unknown kind, without values. An element holding only white space gives no value.
#[test]
fn a_variable_library_leaves_out_variables_that_are_not_text() {
fn a_variable_library_defines_every_kind_with_its_values() {
let mut s = session();
let xml = library(
&[("Shown", "kindB"), ("Name", "textcontent"), ("Photo", "kindC"), ("Other", "kindB")],
&[("A", &[("Shown", &["true"]), ("Name", &["Bravo"]), ("Photo", &["a.png"])])],
);
let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!(r["variables"], json!(["Name"]));
assert_eq!(r["skipped"], json!([{"name": "Shown", "trait": "kindB"}, {"name": "Photo", "trait": "kindC"}, {"name": "Other", "trait": "kindB"}]));
assert_eq!(r["warning"], "variables that aren't text were left out: kindB (2), kindC (1)");
let r = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap();
assert_eq!(r["variables"], json!(["Name", "Shown", "Photo", "Chart", "Loose", "Odd"]));
let vars = &s.doc().unwrap().doc.variables;
assert_eq!(vars.variables.len(), 1);
assert_eq!(vars.dataset("A").map(|d| d.values.len()), Some(1));
let kinds: Vec<(&str, &str)> = vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect();
assert_eq!(kinds, [("Name", "text"), ("Shown", "visibility"), ("Photo", "image"), ("Chart", "graph"), ("Loose", "unknown"), ("Odd", "unknown")]);
assert!(vars.bindings.is_empty());
use vectorcraft_doc::DataValue::{Graph, Image, Text, Visible};
let a = &vars.dataset("A").unwrap().values;
assert_eq!(a.get("Name"), Some(&Text("Bravo".into())));
assert_eq!(a.get("Shown"), Some(&Visible(true)));
assert_eq!(a.get("Photo"), Some(&Image("/Users/me/Art Work/logo#one.png".into())));
assert_eq!(a.get("Chart"), Some(&Graph(",North,South\nQ1,10,2.5\n\"2024\",,-4".into())));
assert_eq!((a.get("Loose"), a.get("Odd")), (None, None));
let b = &vars.dataset("B").unwrap().values;
assert_eq!((b.get("Shown"), b.get("Photo")), (Some(&Visible(false)), Some(&Image("C:\\Art\\logo.png".into()))));
assert_eq!(b.get("Chart"), Some(&Graph(",,\n7,8".into())));
assert!(vars.dataset("C").unwrap().values.is_empty(), "{:?}", vars.dataset("C"));
}
/// A library's visibility, image and graph variables drive the art they are bound to: a variable
/// the document already has with the same name and kind stays bound (#4136), so selecting a
/// library's data set shows or hides the object, swaps the linked image's path and replaces the
/// graph's data. A variable of the same name and another kind is replaced, and its bindings go.
#[test]
fn a_variable_library_keeps_bound_variables_of_every_kind() {
let mut s = session();
let r = rect(&mut s);
let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",a\nX,1"})).unwrap()["id"]
.as_u64()
.unwrap();
for (name, kind, id) in [("Shown", "visibility", r.0), ("Chart", "graph", graph), ("Photo", "text", r.0)] {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
if kind != "text" {
s.execute("variable.bind", &json!({"variable": name, "ids": [id]})).unwrap();
}
}
let loaded = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap();
assert_eq!(loaded["deleted"], json!(["Photo"]), "Photo is an image variable in the library");
let listed = s.execute("variable.list", &json!({})).unwrap();
let bindings: Vec<(String, u64)> =
listed["variables"].as_array().unwrap().iter().map(|v| (v["name"].as_str().unwrap().to_string(), v["bindings"].as_u64().unwrap())).collect();
assert_eq!(bindings.iter().find(|(n, _)| n == "Shown").map(|b| b.1), Some(1));
assert_eq!(bindings.iter().find(|(n, _)| n == "Chart").map(|b| b.1), Some(1));
s.execute("dataset.select", &json!({"name": "B"})).unwrap();
let doc = &s.doc().unwrap().doc;
assert!(!doc.node(r).unwrap().visible, "Shown is false in B");
let csv = doc.node(NodeId(graph)).and_then(|n| n.extras().graph.as_ref()).map(|g| g.to_csv());
assert_eq!(csv.as_deref(), Some(",,\n7,8\n"), "B's graph data");
}
/// A library that isn't one, or that breaks its grammar or the caps, is refused, and the document
@@ -2477,12 +2545,36 @@ fn malformed_variable_libraries_are_refused() {
"&big;".repeat(8000),
" ".repeat(300_000)
);
// A library of one variable `Shown` of the trait given, and a data set holding `value`.
let kind_value = |t: &str, value: &str| {
format!(
"<variableSets><variableSet><variables><variable varName=\"Shown\" trait=\"{t}\"/></variables>\
<sampleDataSets><sampleDataSet dataSetName=\"A\">{value}</sampleDataSet></sampleDataSets></variableSet></variableSets>"
)
};
// A library graph value of more rows or series than a graph holds.
let rows_past = format!("<Shown><data><values>{}</values></data></Shown>", "<row><value>1</value></row>".repeat(10_001));
let series_past =
format!("<Shown><data><values><row><value key=\"name\">Q</value>{}</row></values></data></Shown>", "<value>1</value>".repeat(257));
// 2,000 rows of 20 values of eight digits are more CSV than a graph value holds.
let row = format!("<row>{}</row>", "<value>12345678</value>".repeat(20));
let long_graph = format!("<Shown><data><values>{}</values></data></Shown>", row.repeat(2_000));
let cases = [
("not well-formed XML", "<variableSets><variableSet>".to_string()),
("no `variableSets` element", "<svg><variables/></svg>".to_string()),
("declares no variables", "<variableSets><variableSet><variables/></variableSet></variableSets>".to_string()),
("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])),
("has no `trait`", ok.replace(" trait=\"textcontent\"", "")),
("for `Shown` that isn't `true` or `false`", kind_value("visibility", "<Shown>maybe</Shown>")),
("for `Shown` that isn't `true` or `false`", kind_value("visibility", "<Shown><p>true</p></Shown>")),
("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "<Shown>logo.png</Shown>")),
("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "<Shown>C:logo.png</Shown>")),
("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "<Shown>file:logo.png</Shown>")),
("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "<Shown>1,2</Shown>")),
("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "<Shown><values/></Shown>")),
("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "<Shown><data/><data/></Shown>")),
("graph value for `Shown` longer than 262144 bytes", kind_value("graphdata", &long_graph)),
("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &rows_past)),
("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &series_past)),
("missing `varName`", ok.replace("varName=\"Name\"", "varName=\" \"")),
("missing `dataSetName`", ok.replace(" dataSetName=\"A\"", "")),
("data set `A` is declared twice", library(&[("Name", "textcontent")], &[("A", &[]), ("A", &[])])),
@@ -2531,51 +2623,50 @@ fn a_variable_library_expands_entities_of_plain_text() {
assert_eq!(value, Some(vectorcraft_doc::DataValue::Text("x-y \"z\"-x&a;".into())));
}
/// Save Variable Library writes what Load Variable Library reads back: the text variables in their
/// order, every data set by name and in order, and each text value as it was, with several lines,
/// markup characters, quotes, a carriage return and an empty value. Variables of other kinds are
/// left out with their values, named in `skipped` and in the warning. The library is written while
/// the variables are locked too, to a file with `path`.
/// Save Variable Library writes what Load Variable Library reads back: the variables of every kind
/// in their order, every data set by name and in order, and each value as it was: text with several
/// lines, markup characters, quotes, a carriage return and an empty value; visibility values;
/// image paths with spaces, markup characters, `%`, `#` and letters past ASCII, from a Unix root,
/// a drive and a share; and graph data with series, categories, a numeric category and blanks. A
/// variable of unknown kind is declared without a `trait` and loads back as one. The library is
/// written while the variables are locked too, to a file with `path`.
#[test]
fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() {
fn a_saved_variable_library_loads_back_every_variable_and_data_set() {
let mut s = session();
let t = text(&mut s, "Alice");
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Badge", "visibility")] {
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph"), ("Badge", "visibility")]
{
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
}
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
s.execute("dataset.new", &json!({"name": "First", "values": {"Name": "Bravo", "Note": "One\nTwo & <three>\r\n'four' \"five\"", "Shown": true}}))
.unwrap();
s.execute("dataset.new", &json!({"name": "Say \"hi\" & <go>\tnow", "values": {"Name": "", "Photo": "a.png"}})).unwrap();
let chart = ",North,\"S, \"\"q\"\"\"\nQ1,10,2.5\n\"2024\",,-4";
let first = json!({"Name": "Bravo", "Note": "One\nTwo & <three>\r\n'four' \"five\"", "Shown": true, "Photo": "/Users/me/Art & <Work> 100%/#1 ü.png", "Chart": chart});
s.execute("dataset.new", &json!({"name": "First", "values": first})).unwrap();
let second = json!({"Name": "", "Photo": "C:\\Art\\logo.png", "Badge": false, "Chart": ",,\n7,8"});
s.execute("dataset.new", &json!({"name": "Say \"hi\" & <go>\tnow", "values": second})).unwrap();
s.execute("dataset.new", &json!({"name": "Share", "values": {"Photo": "\\\\server\\share\\a.png"}})).unwrap();
s.execute("dataset.new", &json!({"name": "Empty"})).unwrap();
// A file can declare a variable of unknown kind, which no command defines.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
.variables
.variables
.push(vectorcraft_doc::Variable { name: "Loose name".into(), kind: vectorcraft_doc::VariableKind::Unknown });
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let before = s.doc().unwrap().doc.variables.clone();
let saved = s.execute("variable.saveLibrary", &json!({})).unwrap();
assert_eq!(saved["variables"], json!(["Name", "Note"]));
assert_eq!(saved["datasets"], json!(3));
assert_eq!(
saved["skipped"],
json!([{"name": "Shown", "kind": "visibility"}, {"name": "Photo", "kind": "image"}, {"name": "Badge", "kind": "visibility"}])
);
assert_eq!(saved["warning"], "variables that aren't text were left out: visibility (2), image (1)");
assert_eq!(saved["variables"], json!(["Name", "Shown", "Note", "Photo", "Chart", "Badge", "Loose name"]));
assert_eq!(saved["datasets"], json!(4));
assert_eq!((saved.get("skipped"), saved.get("warning")), (None, None));
assert_eq!(s.doc().unwrap().doc.variables, before, "saving changes nothing");
let mut other = session();
let loaded = other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap();
assert_eq!((loaded["skipped"].clone(), loaded.get("warning")), (json!([]), None));
other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap();
let vars = &other.doc().unwrap().doc.variables;
assert_eq!(vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect::<Vec<_>>(), [("Name", "text"), ("Note", "text")]);
let text_only: Vec<vectorcraft_doc::DataSet> = before
.datasets
.iter()
.map(|d| {
let mut d = d.clone();
d.values.retain(|k, _| k == "Name" || k == "Note");
d
})
.collect();
assert_eq!(vars.datasets, text_only);
assert_eq!(vars.variables, before.variables);
assert_eq!(vars.datasets, before.datasets);
// Saving the loaded library again writes the same file.
assert_eq!(other.execute("variable.saveLibrary", &json!({})).unwrap()["xml"], saved["xml"]);
let dir = Folder::new("vars-save-library");
let path = dir.file("library.xml");
@@ -2585,19 +2676,78 @@ fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() {
assert_eq!(std::fs::read_to_string(&path).unwrap(), saved["xml"].as_str().unwrap());
let mut from_file = session();
from_file.execute("variable.loadLibrary", &json!({"path": path})).unwrap();
assert_eq!(from_file.doc().unwrap().doc.variables.datasets, text_only);
assert_eq!(from_file.doc().unwrap().doc.variables.datasets, before.datasets);
}
/// Graph data whose categories are all blank keeps them through a save and a load, and so does
/// graph data of series names without rows; graph data with neither is refused. An image value
/// written as a `file:/…` URL without a host loads as its path, graph data with more series than a
/// graph holds is refused, and wide graph data is checked against the size cap as it is written.
#[test]
fn saved_graph_values_and_file_urls_load_back_at_their_edges() {
let mut s = session();
s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\n\"\",1\n\"\",2"}})).unwrap();
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
assert!(xml.contains("<row><value key=\"name\" type=\"string\"></value><value>1</value></row>"), "{xml}");
let mut other = session();
other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets);
// Series names without rows load back, and graph data with neither is refused.
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ",North,South"}})).unwrap();
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone();
let mut other = session();
other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets);
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ","}})).unwrap();
let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
assert!(e.contains("graph value for `Chart` without rows or series"), "{e}");
let url = "<variableSets><variableSet><variables><variable varName=\"Photo\" trait=\"fileref\"/></variables><sampleDataSets>\
<sampleDataSet dataSetName=\"A\"><Photo>file:/tmp/logo%20one.png</Photo></sampleDataSet>\
<sampleDataSet dataSetName=\"B\"><Photo>file:/C:/Art/logo.png</Photo></sampleDataSet></sampleDataSets></variableSet></variableSets>";
let mut s = session();
s.execute("variable.loadLibrary", &json!({"xml": url})).unwrap();
let image = |set: &str| s.doc().unwrap().doc.variables.dataset(set).and_then(|d| d.values.get("Photo")).cloned();
assert_eq!(image("A"), Some(vectorcraft_doc::DataValue::Image("/tmp/logo one.png".into())));
assert_eq!(image("B"), Some(vectorcraft_doc::DataValue::Image("C:/Art/logo.png".into())));
// More series than a graph holds are refused.
let mut s = session();
s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
let wide = (0..257).map(|i| i.to_string()).collect::<Vec<_>>().join(",");
s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": wide}})).unwrap();
let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
assert!(e.contains("graph value for `Chart` with more than 10000 rows or 256 series"), "{e}");
// One row of 256 values and 1,000 rows of one: every row is written 256 values wide.
let mut csv = (0..256).map(|i| i.to_string()).collect::<Vec<_>>().join(",");
for i in 0..1_000 {
csv += &format!("\n{i}");
}
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv.clone()}})).unwrap();
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
assert_eq!(xml.matches("<row>").count(), 1_001);
assert!(xml.contains("<data numDataColumns=\"256\">"));
// Rows that make the library larger than 8 MiB are refused as each is written.
for i in 1_000..9_000 {
csv += &format!("\n{i}");
}
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv}})).unwrap();
let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
assert!(e.contains("larger than 8388608 bytes"), "{e}");
}
/// The library is the XML of the public grammar: a document type declaration with the namespace
/// entities, `variableSets` › `variableSet` › `variables` with a `textcontent` variable per text
/// variable, and `sampleDataSets` with a `sampleDataSet` per data set, holding an element per text
/// variable it has a value for, with a `p` element per line. Markup characters, a carriage return,
/// and a tab or quote in a data set name are escaped. A document with text variables and no data
/// sets writes an empty `sampleDataSets`.
/// entities, `variableSets` › `variableSet` › `variables` with a variable per variable, its `trait`
/// and `category` those of its kind, and `sampleDataSets` with a `sampleDataSet` per data set,
/// holding an element per variable it has a value for: a `p` element per line of a text value,
/// `true` or `false`, a `file:` URL for an image's path from a Unix root, and a `data` element for
/// graph data. Markup characters, a carriage return, and a tab or quote in a data set name are
/// escaped. A document with variables and no data sets writes an empty `sampleDataSets`.
#[test]
fn a_saved_variable_library_has_the_library_layout() {
let mut s = session();
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text")] {
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph")] {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
}
let head = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
@@ -2605,13 +2755,17 @@ fn a_saved_variable_library_has_the_library_layout() {
\t<!ENTITY ns_vars \"http://ns.adobe.com/Variables/1.0/\">\n\
\t<!ENTITY ns_custom \"http://ns.adobe.com/GenericCustomNamespace/1.0/\">\n\
\t<!ENTITY ns_flows \"http://ns.adobe.com/Flows/1.0/\">\n\
\t<!ENTITY ns_graphs \"http://ns.adobe.com/Graphs/1.0/\">\n\
]>\n\
<svg>\n\
<variableSets xmlns=\"&ns_vars;\">\n\
\t<variableSet varSetName=\"binding1\" locked=\"none\">\n\
\t\t<variables>\n\
\t\t\t<variable varName=\"Name\" trait=\"textcontent\" category=\"&ns_flows;\"></variable>\n\
\t\t\t<variable varName=\"Shown\" trait=\"visibility\" category=\"&ns_vars;\"></variable>\n\
\t\t\t<variable varName=\"Note\" trait=\"textcontent\" category=\"&ns_flows;\"></variable>\n\
\t\t\t<variable varName=\"Photo\" trait=\"fileref\" category=\"&ns_vars;\"></variable>\n\
\t\t\t<variable varName=\"Chart\" trait=\"graphdata\" category=\"&ns_graphs;\"></variable>\n\
\t\t</variables>\n\
\t\t<v:sampleDataSets xmlns:v=\"&ns_vars;\" xmlns=\"&ns_custom;\">\n";
let tail = "\t\t</v:sampleDataSets>\n\t</variableSet>\n</variableSets>\n</svg>\n";
@@ -2619,7 +2773,8 @@ fn a_saved_variable_library_has_the_library_layout() {
assert_eq!(empty["xml"].as_str().unwrap(), format!("{head}{tail}"));
assert_eq!(empty["datasets"], json!(0));
s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": {"Name": "x\r\ny < z", "Shown": false}})).unwrap();
let values = json!({"Name": "x\r\ny < z", "Shown": false, "Photo": "/art/a b.png", "Chart": ",S\nQ1,1\n2,"});
s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": values})).unwrap();
s.execute("dataset.new", &json!({"name": "C", "values": {"Note": ""}})).unwrap();
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
let sets = "\t\t\t<v:sampleDataSet dataSetName=\"A &amp;&#9;&quot;B&quot;\">\n\
@@ -2627,6 +2782,17 @@ fn a_saved_variable_library_has_the_library_layout() {
\t\t\t\t\t<p>x&#13;</p>\n\
\t\t\t\t\t<p>y &lt; z</p>\n\
\t\t\t\t</Name>\n\
\t\t\t\t<Shown>false</Shown>\n\
\t\t\t\t<Photo>file:////art/a%20b.png</Photo>\n\
\t\t\t\t<Chart>\n\
\t\t\t\t\t<data numDataColumns=\"2\">\n\
\t\t\t\t\t\t<propertyRow key=\"name\"><value></value><value type=\"string\">S</value></propertyRow>\n\
\t\t\t\t\t\t<values>\n\
\t\t\t\t\t\t\t<row><value key=\"name\" type=\"string\">Q1</value><value>1</value></row>\n\
\t\t\t\t\t\t\t<row><value key=\"name\">2</value><value></value></row>\n\
\t\t\t\t\t\t</values>\n\
\t\t\t\t\t</data>\n\
\t\t\t\t</Chart>\n\
\t\t\t</v:sampleDataSet>\n\
\t\t\t<v:sampleDataSet dataSetName=\"C\">\n\
\t\t\t\t<Note>\n\
@@ -2636,10 +2802,11 @@ fn a_saved_variable_library_has_the_library_layout() {
assert_eq!(xml, format!("{head}{sets}{tail}"));
}
/// Save Variable Library refuses a document without variables or without text variables, a text
/// variable whose name can't name an element, a data set name or text value with a character XML
/// can't hold, a name that Load Variable Library would read differently or refuse, and a library
/// past the caps that Load Variable Library reads. A refused save writes no file.
/// Save Variable Library refuses a document without variables, a variable whose name can't name an
/// element (but for a variable of unknown kind), a data set name, text value or graph label with a
/// character XML can't hold, an image value that isn't a file's absolute path, a name that Load
/// Variable Library would read differently or refuse, and a library past the caps that Load
/// Variable Library reads. A refused save writes no file.
#[test]
fn save_variable_library_refuses_what_a_library_cant_hold() {
let dir = Folder::new("vars-save-refused");
@@ -2652,14 +2819,41 @@ fn save_variable_library_refuses_what_a_library_cant_hold() {
let mut s = session();
refused(&mut s, "define a variable first");
// A library without text variables is saved.
s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap();
refused(&mut s, "holds text variables, and the document has none");
assert_eq!(s.execute("variable.saveLibrary", &json!({})).unwrap()["variables"], json!(["Shown"]));
for name in ["First Name", "1st", "a:b", "x/y", "-dash"] {
for (name, kind) in [("First Name", "text"), ("1st", "visibility"), ("a:b", "image"), ("x/y", "graph"), ("-dash", "text")] {
let mut s = session();
s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap();
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
refused(&mut s, &format!("variable `{name}` can't be saved in a variable library"));
}
// No element is named after a variable of unknown kind, so its name can be any name.
let mut s = session();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
.variables
.variables
.push(vectorcraft_doc::Variable { name: "First \"Name\" & <x>".into(), kind: vectorcraft_doc::VariableKind::Unknown });
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone();
let mut other = session();
other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!(other.doc().unwrap().doc.variables.variables, s.doc().unwrap().doc.variables.variables);
// An image value that isn't a file's absolute path, which Load Variable Library refuses.
for path in ["a.png", "C:a.png", "C:\\a.png ", "/"] {
let mut s = session();
s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.push(vectorcraft_doc::DataSet {
name: "A".into(),
values: [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into(),
});
refused(&mut s, "data set `A` holds an image value for `Photo` that isn't a file's absolute path");
}
// A graph label with a character XML can't hold.
let mut s = session();
s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\u{1}\nQ1,1"}})).unwrap();
refused(&mut s, "data set `A` holds a control character");
for name in ["Ünïcode", "_x", "a.b-c_d", "名前"] {
let mut s = session();
s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap();
@@ -2757,10 +2951,10 @@ fn a_saved_variable_library_near_the_size_cap_loads_back() {
/// While the variables are locked, a library that would delete or define a variable is refused, as
/// Delete Variable and New Variable are, and the document keeps its variables and data sets. That
/// covers a library without text variables loaded into a document with variables, and one that
/// adds a text variable to the document's. A library of the document's own text variables, and
/// one without text variables loaded into a document without variables, delete and define none:
/// they load, replacing the data sets.
/// covers a library of other variables loaded into a document with variables, one that adds a
/// variable to the document's, one that declares a document variable's name with another kind, and
/// any library loaded into a document without variables. A library of the document's own variables
/// with their kinds deletes and defines none: it loads, replacing the data sets.
#[test]
fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
let mut s = session();
@@ -2768,7 +2962,7 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Old"}})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let before = s.doc().unwrap().doc.variables.clone();
for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..]] {
for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..], &[("Name", "visibility")][..]] {
let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "variable.loadLibrary" && why == "variables are locked"), "{e}");
assert_eq!(s.doc().unwrap().doc.variables, before);
@@ -2780,13 +2974,13 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
let mut s = session();
s.execute("dataset.new", &json!({"name": "A"})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let e = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Name", "textcontent")], &[])})).unwrap_err();
assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}");
let r = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Shown", "other")], &[("B", &[])])})).unwrap();
assert_eq!((r["deletedDataSets"].clone(), r["names"].clone()), (json!(["A"]), json!(["B"])));
for vars in [&[("Name", "textcontent")][..], &[("Shown", "other")][..]] {
let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}");
}
let vars = &s.doc().unwrap().doc.variables;
assert!(vars.variables.is_empty() && vars.locked);
assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["B"]);
assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["A"]);
}
/// A graph variable's data set applies its CSV as `graph.setData` does: a right-axis series the row's data no longer
@@ -3109,6 +3303,10 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
let head = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\">";
let art = "<rect x=\"1\" y=\"1\" width=\"5\" height=\"5\"/></svg>";
let untraited = format!("{head}<variableSets><variableSet><variables><variable varName=\"A\"/></variables></variableSet></variableSets>{art}");
let relative = format!(
"{head}<variableSets><variableSet><variables><variable varName=\"T\" trait=\"textcontent\"/><variable varName=\"A\" trait=\"fileref\"/></variables>\
<sampleDataSets><sampleDataSet dataSetName=\"D\"><T><p>kept</p></T><A>a.png</A></sampleDataSet></sampleDataSets></variableSet></variableSets>{art}"
);
let refs = "&ns_big;".repeat(40_000);
let big = "x".repeat(250);
let growing = format!(
@@ -3164,11 +3362,23 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(o.doc().unwrap().doc.variables.variables.len(), 1);
for (svg, why) in [(untraited, "variable `A` has no `trait`"), (growing, "entities expand to more than")] {
let (o, warnings) = svg_opened(&svg, "broken.svg");
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}");
let d = &o.doc().unwrap().doc;
assert!(d.variables.variables.is_empty());
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
}
// A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds
// that aren't text.
let (o, warnings) = svg_opened(&untraited, "untraited.svg");
assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}");
assert!(o.doc().unwrap().doc.variables.variables.is_empty());
// The values of the other kinds aren't read, so one that Load Variable Library would refuse
// leaves the text variables and their values as they open.
let (o, warnings) = svg_opened(&relative, "relative.svg");
assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}");
let vars = &o.doc().unwrap().doc.variables;
assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]);
assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into()));
let (o, warnings) = svg_opened(&growing, "broken.svg");
let why = "entities expand to more than";
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}");
let d = &o.doc().unwrap().doc;
assert!(d.variables.variables.is_empty());
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
}