mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 09:21:55 +01:00
Merge main into feat/stylus-wheel
This commit is contained in:
commit
faffba01ae
150 files changed
+10189
-1008
No files matched your search
@@ -1367,6 +1367,28 @@ fn smooth_tool_reduces_jagged_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0));
|
||||
}
|
||||
|
||||
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
|
||||
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
|
||||
/// does not reach keeps its anchors selected, and undo brings the old selection back.
|
||||
#[test]
|
||||
fn smoothing_a_path_drops_its_direct_selected_anchors() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": 200.0 + if i % 2 == 0 { 0.0 } else { 1.5 }})).collect();
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let other = line(&mut s, 100.0, 500.0, 300.0, 500.0);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 38]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
drag(&mut s, "smooth", &[(90.0, 200.0), (200.0, 200.0), (310.0, 200.0)], Mods::default());
|
||||
assert!(path(&s, id).anchor_count() < 20, "the path is smoothed");
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert!(sel.contains(id) && sel.contains(other), "{sel:?}");
|
||||
assert!(!sel.anchors.contains_key(&id) && !sel.segments.contains_key(&id), "{sel:?}");
|
||||
assert_eq!(sel.anchors.get(&other), Some(&[(0, 1)].into()), "the path out of reach keeps its anchor");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&[(0, 38)].into()));
|
||||
}
|
||||
|
||||
/// #1512: a short drag over a small bump smooths the stretch of path under it. The long straight
|
||||
/// sides next to the bump stay straight lines from their far ends, which keep their place.
|
||||
#[test]
|
||||
@@ -1390,6 +1412,169 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected path through `anchors` (x, y, and the in and out handles when given).
|
||||
fn smooth_test_path(s: &mut Session, anchors: &[serde_json::Value], closed: bool) -> NodeId {
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// `path.smoothRegion` along `drag` with the Smooth tool's reach (12 pt at 100%) and default Fidelity.
|
||||
fn smooth_pass(s: &mut Session, drag: &[Point]) {
|
||||
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap();
|
||||
}
|
||||
|
||||
/// Points 1/32 of a segment apart along every segment of `p`.
|
||||
fn smooth_test_samples(p: &PathData) -> Vec<Point> {
|
||||
use kurbo::ParamCurve;
|
||||
let mut v = vec![];
|
||||
for sp in &p.subpaths {
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
v.extend((0..32).map(|k| c.eval(f64::from(k) / 32.0)));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// How much `p` turns along its length, in radians: a wobbly path turns much more than a smooth one.
|
||||
fn total_turning(p: &PathData) -> f64 {
|
||||
let pts = smooth_test_samples(p);
|
||||
pts.windows(3)
|
||||
.map(|w| (w[1] - w[0], w[2] - w[1]))
|
||||
.filter(|(u, v)| u.hypot() > 1e-9 && v.hypot() > 1e-9)
|
||||
.map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Deterministic noise in -1..1.
|
||||
fn smooth_noise(seed: &mut u64) -> f64 {
|
||||
*seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(*seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
/// A drag along y = `y` from x = `x0` to `x1`, one point every 5 pt.
|
||||
fn smooth_drag_along(y: f64, x0: f64, x1: f64) -> Vec<Point> {
|
||||
let n = ((x1 - x0) / 5.0).ceil() as usize;
|
||||
(0..=n).map(|i| Point::new(x0 + (x1 - x0) * i as f64 / n as f64, y)).collect()
|
||||
}
|
||||
|
||||
/// Each drag of the Smooth tool smooths the path under it, and a second drag over the same place
|
||||
/// smooths it further, as the help page describes
|
||||
/// (https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html): a curve that wobbles
|
||||
/// 4 pt either side of its line every 12 pt, with an anchor at each crest, wobbles less after each drag.
|
||||
#[test]
|
||||
fn each_smooth_drag_smooths_a_wobble_larger_than_fidelity_further() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=20)
|
||||
.map(|k| {
|
||||
let (x, y) = (100.0 + 12.0 * f64::from(k), if k % 2 == 0 { 196.0 } else { 204.0 });
|
||||
json!({"x": x, "y": y, "in": [x - 4.4, y], "out": [x + 4.4, y]})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let drag = smooth_drag_along(200.0, 90.0, 350.0);
|
||||
let wobble =
|
||||
|p: &PathData| smooth_test_samples(p).iter().filter(|q| (130.0..=310.0).contains(&q.x)).map(|q| (q.y - 200.0).abs()).fold(0.0, f64::max);
|
||||
let mut before = path(&s, id);
|
||||
for pass in 1..=2 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "pass {pass} changes the path");
|
||||
let (t0, t1) = (total_turning(&before), total_turning(&after));
|
||||
assert!(t1 < 0.9 * t0, "pass {pass}: turning {t0} -> {t1}");
|
||||
let (w0, w1) = (wobble(&before), wobble(&after));
|
||||
assert!(w1 < 0.8 * w0, "pass {pass}: wobble {w0} -> {w1}");
|
||||
let (a, b) = (before.subpaths[0].anchors[0].p, after.subpaths[0].anchors[0].p);
|
||||
assert_eq!(a, b, "pass {pass}: the path keeps its start");
|
||||
before = after;
|
||||
}
|
||||
}
|
||||
|
||||
/// Smoothing a line with up to 1 pt of noise again and again, over all of it or over its middle,
|
||||
/// keeps it close to the line under the noise: each refit stays near the path it smooths.
|
||||
#[test]
|
||||
fn repeated_smooth_drags_stay_close_to_the_line_under_the_noise() {
|
||||
let off = |p: &PathData| {
|
||||
let d: Vec<f64> = smooth_test_samples(p).iter().map(|q| (q.y - 200.0).abs()).collect();
|
||||
(d.iter().sum::<f64>() / d.len() as f64, d.iter().copied().fold(0.0, f64::max))
|
||||
};
|
||||
for (x0, x1) in [(90.0, 410.0), (150.0, 350.0)] {
|
||||
let mut s = session();
|
||||
let mut seed = 7u64;
|
||||
let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let drag = smooth_drag_along(200.0, x0, x1);
|
||||
let (mean0, _) = off(&path(&s, id));
|
||||
for pass in 1..=5 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let (mean, max) = off(&path(&s, id));
|
||||
assert!(
|
||||
mean <= 1.1 * mean0 && max <= 1.5,
|
||||
"drag {x0}-{x1}, pass {pass}: {mean} on average and {max} at most from the line, {mean0} before"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag over the whole of a noisy closed path leaves no corner where the path starts.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_leaves_no_kink_at_its_start() {
|
||||
let mut s = session();
|
||||
let mut seed = 5u64;
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let anchors: Vec<_> = (0..64)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) / 64.0 * std::f64::consts::TAU;
|
||||
let rr = r + 2.5 * smooth_noise(&mut seed);
|
||||
json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect();
|
||||
smooth_pass(&mut s, &ring);
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() < 64, "{} anchors", sp.anchors.len());
|
||||
let (last, first) = (sp.segment(sp.segment_count() - 1), sp.segment(0));
|
||||
let tin = if last.p3.distance(last.p2) > 1e-9 { last.p3 - last.p2 } else { last.p3 - last.p1 };
|
||||
let tout = if first.p1.distance(first.p0) > 1e-9 { first.p1 - first.p0 } else { first.p2 - first.p0 };
|
||||
let kink = tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees();
|
||||
assert!(kink <= 1.0, "a {kink}° corner at the start");
|
||||
}
|
||||
|
||||
/// A drag over the whole of a closed path smooths a bump at its first anchor as much as the same
|
||||
/// bump on the far side of it.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let anchors: Vec<_> = (0..64)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) / 64.0 * std::f64::consts::TAU;
|
||||
let rr = if i % 32 == 0 { r + 6.0 } else { r };
|
||||
json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect();
|
||||
// A Fidelity of 0.5 pt, so the refit follows the smoothed path closely on both sides.
|
||||
let pts: Vec<_> = ring.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.5})).unwrap();
|
||||
let p = path(&s, id);
|
||||
use std::f64::consts::{PI, TAU};
|
||||
// How far the path rises above the circle within 0.3 radians of the angle `near`.
|
||||
let bump = |near: f64| {
|
||||
let off = |q: &Point| (((q.y - c.y).atan2(q.x - c.x) - near + PI).rem_euclid(TAU) - PI).abs();
|
||||
smooth_test_samples(&p).iter().filter(|q| off(q) < 0.3).map(|q| q.distance(c) - r).fold(0.0, f64::max)
|
||||
};
|
||||
let (start, far) = (bump(0.0), bump(PI));
|
||||
assert!(far < 5.0, "the far bump stays {far} pt high");
|
||||
assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_tool_joins_two_lines() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -535,9 +535,9 @@ fn expanded_art_keeps_the_random_transforms_the_canvas_drew() {
|
||||
}
|
||||
|
||||
/// The reply lists each object whose appearance expanded once, by the id it has in the document,
|
||||
/// starting with the selected object. In "group copies" the two copies of the square share an id
|
||||
/// until Expand Appearance gives them ids of their own, and the reply names the group, then each
|
||||
/// copy by its new id.
|
||||
/// starting with the selected object. In "group copies" the group's art holds the square with its
|
||||
/// stroke's effect applied, so the reply names the group alone; the two copies of the square share
|
||||
/// ids until Expand Appearance gives every object in them an id of its own.
|
||||
#[test]
|
||||
fn the_reply_names_each_expanded_copy_by_its_own_id() {
|
||||
for case in RANDOM_CASES {
|
||||
@@ -551,8 +551,17 @@ fn the_reply_names_each_expanded_copy_by_its_own_id() {
|
||||
assert!(ids.iter().all(|&i| s.doc().unwrap().doc.node(NodeId(i)).is_some()), "{case}: {ids:?}");
|
||||
if case == "group copies" {
|
||||
let art = node(&s, id);
|
||||
let copies: Vec<u64> = art.children().unwrap()[0].children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
assert_eq!(ids, [vec![id.0], copies].concat(), "{case}");
|
||||
assert_eq!(ids, [id.0], "{case}");
|
||||
let copies = art.children().unwrap();
|
||||
assert_eq!(copies.len(), 2, "{case}");
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut repeated = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if !seen.insert(n.id) {
|
||||
repeated.push(n.id);
|
||||
}
|
||||
});
|
||||
assert!(repeated.is_empty(), "{case}: {repeated:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,6 +635,210 @@ fn a_library_style_named_with_spaces_comes_in_trimmed() {
|
||||
assert_eq!((text.runs[0].style.size, text.runs[0].style.style_name.as_deref()), (31.0, Some("Body")));
|
||||
}
|
||||
|
||||
/// The size of the first run of text object `id`.
|
||||
fn run_size(s: &Session, id: &Value) -> f64 {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.size,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add to Character Styles puts a library character style into the document's character styles
|
||||
/// without applying it, with or without type selected, in one undo step; the same style there is
|
||||
/// reused without a step, and a name taken by other attributes gets a number. A bad call changes
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn a_library_character_style_is_added_to_the_document_without_applying_it() {
|
||||
let mut s = session();
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Headline", "attrs": {"size": 31.0}}, {"name": "Broken", "attrs": {"size": "big"}}]});
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let styles = |s: &Session| s.doc().unwrap().doc.char_styles.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
// Nothing selected.
|
||||
let before = undo(&s);
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(false)));
|
||||
assert_eq!(styles(&s), ["Headline"]);
|
||||
assert_eq!(undo(&s), before + 1, "one undo step");
|
||||
let attrs = &s.doc().unwrap().doc.char_styles[0].attrs;
|
||||
assert_eq!(attrs.get("size"), Some(&json!(31.0)));
|
||||
// Selected type keeps its look.
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let before = undo(&s);
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(true)));
|
||||
assert_eq!((undo(&s), run_size(&s, &t), styles(&s).len()), (before, 9.0, 1), "reused: no step, the type unchanged");
|
||||
// Another style of that name: numbered, still not applied.
|
||||
run(&mut s, "charStyle.setAttrs", json!({"name": "Headline", "attrs": {"size": 5}}));
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline 2"), Some(false)));
|
||||
assert_eq!(run_size(&s, &t), 9.0);
|
||||
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(NodeId(t.as_u64().unwrap())).unwrap().kind else { panic!("not text") };
|
||||
assert_eq!(text.runs[0].style.style_name, None, "no style applied");
|
||||
// Undo takes the added style back alone.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(styles(&s), ["Headline"]);
|
||||
// Bad calls: nothing changes.
|
||||
let before = (undo(&s), styles(&s));
|
||||
for bad in [
|
||||
json!({"library": lib}),
|
||||
json!({"library": lib, "item": 3}),
|
||||
json!({"library": lib, "item": "Nope"}),
|
||||
json!({"library": "Nope", "item": "Headline"}),
|
||||
json!({"library": lib, "item": "Broken"}),
|
||||
json!({"recorded": {"name": "X", "attrs": "damaged"}}),
|
||||
] {
|
||||
assert!(s.execute("library.addToCharacterStyles", &bad).is_err(), "{bad}");
|
||||
assert_eq!((undo(&s), styles(&s)), before, "{bad}");
|
||||
}
|
||||
// Without a document it isn't available.
|
||||
run(&mut s, "file.close", json!({}));
|
||||
assert!(s.active().is_none());
|
||||
assert!(s.execute("library.addToCharacterStyles", &json!({"library": lib, "item": "Headline"})).is_err());
|
||||
}
|
||||
|
||||
/// A library character style whose fill links to a swatch the document lacks is added and applied
|
||||
/// with the color it shows, unlinked at full tint; a global swatch of that name in the document
|
||||
/// keeps the link and gives its color.
|
||||
#[test]
|
||||
fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() {
|
||||
let base = vectorcraft_color::Color::rgb(0.2, 0.4, 0.6);
|
||||
let shown = base.tinted(0.5);
|
||||
let linked = vectorcraft_color::Paint::Solid { color: shown, swatch: Some("Brand".into()), tint: 0.5 };
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Accent", "attrs": {"size": 20.0, "fill": linked}}]});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let fill = |s: &Session, name: &str| {
|
||||
let st = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == name).map(|c| c.attrs.clone()).unwrap();
|
||||
serde_json::from_value::<vectorcraft_color::Paint>(st["fill"].clone()).unwrap()
|
||||
};
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
assert_eq!(fill(&s, "Accent"), vectorcraft_color::Paint::Solid { color: shown, swatch: None, tint: 1.0 });
|
||||
// Apply as well, on selected type.
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "charStyle", "item": "Accent"}));
|
||||
assert_eq!(r["style"], "Accent", "the added style is reused");
|
||||
assert_eq!(run_size(&s, &t), 20.0);
|
||||
// A document with a global swatch of that name keeps the link.
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let other = vectorcraft_color::Color::rgb(0.8, 0.1, 0.1);
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": other, "global": true}));
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill(&s, "Accent") else { panic!("not a solid fill") };
|
||||
assert_eq!((swatch.as_deref(), tint), (Some("Brand"), 0.5));
|
||||
// The style with the document's swatch color is the same style: added again, it is reused.
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true)));
|
||||
}
|
||||
|
||||
/// A library style is compared with the document's in the form the document stores it in, so a
|
||||
/// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a
|
||||
/// click alike.
|
||||
#[test]
|
||||
fn a_library_style_is_reused_whatever_form_its_file_writes_it_in() {
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Whole", "attrs": {"size": 31}}], "paraStyles": [{"name": "Para", "attrs": {"left_indent": 4}}]});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"}));
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Whole"), Some(true)));
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
for (kind, item) in [("charStyle", "Whole"), ("paraStyle", "Para"), ("paraStyle", "Para")] {
|
||||
assert_eq!(run(&mut s, "library.use", json!({"library": lib, "kind": kind, "item": item}))["style"], item);
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!((d.char_styles.len(), d.para_styles.iter().filter(|p| p.name.starts_with("Para")).count()), (1, 1));
|
||||
}
|
||||
|
||||
/// Rename gives a library item a new name, trimmed, in its place and its group; a character style
|
||||
/// keeps its attributes, a graphic its id. Another item of its kind with that name, an empty or
|
||||
/// too long name, a name that isn't text and an unknown item or library are errors that change
|
||||
/// nothing; a name with path characters is a name like any other; the item's own name writes
|
||||
/// nothing; and the document's history is not touched.
|
||||
#[test]
|
||||
fn library_items_are_renamed_in_place() {
|
||||
let (mut s, g, c, st) = brand();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 120, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let other = run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "library.createGroup", json!({"name": "Brand", "items": [{"kind": "charStyle", "item": st}, {"kind": "fillColor", "item": c}]}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let attrs = run(&mut s, "library.get", json!({}))["charStyles"][0]["attrs"].clone();
|
||||
let r = run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": st, "name": " Title "}));
|
||||
assert_eq!((r["item"].as_str(), r["name"].as_str()), (Some("Title"), Some("Title")));
|
||||
let got = run(&mut s, "library.get", json!({}));
|
||||
assert_eq!(got["charStyles"][0], json!({"name": "Title", "attrs": attrs}), "first still, the attributes kept");
|
||||
assert_eq!(got["charStyles"][1]["name"], other.as_str());
|
||||
assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", &c)]))]);
|
||||
// A colour keeps its group under its new name; a graphic keeps its id.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "strokeColor", "item": c, "name": "Navy"}));
|
||||
assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", "Navy")]))]);
|
||||
let r = run(&mut s, "library.renameItem", json!({"kind": "graphic", "item": "Logo", "name": "Mark"}));
|
||||
assert_eq!(r["item"], g.as_str());
|
||||
let graphic = run(&mut s, "library.get", json!({}))["graphics"][0].clone();
|
||||
assert_eq!((graphic["id"].as_str(), graphic["name"].as_str()), (Some(g.as_str()), Some("Mark")));
|
||||
// Path characters are kept.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Title", "name": "a/b\\c:d"}));
|
||||
assert_eq!(style_order_of(&mut s)[0], "a/b\\c:d");
|
||||
// Errors change nothing.
|
||||
let before = run(&mut s, "library.get", json!({}));
|
||||
let long = "x".repeat(257);
|
||||
for bad in [
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": other}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": " "}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": long}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": 5}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d"}),
|
||||
json!({"kind": "charStyle", "item": "Nope", "name": "X"}),
|
||||
json!({"kind": "paraStyle", "item": "a/b\\c:d", "name": "X"}),
|
||||
json!({"kind": "brush", "item": "a/b\\c:d", "name": "X"}),
|
||||
json!({"library": "Nope", "kind": "charStyle", "item": "a/b\\c:d", "name": "X"}),
|
||||
] {
|
||||
assert!(s.execute("library.renameItem", &bad).is_err(), "{bad}");
|
||||
assert_eq!(run(&mut s, "library.get", json!({})), before, "{bad}");
|
||||
}
|
||||
// A style of another kind may have the name, and 256 characters are allowed.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "a/b\\c:d", "name": "Navy"}));
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Navy", "name": "y".repeat(256)}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no document undo step");
|
||||
}
|
||||
|
||||
/// The current library's character style names, in order.
|
||||
fn style_order_of(s: &mut Session) -> Vec<String> {
|
||||
order(s, "charStyles", "name")
|
||||
}
|
||||
|
||||
/// A rename is kept in the library's file; renaming an item to its own name writes nothing; and a
|
||||
/// rename whose file can't be written is taken back.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_library_item_rename_is_saved_or_taken_back() {
|
||||
let dir = vectorcraft_testkit::temp_dir("library-rename-item");
|
||||
let folder = dir.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
s.libraries.set_dir(Some(folder.clone()));
|
||||
let lib = run(&mut s, "library.create", json!({"name": "Kept"}))["id"].as_str().unwrap().to_string();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 12}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}));
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Body", "name": "Text"}));
|
||||
let mut t2 = session();
|
||||
t2.libraries.set_dir(Some(folder.clone()));
|
||||
assert_eq!(style_order_of(&mut t2), ["Text"], "kept in the file");
|
||||
// The file can't be written (a folder stands where it goes): its own name still succeeds, as
|
||||
// it writes nothing; a new name fails and is taken back.
|
||||
let file = dir.join(format!("{lib}.vclibrary"));
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
std::fs::create_dir(&file).unwrap();
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Text", "name": " Text "}));
|
||||
assert!(s.execute("library.renameItem", &json!({"kind": "charStyle", "item": "Text", "name": "Copy"})).is_err());
|
||||
assert_eq!(style_order_of(&mut s), ["Text"], "taken back");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn libraries_are_kept_in_files_across_sessions() {
|
||||
|
||||
@@ -643,6 +643,32 @@ fn envelope_top_object_shares_a_side_by_control_polygon_length() {
|
||||
assert!(near(Point::new(500.0, 200.0)) < 0.5, "the middle of the bottom: {pts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_top_object_keeps_its_look_when_anchors_are_added() {
|
||||
// Add Anchor Points splits each segment of the top object in two without changing its shape.
|
||||
// The top curve's parameter runs fast at its start, so its halves have control polygons of
|
||||
// different lengths; the envelope still bends the two rectangles as the unsplit curve does.
|
||||
let made = |add_anchors: bool| {
|
||||
let mut s = session();
|
||||
let left = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let right = rect(&mut s, 200.0, 100.0, 100.0, 100.0);
|
||||
let d = "M400 100 C520 40 590 70 600 100 L600 200 L400 200 Z";
|
||||
let t = id_of(&s.execute("path.create", &json!({ "d": d })).unwrap());
|
||||
if add_anchors {
|
||||
sel(&mut s, &[t]);
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, t).path_data().map(|p| p.anchor_count()), Some(8));
|
||||
}
|
||||
sel(&mut s, &[left, right, t]);
|
||||
let e = id_of(&s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap());
|
||||
all_anchors(&live::expand_live(&node(&s, e)))
|
||||
};
|
||||
let (plain, split) = (made(false), made(true));
|
||||
assert_eq!(plain.len(), split.len());
|
||||
let off = plain.iter().zip(&split).map(|(p, q)| p.distance(*q)).fold(0.0, f64::max);
|
||||
assert!(off < 1e-6, "the art moves by up to {off} pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_release_and_expand() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -257,6 +257,25 @@ fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canva
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on
|
||||
/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide.
|
||||
#[test]
|
||||
fn a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 10}}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 50}}));
|
||||
let before = render(&s);
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let after = render(&s);
|
||||
let diff = differing(&before, &after, 64);
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let w = doc.node(doc.layers[0].id).and_then(|l| l.geometric_bounds()).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it() {
|
||||
// The object's own effect, and the fill's (the first appearance item).
|
||||
|
||||
@@ -2820,6 +2820,188 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
}
|
||||
|
||||
/// An install refused because another session revoked the grant its checks relied on writes
|
||||
/// nothing: a store that kept the grant and lost the module gets no module back, its grants stay as
|
||||
/// they were, and the plug-in installed with the id and the other session's revoke stand. `grant`
|
||||
/// approves the module by itself.
|
||||
#[test]
|
||||
fn a_grant_revoked_while_installing_leaves_the_store_as_it_was() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-revoked-while-installing");
|
||||
let id = "test.engine.permissions.revokedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
let grants = folder.0.join("grants.json");
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
std::fs::remove_file(&module).unwrap();
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || {
|
||||
registry::revoke(id);
|
||||
})));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("asks for the permissions doc.read"), "{e}");
|
||||
assert!(!module.exists(), "no module is stored");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grants stay as they were");
|
||||
assert!(registry::granted(id).is_none(), "the other session's revoke stands");
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&bytes)), "the installed plug-in stays");
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || {
|
||||
registry::revoke(id);
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert_eq!(std::fs::read(&module).unwrap(), bytes, "a module `grant` approves is stored");
|
||||
assert!(registry::granted(id).is_some_and(|g| g.hash == sha256_hex(&bytes)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A plug-in another session installs with the id while a module is checked takes the place the
|
||||
/// checks found free. Without `replace`, or with `replace: false`, the install is refused, writes no
|
||||
/// module and leaves that plug-in installed; with `replace: true` the module takes its place.
|
||||
#[test]
|
||||
fn a_plug_in_installed_while_installing_needs_replace() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-installed-while-installing");
|
||||
let id = "test.engine.installedwhileinstalling";
|
||||
let ours = asking(id, "[]", &json!({"objects": []}));
|
||||
let theirs = asking(id, "[]", &json!({"objects": [], "documentData": null}));
|
||||
let data = vectorcraft_format::base64_encode(&ours);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
let installed = || registry::get(id).map(|p| p.hash().to_string());
|
||||
let meanwhile = |theirs: Vec<u8>| -> Option<Box<dyn FnOnce()>> {
|
||||
Some(Box::new(move || {
|
||||
registry::install_bytes(&theirs).unwrap();
|
||||
}))
|
||||
};
|
||||
|
||||
for (replace, why) in [(Value::Null, "is another module than"), (json!(false), "is already installed")] {
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs.clone()));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "replace": replace})).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{replace}: {e}");
|
||||
assert!(!module.exists(), "{replace}: no module is stored");
|
||||
assert_eq!(installed(), Some(sha256_hex(&theirs)), "{replace}: the other plug-in stays installed");
|
||||
registry::remove(id);
|
||||
}
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true}));
|
||||
assert_eq!(std::fs::read(&module).unwrap(), ours);
|
||||
assert_eq!(installed(), Some(sha256_hex(&ours)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Without a plug-in store, the install's approval comes from the grant it read first, the one it
|
||||
/// checks again before it installs: a grant another session records after that read approves
|
||||
/// nothing, so a revoke that follows it can't be undone by the install recording it again.
|
||||
#[test]
|
||||
fn a_grant_recorded_and_revoked_while_installing_approves_nothing() {
|
||||
use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex};
|
||||
use vectorcraft_plugins::registry;
|
||||
let id = "test.engine.permissions.recordedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
let g = Grant { id: id.into(), hash: sha256_hex(&bytes), permissions: vec![Permission::DocRead] };
|
||||
crate::cmd::plugin::AFTER_GRANT_READ.set(Some(Box::new(move || {
|
||||
registry::grant(GrantToken::after_engine_approval(g));
|
||||
})));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("asks for the permissions doc.read"), "{e}");
|
||||
assert!(registry::get(id).is_none(), "nothing is installed");
|
||||
registry::revoke(id);
|
||||
}
|
||||
|
||||
/// A `plugin.remove` in another session while a module is installed waits until the install has
|
||||
/// written the store, then removes the module, its grant and the plug-in: nothing of it stays in
|
||||
/// the store for the next launch.
|
||||
#[test]
|
||||
fn a_removal_while_installing_leaves_nothing_in_the_store() {
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-removed-while-installing");
|
||||
let id = "test.engine.permissions.removedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
let grants = folder.0.join("grants.json");
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, remover) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
let tell = said.clone();
|
||||
crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || {
|
||||
let _ = tell.send("waiting");
|
||||
})));
|
||||
let mut other = session();
|
||||
other.attach_plugin_store(dir);
|
||||
let removed = other.execute("plugin.remove", &json!({"id": id})).map(|_| ()).map_err(|e| e.to_string());
|
||||
let _ = said.send("removed");
|
||||
removed
|
||||
});
|
||||
// The removal has finished, or waits for this install.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
let (first, thread) = remover.recv().unwrap();
|
||||
assert_eq!(thread.join().unwrap(), Ok(()));
|
||||
assert!(registry::get(id).is_none() && registry::granted(id).is_none(), "the plug-in and its grant are gone");
|
||||
assert!(!module.exists(), "no module stays in the store");
|
||||
assert!(!std::fs::read_to_string(&grants).is_ok_and(|g| g.contains(id)), "no grant stays in the store");
|
||||
assert_eq!(first, "waiting", "the removal waits for the install");
|
||||
}
|
||||
|
||||
/// Another session that attaches the plug-in store while a new version is installed loads the
|
||||
/// stored plug-ins once the install has written the store: the version that runs is the one the
|
||||
/// store keeps for the next launch.
|
||||
#[test]
|
||||
fn a_store_loaded_while_installing_loads_the_new_version() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-loaded-while-installing");
|
||||
let id = "test.engine.permissions.loadedwhileinstalling";
|
||||
let old = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let new = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&old), "grant": ["doc.read"]}));
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, loader) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
let tell = said.clone();
|
||||
crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || {
|
||||
let _ = tell.send("waiting");
|
||||
})));
|
||||
session().attach_plugin_store(dir);
|
||||
let _ = said.send("loaded");
|
||||
});
|
||||
// The load has finished, or waits for this install.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
let data = vectorcraft_format::base64_encode(&new);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true}));
|
||||
let (first, thread) = loader.recv().unwrap();
|
||||
thread.join().unwrap();
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&new)), "the new version runs");
|
||||
assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), new, "the store keeps the new version");
|
||||
assert_eq!(first, "waiting", "the load waits for the install");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Runs the test `name` of this module again in a process of its own → whether this is that
|
||||
/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here
|
||||
/// read it again each time they attach a plug-in store.
|
||||
|
||||
@@ -2473,6 +2473,65 @@ fn deferred_commit_forwards_preview_warnings() {
|
||||
assert!(ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))), "{ui:?}");
|
||||
}
|
||||
|
||||
/// A session with a rectangle selected, and type too with `with_type`, tool `tool` chosen,
|
||||
/// Real-time Drawing off, and an interaction labeled `label` whose deferred Bloat preview warns
|
||||
/// that type is skipped when type is selected.
|
||||
fn deferred_bloat(label: &str, with_type: bool, tool: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap();
|
||||
let text = s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Hi"})).unwrap();
|
||||
let ids = if with_type { json!([rect["id"], text["id"]]) } else { json!([rect["id"]]) };
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
s.select_tool(tool, ViewInfo::default()).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.begin_interaction(label).unwrap();
|
||||
let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0});
|
||||
s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p));
|
||||
s
|
||||
}
|
||||
|
||||
/// A command that applies a deferred preview before it runs (Undo, Clear History) reports the
|
||||
/// preview's warning in its result, as the tool's own commit reports it; the preview is its own
|
||||
/// step, which Undo takes back. A preview without a warning adds none.
|
||||
#[test]
|
||||
fn settling_a_deferred_preview_keeps_its_warning() {
|
||||
let mut s = deferred_bloat("Bloat", true, "selection");
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(r["undone"], "Bloat", "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}");
|
||||
assert_eq!(r["previewWarning"], r["warning"], "{r}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before, "the preview was a step of its own, and Undo took it back");
|
||||
let r = s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(r.get("warning").is_none() && r.get("previewWarning").is_none(), "nothing was settled: {r}");
|
||||
|
||||
let mut s = deferred_bloat("Bloat", true, "selection");
|
||||
let r = s.execute("edit.clearHistory", &json!({})).unwrap();
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}");
|
||||
|
||||
let mut s = deferred_bloat("Bloat", false, "selection");
|
||||
let r = s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"undone": "Bloat"}));
|
||||
}
|
||||
|
||||
/// Typing kept as its own step when a tool's drag begins, or when a Cmd press lends the Selection
|
||||
/// tool, shows its applied preview's warning in the status bar.
|
||||
#[test]
|
||||
fn settling_typing_for_a_tool_shows_its_preview_warning() {
|
||||
use vectorcraft_tools::{Action, Mods};
|
||||
let warned = |ui: &[UiRequest]| ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type")));
|
||||
let mut s = deferred_bloat("Typing", true, "selection");
|
||||
let ui = s.apply_actions(vec![Action::Begin("Move".into())]).unwrap();
|
||||
assert!(warned(&ui), "{ui:?}");
|
||||
|
||||
let mut s = deferred_bloat("Typing", true, "rectangle");
|
||||
let cmd = Mods { cmd: true, ..Default::default() };
|
||||
let ui = s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
assert!(warned(&ui), "{ui:?}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
}
|
||||
|
||||
/// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does
|
||||
/// not replace full-resolution pixels already in the document.
|
||||
#[test]
|
||||
|
||||
@@ -1348,3 +1348,159 @@ fn theme_picker_refuses_bad_params() {
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
const RED: &str = "rgb 255 0 0";
|
||||
const PURPLE: &str = "rgb 128 0 204";
|
||||
const BLUE: &str = "rgb 0 0 255";
|
||||
|
||||
/// Two red rectangles, a purple one and a blue one, selected.
|
||||
fn prominent_art(s: &mut Session) -> [NodeId; 4] {
|
||||
let ids = [rect(s, json!("#ff0000")), rect(s, json!("#ff0000")), rect(s, json!("#8000cc")), rect(s, json!("#0000ff"))];
|
||||
select_all(s);
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_gives_each_rows_share_of_the_uses() {
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": BLUE, "to": null, "tint": 50}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map}));
|
||||
assert_eq!(r["shares"], json!([75.0, 25.0]));
|
||||
assert_eq!(
|
||||
r["map"],
|
||||
json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": null, "tint": 50}]),
|
||||
"rows as given, from as a list"
|
||||
);
|
||||
// An excluded row has no share, and the others share the uses.
|
||||
let excl = json!([{"from": [RED, PURPLE], "to": null}, {"from": [BLUE], "to": null, "exclude": true}]);
|
||||
assert_eq!(run(&mut s, "recolor.weigh", json!({"map": excl}))["shares"], json!([100.0, 0.0]));
|
||||
// An excluded row before another that lists the same colour doesn't take its uses.
|
||||
let first = json!([{"from": [RED], "exclude": true}, {"from": [RED]}, {"from": [BLUE, PURPLE]}]);
|
||||
assert_eq!(run(&mut s, "recolor.weigh", json!({"map": first}))["shares"], json!([0.0, 50.0, 50.0]));
|
||||
// A current colour that no art uses counts nothing, and a use counts for the first row only.
|
||||
let twice = json!({"map": [{"from": [RED, "#123456"]}, {"from": [RED, PURPLE, BLUE]}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", twice)["shares"], json!([50.0, 50.0]));
|
||||
// As recolor.apply matches them: an exact colour before a hex one, a row with a new colour first.
|
||||
let exact = json!({"map": [{"from": ["#ff0000", PURPLE], "to": "#00ff00"}, {"from": [RED, BLUE], "to": "#ffff00"}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", exact)["shares"], json!([25.0, 75.0]));
|
||||
let recolored = json!({"map": [{"from": [RED, PURPLE]}, {"from": [RED, BLUE], "to": "#ffff00"}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", recolored)["shares"], json!([25.0, 75.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_colors_to_the_rows_weights_and_changes_nothing() {
|
||||
let mut s = session();
|
||||
let [_, _, purple, blue] = prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]}));
|
||||
assert_eq!(r["map"], json!([{"from": [RED], "to": "#00ff00"}, {"from": [BLUE, PURPLE], "to": "#ffff00"}]));
|
||||
assert_eq!(r["shares"], json!([50.0, 50.0]));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#8000cc", "a query leaves the art alone");
|
||||
// Recoloring with the weighed rows gives the moved colour its new row's colour.
|
||||
select_all(&mut s);
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"]}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#ffff00");
|
||||
assert_eq!(fill(&s, blue).to_hex(), "#ffff00");
|
||||
// A row's first colour stays, however small its weight.
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [0, 1]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED]));
|
||||
assert_eq!(r["shares"], json!([50.0, 50.0]));
|
||||
// Excluded rows keep their colours and take none; their weights are ignored.
|
||||
let three =
|
||||
json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE], "to": "#000000", "exclude": true}, {"from": ["#00ff00"], "to": "#000000"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": three, "weights": [1, 50, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE]));
|
||||
// A row without a new colour recolors nothing, so it neither gives nor takes colours.
|
||||
let keep = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE]}, {"from": ["#00ff00"], "to": "#000000"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": keep, "weights": [0, 1, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE]));
|
||||
}
|
||||
|
||||
/// A colour that two rows list moves only where recolor.apply recolors it with the row it moved
|
||||
/// to, so the shares describe the recolor.
|
||||
#[test]
|
||||
fn weigh_keeps_a_moved_color_from_rows_that_also_list_it() {
|
||||
const GREEN: &str = "rgb 0 255 0";
|
||||
let mut s = session();
|
||||
let [_, _, purple, _] = prominent_art(&mut s);
|
||||
rect(&mut s, json!("#00ff00"));
|
||||
select_all(&mut s);
|
||||
// The purple moves from the first row to the third; the second row's entry for it goes.
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE, PURPLE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED]));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!([GREEN, PURPLE]));
|
||||
assert_eq!(r["shares"], json!([40.0, 20.0, 40.0]));
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#ffff00", "the purple takes the row it moved to");
|
||||
// A colour that another row lists first stays: that row would take it back.
|
||||
let mut s = session();
|
||||
let [_, _, purple, _] = prominent_art(&mut s);
|
||||
rect(&mut s, json!("#00ff00"));
|
||||
select_all(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [PURPLE, BLUE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED, PURPLE]));
|
||||
assert_eq!(r["map"][1]["from"], json!([PURPLE, BLUE]));
|
||||
assert_eq!(r["shares"], json!([60.0, 20.0, 20.0]));
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#000000", "the purple keeps the first row's colour");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_the_tints_of_a_global_swatch_together() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 90, "k": 0}, "global": true}));
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
let full = rect(&mut s, json!("#00ff00"));
|
||||
let tint = rect(&mut s, json!("#00ff00"));
|
||||
rect(&mut s, json!("#0000ff"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": "Brand"}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": "Brand", "tint": 50}));
|
||||
select_all(&mut s);
|
||||
let brand: Vec<Value> = run(&mut s, "recolor.colors", json!({}))["colors"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c["swatch"] == "Brand")
|
||||
.map(|c| c["key"].clone())
|
||||
.collect();
|
||||
assert_eq!(brand.len(), 2);
|
||||
let map = json!([{"from": [RED, brand[0], brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]);
|
||||
// Even weights would take one tint alone, which would split the swatch: nothing moves.
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
// The swatch's two colours move to the blue row as one.
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 3]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE, brand[0], brand[1]]));
|
||||
assert_eq!(r["shares"], json!([25.0, 75.0]));
|
||||
// Colours that stay keep their order, a swatch's colours with another between them included.
|
||||
let split = json!([{"from": [brand[0], RED, brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": split, "weights": [3, 1]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([brand[0], RED, brand[1]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_refuses_bad_weights() {
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED]}, {"from": [BLUE], "exclude": true}]);
|
||||
for (p, msg) in [
|
||||
(json!({"map": map, "weights": [1]}), "`weights` must be a list of 2 numbers, one per row"),
|
||||
(json!({"map": map, "weights": "1, 1"}), "`weights` must be a list of 2 numbers"),
|
||||
(json!({"map": map, "weights": [1, -1]}), "each weight must be a number of 0 or more (got -1)"),
|
||||
(json!({"map": map, "weights": [1, "2"]}), "each weight must be a number of 0 or more"),
|
||||
(json!({"map": map, "weights": [0, 5]}), "at least one row that isn't excluded needs a weight above 0"),
|
||||
(json!({"weights": [1, 1]}), "missing `map`"),
|
||||
(json!({"map": [{"to": "#ff0000"}]}), "each row needs `from`"),
|
||||
] {
|
||||
let e = s.execute("recolor.weigh", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,52 @@ fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `$.fileName` in code an earlier run of a named engine kept names the file that code is in: that
|
||||
/// run's script, a file it included or a file `$.evalFile` gave, not the file of the run that calls
|
||||
/// it. Code from a script given as text, and code whose place the engine no longer keeps, has no
|
||||
/// name; a dropped engine takes its functions with it.
|
||||
#[test]
|
||||
fn a_kept_function_reads_the_file_name_of_the_file_it_is_in() {
|
||||
let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-file-name-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for dir in ["a", "b"] {
|
||||
std::fs::create_dir_all(base.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("a/inc.jsxinc"), "function fromInclude() { return $.fileName; }").unwrap();
|
||||
std::fs::write(base.join("a/ev.jsxinc"), "\nfunction fromEval() { return $.fileName; }").unwrap();
|
||||
let def = base.join("a/def.jsx");
|
||||
std::fs::write(&def, "#targetengine e\nfunction where() { return $.fileName; }\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');").unwrap();
|
||||
let caller = base.join("b/caller.jsx");
|
||||
let call = |s: &mut Session, text: &str| -> Vec<String> {
|
||||
std::fs::write(&caller, text).unwrap();
|
||||
let r = s.execute("script.run", &json!({"path": caller.to_string_lossy()})).unwrap();
|
||||
r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect()
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap();
|
||||
let from_file = call(&mut s, "#targetengine e\nvc.log([where(), fromInclude(), fromEval(), $.fileName]);");
|
||||
let from_text = log(&mut s, "#targetengine e\nvc.log([where(), $.fileName, eval('where()'), eval('$.fileName')]);");
|
||||
run(&mut s, "#targetengine e\nfunction fromText() { return $.fileName; }").unwrap();
|
||||
let text_kept = call(&mut s, "#targetengine e\nvc.log([fromText(), $.fileName]);");
|
||||
// Each run's own place takes the room of the ones before, so def.jsx's places go.
|
||||
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300)));
|
||||
for _ in 0..20 {
|
||||
run(&mut s, "#targetengine e\nvar x = 1;").unwrap();
|
||||
}
|
||||
let evicted = call(&mut s, "#targetengine e\nvc.log([where(), fromEval(), $.fileName]);");
|
||||
TEST_KEPT_MAP_BYTES.with(|b| b.set(None));
|
||||
s.execute("script.engine.drop", &json!({"name": "e"})).unwrap();
|
||||
let dropped = log(&mut s, "#targetengine e\nvc.log(typeof where);");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let ends = |names: &[String], ends: &[&str]| names.len() == ends.len() && names.iter().zip(ends).all(|(n, e)| n.ends_with(e));
|
||||
assert!(ends(&from_file, &["a/def.jsx", "a/inc.jsxinc", "a/ev.jsxinc", "b/caller.jsx"]), "{from_file:?}");
|
||||
let shown: Vec<String> = from_text[0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect();
|
||||
assert!(ends(&shown, &["a/def.jsx", "", "a/def.jsx", ""]) && shown[1].is_empty() && shown[3].is_empty(), "{shown:?}");
|
||||
assert!(text_kept[0].is_empty() && text_kept[1].ends_with("b/caller.jsx"), "{text_kept:?}");
|
||||
assert!(evicted[0].is_empty() && evicted[1].is_empty() && evicted[2].ends_with("b/caller.jsx"), "{evicted:?}");
|
||||
assert_eq!(dropped, json!(["undefined"]));
|
||||
}
|
||||
|
||||
/// A named engine keeps the places of its earlier runs' code within its budget, the oldest going
|
||||
/// first, and the code still runs once its place is gone.
|
||||
#[test]
|
||||
|
||||
@@ -374,6 +374,48 @@ fn script_eval_file_returns_last_value_and_shares_globals() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `$.fileName` names the file the code reading it is in: a function `$.evalFile` gave names its
|
||||
/// file after the file has returned, through nested files, and code an included file inserted names
|
||||
/// that file. Code that `eval` compiled names the file being run.
|
||||
#[test]
|
||||
fn script_file_name_names_the_file_of_the_code_that_reads_it() {
|
||||
let base = folder("filename");
|
||||
write(&base.join("main/inc.jsxinc"), "function fromInclude() { return $.fileName; }\nvar includedTop = $.fileName;");
|
||||
write(
|
||||
&base.join("main/sub/outer.jsx"),
|
||||
"function fromOuter() { return $.fileName; }\nvar before = $.fileName;\n$.evalFile('inner.jsx');\nvar after = $.fileName;\nfromInner();",
|
||||
);
|
||||
write(&base.join("main/sub/inner.jsx"), "function fromInner() { return $.fileName; }\n$.fileName;");
|
||||
let r = run(
|
||||
&base,
|
||||
"#include \"inc.jsxinc\"\nvar nested = $.evalFile('sub/outer.jsx');\n\
|
||||
vc.log([fromInclude(), includedTop, before, after, nested, fromOuter(), fromInner(), $.fileName, eval('$.fileName')]);",
|
||||
)
|
||||
.unwrap();
|
||||
let names: Vec<String> = r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect();
|
||||
let ends = [
|
||||
"main/inc.jsxinc",
|
||||
"main/inc.jsxinc",
|
||||
"sub/outer.jsx",
|
||||
"sub/outer.jsx",
|
||||
"sub/inner.jsx",
|
||||
"sub/outer.jsx",
|
||||
"sub/inner.jsx",
|
||||
"main/main.jsx",
|
||||
"main/main.jsx",
|
||||
];
|
||||
assert_eq!(names.len(), ends.len(), "{names:?}");
|
||||
for (name, end) in names.iter().zip(ends) {
|
||||
assert!(name.ends_with(end), "{name} ends with {end}: {names:?}");
|
||||
}
|
||||
// A script given as text has no name, and neither have the functions it defines.
|
||||
let r = Session::new()
|
||||
.execute("script.run", &json!({"source": "function f() { return $.fileName; }\nvc.log([f(), $.fileName]);", "name": "t.js"}))
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([["", ""]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_eval_file_outside_scope_refused() {
|
||||
let base = folder("evaloutside");
|
||||
|
||||
Reference in new issue
Block a user