mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 18:04:15 +00:00
Merge main into fix/undo-history-follows-memory-r
This commit is contained in:
@@ -2969,6 +2969,91 @@ fn image_trace_make_places_paths_over_the_image() {
|
||||
assert_eq!(paths[0].appearance.fill_paint(), Paint::solid(Color::rgb8(0, 0, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_keep_colors_traces_only_the_colors_listed() {
|
||||
// A light field with a black ring, a red square and a blue bar on it.
|
||||
let art = vectorcraft_trace::Raster::from_fn(200, 150, |x, y| {
|
||||
let r = (f64::from(x) + 0.5 - 70.0).hypot(f64::from(y) + 0.5 - 60.0);
|
||||
if (34.0..=40.0).contains(&r) {
|
||||
[0, 0, 0, 255]
|
||||
} else if (130..170).contains(&x) && (30..70).contains(&y) {
|
||||
[200, 40, 50, 255]
|
||||
} else if (30..170).contains(&x) && (110..130).contains(&y) {
|
||||
[40, 80, 200, 255]
|
||||
} else {
|
||||
[240, 240, 220, 255]
|
||||
}
|
||||
});
|
||||
let traced = |keep: Value| {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::IDENTITY);
|
||||
let params = json!({"params": {"mode": "color", "palette": "limited", "colors": 4, "keepColors": keep}});
|
||||
let r = s.execute("imageTrace.makeAndExpand", ¶ms)?;
|
||||
let g = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let fills: Vec<Paint> = g.children().unwrap().iter().map(|n| n.appearance.fill_paint()).collect();
|
||||
Ok::<_, EngineError>((r["colors"].clone(), fills))
|
||||
};
|
||||
let (black, red, blue, light) = (Color::rgb8(0, 0, 0), Color::rgb8(200, 40, 50), Color::rgb8(40, 80, 200), Color::rgb8(240, 240, 220));
|
||||
let has = |fills: &[Paint], c: Color| fills.contains(&Paint::solid(c));
|
||||
// Nothing listed: every color.
|
||||
let (colors, fills) = traced(json!([])).unwrap();
|
||||
assert_eq!(colors, 4);
|
||||
assert!([black, red, blue, light].into_iter().all(|c| has(&fills, c)), "{fills:?}");
|
||||
// The black and the red only.
|
||||
let (colors, fills) = traced(json!(["#000000", "#c8283c"])).unwrap();
|
||||
assert_eq!(colors, 2);
|
||||
assert!(has(&fills, black) && has(&fills, red), "{fills:?}");
|
||||
assert!(fills.iter().all(|f| *f == Paint::solid(black) || *f == Paint::solid(red)), "{fills:?}");
|
||||
// A color that is none is refused.
|
||||
let e = traced(json!(["#000000", "black"])).unwrap_err().to_string();
|
||||
assert!(e.contains("\"black\"") && e.contains("#rrggbb"), "{e}");
|
||||
assert!(find_command("imageTrace.make").unwrap().params.contains("keepColors?: [\"#rrggbb\"…]"));
|
||||
assert!(find_command("imageTrace.makeAndExpand").unwrap().params.contains("warnings: [text…] (as imageTrace.make)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_keep_colors_warns_about_colors_that_match_nothing() {
|
||||
// A light field with a black ring and a red square on it.
|
||||
let art = vectorcraft_trace::Raster::from_fn(200, 150, |x, y| {
|
||||
let r = (f64::from(x) + 0.5 - 70.0).hypot(f64::from(y) + 0.5 - 60.0);
|
||||
if (34.0..=40.0).contains(&r) {
|
||||
[0, 0, 0, 255]
|
||||
} else if (130..170).contains(&x) && (30..70).contains(&y) {
|
||||
[200, 40, 50, 255]
|
||||
} else {
|
||||
[240, 240, 220, 255]
|
||||
}
|
||||
});
|
||||
let traced = |params: Value| {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::IDENTITY);
|
||||
let r = s.execute("imageTrace.makeAndExpand", &json!({ "params": params })).unwrap();
|
||||
(r["paths"].as_u64().unwrap(), r["warnings"].clone())
|
||||
};
|
||||
let color = |keep: Value| traced(json!({"mode": "color", "palette": "limited", "colors": 3, "keepColors": keep}));
|
||||
// Every color listed is in the image: no warning.
|
||||
let (paths, warnings) = color(json!(["#000000", "#c8283c"]));
|
||||
assert!(paths > 0);
|
||||
assert_eq!(warnings, json!([]));
|
||||
// No color matches: nothing is traced, and the reply says why.
|
||||
assert_eq!(
|
||||
color(json!(["#ff00ff", "#00ffff"])),
|
||||
(0, json!(["Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff)."]))
|
||||
);
|
||||
// One color matches nothing: the others are traced, and that one is named.
|
||||
let (paths, warnings) = color(json!(["#000000", "#00ffff"]));
|
||||
assert!(paths > 0);
|
||||
assert_eq!(warnings, json!(["keepColors: none of the colors the trace found matches #00ffff, so nothing of it is traced."]));
|
||||
// Ignore Color leaves out the only color listed.
|
||||
let ignored =
|
||||
traced(json!({"mode": "color", "palette": "limited", "colors": 3, "keepColors": ["#000000"], "ignoreWhite": true, "ignoreColor": "#000000"}));
|
||||
assert_eq!(ignored, (0, json!(["Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists."])));
|
||||
// Flat Logo mode does not use the list.
|
||||
let (paths, warnings) = traced(json!({"mode": "logo", "keepColors": ["#ff00ff"]}));
|
||||
assert!(paths > 0);
|
||||
assert_eq!(warnings, json!(["Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds."]));
|
||||
}
|
||||
|
||||
/// #3098: a trace made away from the command (off the UI thread) and handed in makes the command's
|
||||
/// own edit, as one undo step; Cancel stops it; once its image has changed it no longer applies.
|
||||
#[test]
|
||||
|
||||
@@ -1440,17 +1440,17 @@ fn spiral_drags_with_alt_and_ctrl_change_its_segments_and_decay() {
|
||||
};
|
||||
s.select_tool("spiral", v).unwrap();
|
||||
let undo = undo_steps(&s);
|
||||
// Alt from a radius of 100 to 200: 10 segments become 14, one full wind of four quarter turns.
|
||||
// Alt from a radius of 100 to 200: preserving the inner end adds three full winds.
|
||||
let (anchors, outer) = spiral(&mut s, Mods { alt: true, ..Mods::default() }, (300.0, 100.0));
|
||||
assert_eq!(anchors, 15);
|
||||
assert_eq!(anchors, 23);
|
||||
assert!(near(outer, Point::new(300.0, 100.0)), "{outer:?}");
|
||||
assert_eq!(s.tool_options()["segments"], json!(14));
|
||||
// Ctrl/Cmd from 100 to 50: the decay rises from 80 % to 80 × 2^(1/14) %.
|
||||
assert_eq!(s.tool_options()["segments"], json!(22));
|
||||
// Ctrl/Cmd from 100 to 50: the decay rises from 80 % to 80 × 2^(4/22) %.
|
||||
let (anchors, outer) = spiral(&mut s, Mods { cmd: true, ..Mods::default() }, (150.0, 100.0));
|
||||
assert_eq!(anchors, 15);
|
||||
assert_eq!(anchors, 23);
|
||||
assert!(near(outer, Point::new(150.0, 100.0)), "{outer:?}");
|
||||
let decay = s.tool_options()["decay"].as_f64().unwrap();
|
||||
assert!((decay - 80.0 * 2f64.powf(1.0 / 14.0)).abs() < 1e-9, "{decay}");
|
||||
assert!((decay - 80.0 * 2f64.powf(4.0 / 22.0)).abs() < 1e-9, "{decay}");
|
||||
assert_eq!(undo_steps(&s) - undo, 2, "one undo step a spiral");
|
||||
}
|
||||
|
||||
|
||||
@@ -343,23 +343,139 @@ fn artboard_commands_read_the_recorded_selected_artboards() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `edit.copy` and `edit.cut` run the Artboard tool's copy and take no artboards, so their entries
|
||||
/// stay as given, apart from the locked-art preference the Artboard tool's copy notes.
|
||||
/// A Cut or Copy with the Artboard tool replays on the artboards it took in a new session, where
|
||||
/// another tool is chosen: with nothing selected there, and with an object selected that a Cut or
|
||||
/// Copy of objects would take. What it pastes is the same.
|
||||
#[test]
|
||||
fn edit_copy_and_cut_with_the_artboard_tool_record_their_params_as_given() {
|
||||
fn edit_copy_and_cut_with_the_artboard_tool_replay_on_its_artboards() {
|
||||
for id in ["edit.copy", "edit.cut"] {
|
||||
for select in ["select.all", "select.none"] {
|
||||
let mut s = Session::new();
|
||||
second_artboard_selected(&mut s);
|
||||
s.execute(select, &json!({})).unwrap();
|
||||
s.execute(id, &json!({})).unwrap();
|
||||
let boards = if id == "edit.cut" { 2 } else { 3 };
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), boards, "{id} after {select}");
|
||||
assert_eq!(documents(&replayed(&s)), documents(&s), "{id} after {select}");
|
||||
let entry = s.journal.last().unwrap().clone();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), boards + 1, "{id} after {select}");
|
||||
let r = replayed(&s);
|
||||
assert_ne!(r.tool_id(), "artboard");
|
||||
assert_eq!(documents(&r), documents(&s), "{id} after {select}");
|
||||
assert_eq!(entry, (id.to_string(), json!({"selectedArtboards": [1], "art": true, "lockedAndHidden": false})), "{id} after {select}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Copy after a Paste takes the pasted artboards, which the Artboard tool selected, and so does its
|
||||
/// replay, though `edit.paste` selects nothing in a new session's tool.
|
||||
#[test]
|
||||
fn edit_copy_after_a_paste_with_the_artboard_tool_replays_on_the_pasted_artboards() {
|
||||
let mut s = Session::new();
|
||||
second_artboard_selected(&mut s);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap().1, json!({"selectedArtboards": [3], "art": true, "lockedAndHidden": false}));
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 5);
|
||||
assert_eq!(documents(&replayed(&s)), documents(&s));
|
||||
}
|
||||
|
||||
/// A recorded action keeps `edit.copy` and `edit.cut` as given, so when it plays they follow the tool
|
||||
/// chosen then, and a batch step records and leaves out the same values. The locked-art preference
|
||||
/// that the Artboard tool's copy notes stays in the action.
|
||||
#[test]
|
||||
fn edit_copy_and_cut_with_the_artboard_tool_record_nothing_for_an_action() {
|
||||
for id in ["edit.copy", "edit.cut"] {
|
||||
let mut s = Session::new();
|
||||
second_artboard_selected(&mut s);
|
||||
let start = second_artboard_selected(&mut s);
|
||||
s.execute(id, &json!({})).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_string(), json!({"lockedAndHidden": false})), "{id}");
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action, [(id.to_string(), json!({"lockedAndHidden": false}))], "{id}");
|
||||
let mut played = Session::new();
|
||||
played.execute("file.new", &json!({"width": 400, "height": 200, "created": null})).unwrap();
|
||||
played.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
played.execute(id, &action[0].1).unwrap();
|
||||
assert_eq!(played.doc().unwrap().doc.artboards.len(), 1, "{id}");
|
||||
assert!(played.clipboard.artboards.is_empty(), "{id}");
|
||||
assert_eq!(played.clipboard.nodes.len(), 1, "{id}");
|
||||
|
||||
let mut s = Session::new();
|
||||
let start = second_artboard_selected(&mut s);
|
||||
let steps = json!([{"command": id, "params": {}}, {"command": "edit.paste", "params": {}}]);
|
||||
s.execute("command.batch", &json!({ "commands": steps })).unwrap();
|
||||
assert_eq!(
|
||||
s.journal.last().unwrap().1["commands"][0]["params"],
|
||||
json!({"selectedArtboards": [1], "art": true, "lockedAndHidden": false}),
|
||||
"{id}"
|
||||
);
|
||||
assert_eq!(documents(&replayed(&s)), documents(&s), "{id}");
|
||||
assert_eq!(s.journal_for_action(start)[0].1["commands"][0]["params"], json!({"lockedAndHidden": false}), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Without the Artboard tool, Cut and Copy of objects record nothing more than they did.
|
||||
#[test]
|
||||
fn edit_copy_and_cut_of_objects_record_their_params_as_given() {
|
||||
for id in ["edit.copy", "edit.cut"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200, "created": null})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute(id, &json!({})).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_string(), json!({})), "{id}");
|
||||
assert!(s.clipboard.artboards.is_empty(), "{id}");
|
||||
assert_eq!(documents(&replayed(&s)), documents(&s), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A recorded `selectedArtboards` needs only a document and is checked as `indices` is, as are `art`
|
||||
/// and the rule that a cut leaves one artboard. A failed call changes neither the document nor the
|
||||
/// clipboard.
|
||||
#[test]
|
||||
fn edit_copy_and_cut_read_the_recorded_artboards() {
|
||||
for id in ["edit.copy", "edit.cut"] {
|
||||
assert!(matches!(Session::new().execute(id, &json!({"selectedArtboards": [0]})), Err(crate::EngineError::Disabled(..))));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200, "created": null})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 1010, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id}");
|
||||
let before = documents(&s);
|
||||
for bad in [
|
||||
json!({"selectedArtboards": [9]}),
|
||||
json!({"selectedArtboards": []}),
|
||||
json!({"selectedArtboards": "1"}),
|
||||
json!({"selectedArtboards": null}),
|
||||
json!({"selectedArtboards": [1], "art": "yes"}),
|
||||
] {
|
||||
let err = s.execute(id, &bad).unwrap_err().to_string();
|
||||
assert!(err.contains(id) || err.contains("no such artboard"), "{id} {bad}: {err}");
|
||||
assert_eq!(documents(&s), before, "{id} {bad}");
|
||||
assert!(s.clipboard.artboards.is_empty(), "{id} {bad}");
|
||||
}
|
||||
s.execute(id, &json!({"selectedArtboards": [1], "art": false})).unwrap();
|
||||
assert_eq!(s.clipboard.artboards.len(), 1, "{id}");
|
||||
assert!(s.clipboard.nodes.is_empty(), "{id}");
|
||||
assert_eq!(s.journal.last().unwrap().1, json!({"selectedArtboards": [1], "art": false}), "{id}");
|
||||
// Objects selected, `art` is still checked.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let err = s.execute(id, &json!({"art": "yes"})).unwrap_err().to_string();
|
||||
assert!(err.contains(id), "{id}: {err}");
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200, "created": null})).unwrap();
|
||||
assert!(s.execute("edit.cut", &json!({"selectedArtboards": [0]})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
|
||||
/// `artboard.duplicate` and the cut and copy record the tool's Move/Copy Artwork option: replayed in
|
||||
/// a new session, where the option is on, the art stays behind as it did.
|
||||
#[test]
|
||||
fn artboard_commands_record_the_tools_move_art_option() {
|
||||
for id in ["artboard.duplicate", "artboard.cut", "artboard.copy"] {
|
||||
for id in ["artboard.duplicate", "artboard.cut", "artboard.copy", "edit.cut", "edit.copy"] {
|
||||
let mut s = Session::new();
|
||||
second_artboard_selected(&mut s);
|
||||
s.set_tool_option("moveArt", &json!(false));
|
||||
|
||||
@@ -164,6 +164,48 @@ fn a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_
|
||||
}
|
||||
}
|
||||
|
||||
#[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).
|
||||
for (effect, params, item) in [
|
||||
("warp.arc", json!({"bend": 40}), json!(null)),
|
||||
("warp.bulge", json!({"bend": 40, "orientation": "vertical"}), json!(null)),
|
||||
("warp.inflate", json!({"bend": 40}), json!(0)),
|
||||
] {
|
||||
let mut s = session();
|
||||
let id = gradient_rect(&mut s, Rect::new(40.0, 70.0, 160.0, 130.0), white_black(), false);
|
||||
// Placed from a quarter of the way across to the right edge.
|
||||
run(&mut s, "paint.setGradientGeom", json!({"start": [70, 100], "end": [160, 100], "stroke": false}));
|
||||
let placed = s.doc().unwrap().doc.node(id).and_then(|n| match n.appearance.fill_paint() {
|
||||
vectorcraft_color::Paint::Gradient(g) => g.geom,
|
||||
_ => None,
|
||||
});
|
||||
assert!(placed.is_some(), "the fill's gradient is placed");
|
||||
run(&mut s, "effect.apply", json!({"effect": effect, "params": params, "ids": [id.0], "item": item}));
|
||||
let before = render(&s);
|
||||
// Fill alone: the gradient becomes strips inside the outline the warp makes.
|
||||
run(&mut s, "object.expand", json!({"object": false, "stroke": false, "steps": 64}));
|
||||
let after = render(&s);
|
||||
let diff = mean_diff(&before, &after);
|
||||
assert!(diff < 1.0, "{effect} {params} on item {item}: mean difference {diff}");
|
||||
// The ramp's midpoint, 115 pt before the warp, moves and scales with the warped bounds.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let b = doc.node(doc.layers[0].id).and_then(|l| l.geometric_bounds()).unwrap();
|
||||
let want = b.x0 + (115.0 - 40.0) / 120.0 * b.width();
|
||||
assert!((want - 115.0).abs() > 2.0, "{effect} {params}: the warp moves the midpoint ({b:?})");
|
||||
let red = |x: usize| f64::from(after.pixels[(100 * 200 + x) * 4]);
|
||||
// White turns dark once on row 100, and gradually, so the crossing is the ramp's midpoint
|
||||
// and not an edge of the outline.
|
||||
let crossings: Vec<usize> =
|
||||
(b.x0.ceil() as usize + 3..b.x1.floor() as usize - 4).filter(|&x| red(x) >= 127.5 && red(x + 1) < 127.5).collect();
|
||||
assert_eq!(crossings.len(), 1, "{effect} {params}: white turns dark once on row 100: {crossings:?}");
|
||||
let x = crossings[0];
|
||||
assert!(red(x - 2) - red(x + 3) < 100.0, "{effect} {params}: the ramp, not an edge: {} to {}", red(x - 2), red(x + 3));
|
||||
let half = x as f64 + 0.5 + (red(x) - 127.5) / (red(x) - red(x + 1));
|
||||
assert!((half - want).abs() < 1.0, "{effect} {params} on item {item}: the midpoint is at {half}, want {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_strips_match_the_gradient_samples() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Outline Stroke (`object.path.outlineStroke`) and the live Outline Stroke effect produce the
|
||||
//! stroke as the canvas paints it: dashes, arrowheads, width profiles, alignment, every stroke
|
||||
//! item in order, with the stroke's opacity and blend mode moved to the new fill.
|
||||
//! item in order, with the stroke's opacity and blend mode moved to the new fill. Outline Stroke,
|
||||
//! Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the
|
||||
//! object's geometry effects and each stroke's own to the path before outlining that stroke.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
@@ -180,6 +182,329 @@ fn the_live_effect_outlines_the_stroke_it_sits_on() {
|
||||
assert!(close(g.bounds().unwrap(), Rect::new(0.0, 49.0, 100.0, 51.0), 0.01), "{:?}", g.bounds());
|
||||
}
|
||||
|
||||
fn render(s: &Session) -> vectorcraft_render::Rendered {
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
vectorcraft_render::Renderer::new().render(&doc, 400, 300, vectorcraft_geom::Affine::IDENTITY, &opts)
|
||||
}
|
||||
|
||||
/// Pixels whose color differs by more than `tol` in any channel.
|
||||
fn differing(a: &vectorcraft_render::Rendered, b: &vectorcraft_render::Rendered, tol: u8) -> usize {
|
||||
a.pixels
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(b.pixels.as_chunks::<4>().0)
|
||||
.filter(|(p, q)| p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > tol))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Does `n` or anything in it have a geometry effect, its own or a fill's or stroke's?
|
||||
fn has_geometry_effects(n: &Node) -> bool {
|
||||
let geometry = |e: &vectorcraft_doc::Effect| vectorcraft_render::effects::is_geometry(&e.id);
|
||||
let mut found = false;
|
||||
n.walk(&mut |m| found |= m.appearance.effects.iter().any(geometry) || m.appearance.items.iter().any(|i| i.effects().iter().any(geometry)));
|
||||
found
|
||||
}
|
||||
|
||||
/// A selected 100 pt square at (150, 100) with a 4 pt black stroke and fill `fill` (paint.setFill's),
|
||||
/// and `effects` (effect.apply's `effect` and `params`) on appearance item `item` (`null`: on the
|
||||
/// object).
|
||||
fn square_with(s: &mut Session, fill: Value, item: Value, effects: &[(&str, Value)]) {
|
||||
s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &fill).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
for (effect, params) in effects {
|
||||
s.execute("effect.apply", &json!({"effect": effect, "params": params, "item": item})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometry effects the tests put on the stroke or on the object.
|
||||
fn geometry_effects() -> [(&'static str, Value); 2] {
|
||||
[("path.offsetPath", json!({"offset": 10})), ("distort.zigZag", json!({"size": 6, "ridges": 3}))]
|
||||
}
|
||||
|
||||
/// The commands that outline strokes: Outline Stroke, Expand with Stroke alone, and Flatten
|
||||
/// Transparency with Convert All Strokes to Outlines.
|
||||
fn outlining() -> [(&'static str, Value); 3] {
|
||||
[
|
||||
("object.path.outlineStroke", json!({})),
|
||||
("object.expand", json!({"object": false, "fill": false, "stroke": true})),
|
||||
("object.flattenTransparency", json!({"strokesToOutlines": true})),
|
||||
]
|
||||
}
|
||||
|
||||
/// What `command` with `params` leaves in place of the selected object.
|
||||
fn outlined_by(s: &mut Session, command: &str, params: &Value) -> Node {
|
||||
let r = s.execute(command, params).unwrap_or_else(|e| panic!("{command}: {e}"));
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
/// For each command in [`outlining`] and each of [`geometry_effects`] on `item` of a square filled
|
||||
/// with `fill`: the pixels that differ by more than 64 from the canvas before, and whether a
|
||||
/// geometry effect is left on the result.
|
||||
fn outlined_as_drawn(fill: Value, item: Value) -> Vec<(&'static str, &'static str, usize, bool)> {
|
||||
let mut results = vec![];
|
||||
for (command, p) in outlining() {
|
||||
for (effect, params) in geometry_effects() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, fill.clone(), item.clone(), &[(effect, params)]);
|
||||
let before = render(&s);
|
||||
let n = outlined_by(&mut s, command, &p);
|
||||
results.push((command, effect, differing(&before, &render(&s), 64), has_geometry_effects(&n)));
|
||||
}
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
/// What [`outlined_as_drawn`] gives when every outline looks as the canvas drew the object.
|
||||
fn as_drawn() -> Vec<(&'static str, &'static str, usize, bool)> {
|
||||
outlining().iter().flat_map(|(command, _)| geometry_effects().map(|(effect, _)| (*command, effect, 0, false))).collect()
|
||||
}
|
||||
|
||||
/// A stroke's own geometry effects reshape the path it strokes, as on the canvas: the outline is
|
||||
/// the stroke of the offset or zig-zagged path, not the stroke's outline offset or zig-zagged.
|
||||
#[test]
|
||||
fn a_geometry_effect_on_the_stroke_shapes_the_path_it_outlines() {
|
||||
assert_eq!(outlined_as_drawn(json!({"none": true}), json!(1)), as_drawn());
|
||||
// The stroke of the square offset by 10: 4 pt wide around a 120 pt square.
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"none": true}), json!(1), &[("path.offsetPath", json!({"offset": 10}))]);
|
||||
let n = outline(&mut s);
|
||||
assert!(close(n.geometric_bounds().unwrap(), Rect::new(138.0, 88.0, 262.0, 212.0), 0.01), "{:?}", n.geometric_bounds());
|
||||
assert!(near(area(&n), 124.0 * 124.0 - 116.0 * 116.0, 2.0), "{}", area(&n));
|
||||
}
|
||||
|
||||
/// A stroke whose geometry effect leaves no path paints nothing on the canvas, and outlining it
|
||||
/// replaces the live stroke with an empty group.
|
||||
#[test]
|
||||
fn a_stroke_its_effects_empty_is_outlined_to_nothing() {
|
||||
for (command, p) in outlining() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"none": true}), json!(1), &[("path.offsetPath", json!({"offset": -60}))]);
|
||||
let before = render(&s);
|
||||
let n = outlined_by(&mut s, command, &p);
|
||||
assert!(matches!(&n.kind, NodeKind::Group { children, .. } if children.is_empty()), "{command}: {n:?}");
|
||||
let mut stroked = false;
|
||||
for layer in &s.doc().unwrap().doc.layers {
|
||||
layer.walk(&mut |m| stroked |= m.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))));
|
||||
}
|
||||
assert!(!stroked, "{command} left a live stroke");
|
||||
assert_eq!(differing(&before, &render(&s), 64), 0, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A drop shadow on a stroke with a geometry effect stays on the outline, which draws as the
|
||||
/// stroke did.
|
||||
#[test]
|
||||
fn the_outline_of_a_reshaped_stroke_keeps_its_drop_shadow() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"none": true}), json!(1), &[("path.offsetPath", json!({"offset": 10})), ("stylize.dropShadow", json!({}))]);
|
||||
let before = render(&s);
|
||||
let n = outline(&mut s);
|
||||
let kept: Vec<&str> = n.appearance.items.iter().flat_map(|i| i.effects()).map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(kept, ["stylize.dropShadow"]);
|
||||
assert_eq!(differing(&before, &render(&s), 64), 0, "the shadowed outline draws as the stroke did");
|
||||
}
|
||||
|
||||
/// The brush art of a brushed stroke with a geometry effect follows the path the effect makes.
|
||||
#[test]
|
||||
fn a_brush_draws_along_the_path_the_stroke_effects_make() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"none": true}), json!(1), &[("path.offsetPath", json!({"offset": 10}))]);
|
||||
s.execute("brush.apply", &json!({"name": "Tapered Stroke"})).unwrap();
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
let st = s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().cloned().unwrap();
|
||||
assert!(st.brush.is_some() && st.effects.len() == 1, "{st:?}");
|
||||
let before = render(&s);
|
||||
let n = outline(&mut s);
|
||||
assert!(!vectorcraft_brush::has_brush(&n) && !has_geometry_effects(&n), "brush art: {n:?}");
|
||||
assert_eq!(differing(&before, &render(&s), 64), 0, "the brush art draws as the brushed stroke did");
|
||||
}
|
||||
|
||||
/// The object's geometry effects reshape the path its fills paint and its strokes outline, as on
|
||||
/// the canvas, and do not stay on the result.
|
||||
#[test]
|
||||
fn a_geometry_effect_on_the_object_shapes_the_path_it_outlines() {
|
||||
assert_eq!(outlined_as_drawn(json!({"color": "#33aa55"}), Value::Null), as_drawn());
|
||||
}
|
||||
|
||||
/// The canvas paints a gradient fill or stroke on each copy that the object's Transform effect
|
||||
/// makes by itself; the outlined result draws the same, with the gradient fitted to each copy.
|
||||
#[test]
|
||||
fn each_transform_copy_keeps_its_own_gradient() {
|
||||
let mut differ = vec![];
|
||||
for on_stroke in [false, true] {
|
||||
for (command, p) in outlining() {
|
||||
let mut s = session();
|
||||
let fill = if on_stroke { json!({"none": true}) } else { json!({"gradient": {"kind": "linear"}}) };
|
||||
square_with(&mut s, fill, Value::Null, &[("distort.transform", json!({"moveH": 120, "copies": 1}))]);
|
||||
if on_stroke {
|
||||
s.execute("paint.setStroke", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 12})).unwrap();
|
||||
}
|
||||
let before = render(&s);
|
||||
outlined_by(&mut s, command, &p);
|
||||
differ.push((on_stroke, command, differing(&before, &render(&s), 64)));
|
||||
}
|
||||
}
|
||||
let none_differ: Vec<_> = [false, true].into_iter().flat_map(|on_stroke| outlining().map(|(command, _)| (on_stroke, command, 0))).collect();
|
||||
assert_eq!(differ, none_differ);
|
||||
}
|
||||
|
||||
/// With Scale Strokes & Effects on, the canvas draws the stroke of a solid square that its
|
||||
/// Transform effect scales to 200% at 8 pt; the outlined result draws the same.
|
||||
#[test]
|
||||
fn a_transform_that_scales_strokes_outlines_the_scaled_stroke() {
|
||||
let scale = json!({"scaleH": 200, "scaleV": 200, "strokes": true});
|
||||
let mut differ = vec![];
|
||||
for (command, p) in outlining() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"color": "#33aa55"}), Value::Null, &[("distort.transform", scale.clone())]);
|
||||
let before = render(&s);
|
||||
outlined_by(&mut s, command, &p);
|
||||
differ.push((command, differing(&before, &render(&s), 64)));
|
||||
}
|
||||
let none_differ: Vec<_> = outlining().map(|(command, _)| (command, 0)).into_iter().collect();
|
||||
assert_eq!(differ, none_differ);
|
||||
}
|
||||
|
||||
/// Random in a Transform effect takes its seed from the object's id. The outline draws as the
|
||||
/// canvas drew the object with Random in a Transform effect that copies a gradient square, in a
|
||||
/// Transform effect on the stroke of such a square, and in a Transform effect on the fill of a
|
||||
/// plain square.
|
||||
#[test]
|
||||
fn outlines_keep_the_random_transforms_the_canvas_drew() {
|
||||
let random = json!({"moveH": 30, "moveV": 30, "rotate": 40, "random": true});
|
||||
let cases = [
|
||||
("random copies", json!({"gradient": {"kind": "linear"}}), json!({"moveH": 120, "rotate": 30, "copies": 1, "random": true}), None),
|
||||
("copies, random stroke", json!({"gradient": {"kind": "linear"}}), json!({"moveH": 120, "copies": 1}), Some(1)),
|
||||
("random fill", json!({"color": "#33aa55"}), json!({}), Some(0)),
|
||||
];
|
||||
let mut differ = vec![];
|
||||
for (case, fill, object, item) in &cases {
|
||||
for (command, p) in outlining() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, fill.clone(), Value::Null, &[]);
|
||||
if object != &json!({}) {
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": object})).unwrap();
|
||||
}
|
||||
s.execute("stroke.set", &json!({"weight": 12})).unwrap();
|
||||
if let Some(item) = item {
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": random, "item": item})).unwrap();
|
||||
}
|
||||
let before = render(&s);
|
||||
outlined_by(&mut s, command, &p);
|
||||
differ.push((*case, command, differing(&before, &render(&s), 64)));
|
||||
}
|
||||
}
|
||||
let none_differ: Vec<_> = cases.iter().flat_map(|(case, ..)| outlining().map(|(command, _)| (*case, command, 0))).collect();
|
||||
assert_eq!(differ, none_differ);
|
||||
}
|
||||
|
||||
/// For each command in [`outlining`] on a stroke-only square with `effects` on appearance item
|
||||
/// `item`: the pixels that differ by more than 64 from the canvas before, whether a geometry
|
||||
/// effect is left on the result, and (for Outline Stroke) the outline's box and area.
|
||||
fn outlined_square(item: Value, effects: &[(&str, Value)], hide: bool) -> (Vec<(&'static str, usize, bool)>, Rect, f64) {
|
||||
let mut results = vec![];
|
||||
let mut shape = (Rect::ZERO, 0.0);
|
||||
for (command, p) in outlining() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"none": true}), item.clone(), effects);
|
||||
if hide {
|
||||
for index in 0..effects.len() {
|
||||
s.execute("effect.setParams", &json!({"index": index, "visible": false, "item": item})).unwrap();
|
||||
}
|
||||
}
|
||||
let before = render(&s);
|
||||
let n = outlined_by(&mut s, command, &p);
|
||||
if command == "object.path.outlineStroke" {
|
||||
shape = (n.geometric_bounds().unwrap(), area(&n));
|
||||
}
|
||||
results.push((command, differing(&before, &render(&s), 64), has_geometry_effects(&n)));
|
||||
}
|
||||
(results, shape.0, shape.1)
|
||||
}
|
||||
|
||||
/// What [`outlined_square`] gives for each command when the outline draws as the canvas did and
|
||||
/// keeps no geometry effect.
|
||||
fn drawn_plain() -> Vec<(&'static str, usize, bool)> {
|
||||
outlining().map(|(command, _)| (command, 0, false)).into_iter().collect()
|
||||
}
|
||||
|
||||
/// A path with no effects outlines its own stroke: 4 pt wide around the 100 pt square.
|
||||
#[test]
|
||||
fn a_path_without_effects_outlines_its_own_stroke() {
|
||||
let (results, bounds, a) = outlined_square(Value::Null, &[], false);
|
||||
assert_eq!(results, drawn_plain());
|
||||
assert!(close(bounds, Rect::new(148.0, 98.0, 252.0, 202.0), 0.01), "{bounds:?}");
|
||||
assert!(near(a, 104.0 * 104.0 - 96.0 * 96.0, 0.5), "{a}");
|
||||
}
|
||||
|
||||
/// Round Corners on the object rounds the path whose stroke is outlined, with the radius in
|
||||
/// points as the canvas draws it: corners of radius 12 outside and 8 inside.
|
||||
#[test]
|
||||
fn round_corners_on_the_object_round_the_stroke_it_outlines() {
|
||||
let (results, bounds, a) = outlined_square(Value::Null, &[("stylize.roundCorners", json!({"radius": 10}))], false);
|
||||
assert_eq!(results, drawn_plain());
|
||||
assert!(close(bounds, Rect::new(148.0, 98.0, 252.0, 202.0), 0.01), "{bounds:?}");
|
||||
let rounded = 104.0 * 104.0 - 96.0 * 96.0 - (4.0 - std::f64::consts::PI) * (12.0 * 12.0 - 8.0 * 8.0);
|
||||
assert!(near(a, rounded, 2.0), "{a}, rounded {rounded}");
|
||||
}
|
||||
|
||||
/// A hidden geometry effect, on the object or on the stroke, does not draw on the canvas and does
|
||||
/// not shape the outline.
|
||||
#[test]
|
||||
fn a_hidden_geometry_effect_does_not_shape_the_outline() {
|
||||
for item in [Value::Null, json!(1)] {
|
||||
let (results, bounds, a) = outlined_square(item.clone(), &geometry_effects(), true);
|
||||
let drawn: Vec<_> = results.iter().map(|(command, differ, _)| (*command, *differ)).collect();
|
||||
assert_eq!(drawn, drawn_plain().into_iter().map(|(command, differ, _)| (command, differ)).collect::<Vec<_>>(), "item {item}");
|
||||
assert!(close(bounds, Rect::new(148.0, 98.0, 252.0, 202.0), 0.01), "item {item}: {bounds:?}");
|
||||
assert!(near(a, 104.0 * 104.0 - 96.0 * 96.0, 0.5), "item {item}: {a}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An effect on the object that is not a geometry effect, such as a Gaussian Blur, stays on the
|
||||
/// result of Outline Stroke and Expand while the geometry effect shapes the path. Flatten
|
||||
/// Transparency renders raster effects into an image instead.
|
||||
#[test]
|
||||
fn an_effect_that_is_not_geometry_stays_on_the_result() {
|
||||
for (command, p) in outlining().into_iter().filter(|(command, _)| *command != "object.flattenTransparency") {
|
||||
let mut s = session();
|
||||
square_with(
|
||||
&mut s,
|
||||
json!({"color": "#33aa55"}),
|
||||
Value::Null,
|
||||
&[("distort.zigZag", json!({"size": 6, "ridges": 3})), ("blur.gaussian", json!({}))],
|
||||
);
|
||||
let n = outlined_by(&mut s, command, &p);
|
||||
let kept: Vec<&str> = n.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(kept, ["blur.gaussian"], "{command}");
|
||||
assert!(!has_geometry_effects(&n), "{command}: {n:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo after outlining a path with geometry effects on the object and on its stroke gives back
|
||||
/// the path as it was, effects included, and its selection.
|
||||
#[test]
|
||||
fn undo_gives_back_the_path_with_its_effects() {
|
||||
for (command, p) in outlining() {
|
||||
let mut s = session();
|
||||
square_with(&mut s, json!({"color": "#33aa55"}), Value::Null, &[("distort.zigZag", json!({"size": 6, "ridges": 3}))]);
|
||||
s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": 10}, "item": 1})).unwrap();
|
||||
let before = s.doc().unwrap().doc.layers.clone();
|
||||
let selected = s.doc().unwrap().selection.objects.clone();
|
||||
outlined_by(&mut s, command, &p);
|
||||
assert_ne!(s.doc().unwrap().doc.layers, before, "{command} changed nothing");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before, "{command}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, selected, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushed_strokes_outline_to_their_brush_art() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -64,7 +64,7 @@ fn an_unknown_key_is_named_with_the_nearest_accepted_one() {
|
||||
("file.new", json!(null)),
|
||||
// Keys listed by reference, and any key where the description says so.
|
||||
("file.newPresets.save", json!({"name": "a", "width": 300})),
|
||||
("document.export", json!({"format": "png", "anyFormatOption": 1})),
|
||||
("document.export", json!({"format": "png", "styling": "style"})),
|
||||
// Not a command: running it says so.
|
||||
("no.such", json!({"x": 1})),
|
||||
] {
|
||||
@@ -74,6 +74,109 @@ fn an_unknown_key_is_named_with_the_nearest_accepted_one() {
|
||||
assert!(check_keys("x", "{a, …as file.new}", &json!({"b": 1})).is_err());
|
||||
}
|
||||
|
||||
/// An export's options: a key no format reads is refused, at the top level and in the PDF objects,
|
||||
/// under each command that takes them.
|
||||
#[test]
|
||||
fn export_options_refuse_a_key_no_format_reads() {
|
||||
for id in ["document.export", "document.exportSelection", "document.serialize"] {
|
||||
assert_eq!(
|
||||
refusal(id, json!({"format": "pdf", "standard": "pdfX4", "noSuchOption": true})),
|
||||
"unknown parameter `noSuchOption`; no format takes it (see document.formats)"
|
||||
);
|
||||
assert_eq!(refusal(id, json!({"format": "pdf", "standardd": "pdfX4"})), "unknown parameter `standardd`; did you mean `standard`?");
|
||||
assert_eq!(
|
||||
refusal(id, json!({"format": "pdf", "options": {"standard": "pdfX4"}})),
|
||||
"unknown parameter `options`; no format takes it (see document.formats)"
|
||||
);
|
||||
}
|
||||
// A command that writes one format refuses another format's option, and says which format.
|
||||
for (id, why) in [
|
||||
("document.exportPdf", "PDF doesn't take it"),
|
||||
("document.pdfSettings", "PDF doesn't take it"),
|
||||
("pdf.preset.save", "PDF doesn't take it"),
|
||||
("document.exportEps", "EPS doesn't take it"),
|
||||
("document.exportDxf", "DXF doesn't take it"),
|
||||
] {
|
||||
for key in ["noSuchOption", "quality"] {
|
||||
assert_eq!(refusal(id, json!({key: 1})), format!("unknown parameter `{key}`; {why} (see document.formats)"));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
refusal("document.exportEps", json!({"flattener": {"balanse": 50}})),
|
||||
"unknown parameter `flattener.balanse`; did you mean `flattener.balance`?"
|
||||
);
|
||||
assert!(refusal("document.exportDxf", json!({"flattener": {}})).contains("DXF doesn't take it"));
|
||||
assert!(refusal("document.exportEps", json!({"marks": {}})).contains("EPS doesn't take it"));
|
||||
for id in ["document.pdfSettings", "pdf.preset.save"] {
|
||||
assert!(refusal(id, json!({"marks": {"useDocumentBleed": true}})).starts_with("unknown parameter `marks.useDocumentBleed`;"), "{id}");
|
||||
}
|
||||
for (given, message) in [
|
||||
(json!({"marks": {"useDocumentBleed": true}}), "unknown parameter `marks.useDocumentBleed`; `marks` takes:"),
|
||||
(json!({"bleed": {"useDocumen": true}}), "unknown parameter `bleed.useDocumen`; did you mean `bleed.useDocument`?"),
|
||||
(json!({"output": {"intent": "x"}}), "unknown parameter `output.intent`;"),
|
||||
(json!({"advanced": {"outlineTxt": true}}), "unknown parameter `advanced.outlineTxt`; did you mean `advanced.outlineText`?"),
|
||||
(json!({"security": {"openPasswrd": "x"}}), "unknown parameter `security.openPasswrd`; did you mean `security.openPassword`?"),
|
||||
(json!({"compression": {"color": {"dpi": 300}}}), "unknown parameter `compression.color.dpi`;"),
|
||||
(json!({"flattener": {"balanse": 50}}), "unknown parameter `flattener.balanse`; did you mean `flattener.balance`?"),
|
||||
] {
|
||||
for id in ["document.export", "document.exportPdf"] {
|
||||
let got = refusal(id, given.clone());
|
||||
assert!(got.starts_with(message), "{id} {given}: {got}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The check passes each key `document.formats` lists, each key a command's own description names,
|
||||
/// and each field of the PDF settings and the flattener options. A key an encoder reads that none
|
||||
/// of these names is outside this test.
|
||||
#[test]
|
||||
fn export_options_pass_every_listed_key() {
|
||||
use crate::cmd::fileio::{FORMATS, dxf, eps, pdf::OPTIONS};
|
||||
for f in FORMATS.iter().filter(|f| f.write) {
|
||||
for o in f.options {
|
||||
let params = json!({"format": f.id, o.name: null});
|
||||
assert!(check_params("document.export", ¶ms).is_ok(), "{params}");
|
||||
}
|
||||
}
|
||||
for (id, options) in [("document.exportEps", eps::OPTIONS), ("document.exportDxf", dxf::OPTIONS), ("document.exportPdf", OPTIONS)] {
|
||||
for o in options {
|
||||
assert!(check_params(id, &json!({o.name: null})).is_ok(), "{id} {}", o.name);
|
||||
}
|
||||
}
|
||||
for id in [
|
||||
"document.export",
|
||||
"document.exportSelection",
|
||||
"document.serialize",
|
||||
"document.exportPdf",
|
||||
"document.pdfSettings",
|
||||
"pdf.preset.save",
|
||||
"document.exportEps",
|
||||
"document.exportDxf",
|
||||
] {
|
||||
// An export reads these two when it writes over the file a lossy document came from. The
|
||||
// PDF settings and preset commands take them through document.exportPdf's description.
|
||||
check_params(id, &json!({"path": "a", "acknowledgeLoss": true})).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
let keys = doc_keys(find_command(id).unwrap().params).unwrap().keys;
|
||||
let refused: Vec<&str> = keys.into_iter().filter(|key| check_params(id, &json!({*key: null})).is_err()).collect();
|
||||
// `document.exportPdf`'s description explains the page boxes as `BleedBox = …` between its
|
||||
// keys, which reads as two more keys.
|
||||
let prose = if id == "document.exportPdf" { vec!["BleedBox", "MediaBox"] } else { vec![] };
|
||||
assert_eq!(refused, prose, "{id} names and refuses these");
|
||||
}
|
||||
let settings = serde_json::to_value(vectorcraft_pdf::PdfSettings::default()).unwrap();
|
||||
for key in settings.as_object().unwrap().keys() {
|
||||
assert!(OPTIONS.iter().any(|o| o.name == key), "document.formats doesn't list the PDF option `{key}`");
|
||||
}
|
||||
let mut every = settings;
|
||||
every["flattener"] = serde_json::to_value(crate::cmd::flatten::FlattenOptions::default()).unwrap();
|
||||
every["security"]["openPassword"] = json!("a");
|
||||
every["security"]["permissionsPassword"] = json!("b");
|
||||
every["preset"] = json!("High Quality Print");
|
||||
for id in ["document.export", "document.exportPdf", "document.pdfSettings", "pdf.preset.save"] {
|
||||
check_params(id, &every).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// `stroke.set` names every key it reads (its own, `item`, and `ids`/`id`/`target`), so a
|
||||
/// misnamed one is refused instead of answering `objects: 1` with nothing changed.
|
||||
#[test]
|
||||
|
||||
@@ -1055,6 +1055,225 @@ fn a_cancelled_filter_run_changes_nothing() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list).
|
||||
fn with_commands(id: &str, kind: &str, commands: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#)
|
||||
}
|
||||
|
||||
/// Two commands: Grow, with a parameter, and Tidy, whose `menu` names another menu.
|
||||
const GROW_AND_TIDY: &str = r#"[{"id":"grow","label":"Grow","params":{"by":{"type":"number","min":0,"max":10,"default":2}}},
|
||||
{"id":"tidy","label":"Tidy","menu":"File"}]"#;
|
||||
|
||||
/// A plug-in that adds a triangle when it runs as its command `grow` (`_context.command`) and
|
||||
/// returns its input unchanged otherwise.
|
||||
fn grower(id: &str) -> String {
|
||||
let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#;
|
||||
tpl::when_given(&with_commands(id, "filter", GROW_AND_TIDY), tpl::Given::Params, r#""command":"grow""#, triangle)
|
||||
}
|
||||
|
||||
/// The command listing's entry for `id`.
|
||||
fn listed(s: &Session, id: &str) -> Option<crate::cmd::CommandInfo> {
|
||||
s.commands().into_iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum()
|
||||
}
|
||||
|
||||
/// A plug-in's commands are commands of their own while it is installed: listed under Object ›
|
||||
/// Plug-ins › its name whatever menu the manifest names, run with their checked parameters and
|
||||
/// `_context.command` as one undo step named after them, and gone once it is removed or replaced
|
||||
/// by a module without them.
|
||||
#[test]
|
||||
fn plugin_commands_are_registered_run_and_removed() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.cmds";
|
||||
let (grow, tidy) = ("plugin.test.engine.cmds.grow", "plugin.test.engine.cmds.tidy");
|
||||
let info = install_wat(&mut s, &grower(id));
|
||||
assert_eq!(info["commands"][0]["command"], grow);
|
||||
assert_eq!(info["commands"][1]["label"], "Tidy");
|
||||
for (cmd, label) in [(grow, "Grow"), (tidy, "Tidy")] {
|
||||
let c = listed(&s, cmd).unwrap_or_else(|| panic!("{cmd} is listed"));
|
||||
assert_eq!((c.label, c.menu.as_slice()), (label, &["Object", "Plug-ins", "Cmd Test"][..]), "{cmd}");
|
||||
assert!(c.enabled, "{cmd}");
|
||||
}
|
||||
assert!(crate::cmd::find_command(grow).is_some());
|
||||
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let (before, undo) = (objects(&s), s.doc().unwrap().history.undo.len());
|
||||
let r = run(&mut s, grow, json!({"by": 3}));
|
||||
assert_eq!((r["plugin"].as_str(), r["command"].as_str()), (Some(id), Some("grow")));
|
||||
assert_eq!(objects(&s), before + 1, "the command added its triangle");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Grow"));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(objects(&s), before);
|
||||
// Its parameters are checked before it runs.
|
||||
let e = s.execute(grow, &json!({"by": "lots"})).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::BadParams { cmd, .. } if cmd == grow), "{e}");
|
||||
assert_eq!(objects(&s), before);
|
||||
// Another command of the same plug-in is told apart by its id.
|
||||
run(&mut s, tidy, json!({}));
|
||||
assert_eq!(objects(&s), before, "tidy returns its input unchanged");
|
||||
|
||||
// Replaced by a module without commands, its commands are gone; installed again, back.
|
||||
install_wat(&mut s, &tpl::module(&tpl::manifest(id, "filter", "{}"), tpl::ECHO, "", 1));
|
||||
assert!(listed(&s, grow).is_none() && crate::cmd::find_command(grow).is_none());
|
||||
install_wat(&mut s, &grower(id));
|
||||
assert!(listed(&s, grow).is_some());
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(listed(&s, grow).is_none() && listed(&s, tidy).is_none());
|
||||
assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs");
|
||||
}
|
||||
|
||||
/// A command run is journaled like any other, so an action records it with its parameters and
|
||||
/// plays it back.
|
||||
#[test]
|
||||
fn actions_record_and_play_plugin_commands() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.cmds.actions";
|
||||
let grow = crate::cmd::plugin::command_id(id, "grow");
|
||||
install_wat(&mut s, &grower(id));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let before = objects(&s);
|
||||
let start = s.journal.len();
|
||||
run(&mut s, &grow, json!({"by": 4}));
|
||||
let steps = s.journal_for_action(start);
|
||||
assert_eq!(steps, [(grow.clone(), json!({"by": 4}))]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
let commands: Vec<Value> = steps.iter().map(|(c, p)| json!({"command": c, "params": p})).collect();
|
||||
// The triangle a run adds is selected, and the next run would be given it: deselect between.
|
||||
let none = json!({"command": "select.none", "params": {}});
|
||||
run(&mut s, "command.batch", json!({"label": "Grow Twice", "commands": [commands[0].clone(), none, commands[0].clone()]}));
|
||||
assert_eq!(objects(&s), before + 2, "both steps ran");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A command that traps leaves the document and its history as they were, and the error names
|
||||
/// the plug-in and the command.
|
||||
#[test]
|
||||
fn a_failing_plugin_command_changes_nothing_and_names_itself() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 10.0, "#ff0000");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let id = "test.engine.cmds.trap";
|
||||
install_wat(&mut s, &tpl::module(&with_commands(id, "filter", r#"[{"id":"boom","label":"Boom"}]"#), "unreachable", "", 1));
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute(&crate::cmd::plugin::command_id(id, "boom"), &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("“Cmd Test” › Boom: ") && e.contains("trapped"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A command that runs out of its instruction budget leaves the document and its history as they
|
||||
/// were, and the error names the plug-in and the command.
|
||||
#[test]
|
||||
fn a_plugin_command_out_of_budget_changes_nothing_and_names_itself() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 10.0, "#ff0000");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let id = "test.engine.cmds.spin";
|
||||
let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#;
|
||||
// More steps than a light budget pays for (as the plug-in crate's budget test counts them).
|
||||
install_wat(&mut s, &tpl::spinning(&with_commands(id, "filter", r#"[{"id":"spin","label":"Spin"}]"#), 100_000_000, triangle));
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute(&crate::cmd::plugin::command_id(id, "spin"), &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("“Cmd Test” › Spin: ") && e.contains("instruction budget"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// An `ids` that is not a list, or that holds an entry that is not an object id, is an error naming
|
||||
/// `ids` for a plug-in command and for `plugin.run`, and is never read as the selection; left out
|
||||
/// or null, `ids` is the selection.
|
||||
#[test]
|
||||
fn a_malformed_ids_is_refused_not_read_as_the_selection() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.cmds.ids";
|
||||
let grow = crate::cmd::plugin::command_id(id, "grow");
|
||||
install_wat(&mut s, &grower(id));
|
||||
rect(&mut s, 10.0, "#ff0000");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let cases = [
|
||||
(grow.as_str(), json!(5)),
|
||||
(grow.as_str(), json!([1, "x"])),
|
||||
(grow.as_str(), json!([-1])),
|
||||
("plugin.run", json!("all")),
|
||||
("plugin.run", json!([1.5])),
|
||||
];
|
||||
for (cmd, ids) in cases {
|
||||
let mut p = json!({"ids": ids});
|
||||
if cmd == "plugin.run" {
|
||||
p["id"] = json!(id);
|
||||
}
|
||||
let e = s.execute(cmd, &p).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::BadParams { cmd: c, .. } if c == cmd), "{cmd} {ids}: {e}");
|
||||
let said = e.to_string();
|
||||
assert!(
|
||||
said.contains("ids must be an array of non-negative integer object ids") || said.contains("not a non-negative integer object id"),
|
||||
"{cmd} {ids}: {e}"
|
||||
);
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{cmd} {ids}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {ids}");
|
||||
}
|
||||
// Left out or null, the command runs on the selection.
|
||||
for p in [json!({}), json!({"ids": null})] {
|
||||
let r = run(&mut s, &grow, p.clone());
|
||||
assert_eq!(r["command"], "grow", "{p}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{p}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{p}");
|
||||
}
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A live effect's commands are listed under Effect › Plug-ins and run under its permissions (with
|
||||
/// commands it gets `doc.write` unless its list leaves it out), and labels show bidirectional
|
||||
/// characters escaped. A malformed
|
||||
/// `commands` entry is refused at install, and the error names it.
|
||||
#[test]
|
||||
fn effect_commands_labels_and_malformed_entries() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.cmds.effect";
|
||||
let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#;
|
||||
install_wat(&mut s, &tpl::returning(&with_commands(id, "effect", "[{\"id\":\"flip\",\"label\":\"Flip\u{202E}txt\"}]"), triangle));
|
||||
let c = listed(&s, &crate::cmd::plugin::command_id(id, "flip")).expect("listed");
|
||||
assert_eq!((c.label, c.menu.as_slice()), ("Flip\\u{202E}txt", &["Effect", "Plug-ins", "Cmd Test"][..]));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
// Without `permissions`, a live effect with commands may change the document: its command adds
|
||||
// the triangle, as one undo step.
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let out = run(&mut s, &crate::cmd::plugin::command_id(id, "flip"), json!({}));
|
||||
assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}");
|
||||
assert_ne!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
// One that lists its permissions without `doc.write` is refused the change, and the document
|
||||
// stays as it was.
|
||||
let listed = format!(
|
||||
r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"effect","permissions":["doc.read","effect.render"],"commands":[{{"id":"flip","label":"Flip"}}]}}"#
|
||||
);
|
||||
let wasm = wat::parse_str(tpl::returning(&listed, triangle)).unwrap();
|
||||
let hash = vectorcraft_plugins::permissions::sha256_hex(&wasm);
|
||||
let grant = json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read", "effect.render"], "hash": hash});
|
||||
run(&mut s, "plugin.install", grant);
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute(&crate::cmd::plugin::command_id(id, "flip"), &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("wasn't granted `doc.write`"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
|
||||
let bad = id.replace("effect", "bad");
|
||||
let wasm = wat::parse_str(tpl::module(&with_commands(&bad, "filter", r#"[{"id":"ok","label":"A"},{"id":"Bad","label":"B"}]"#), tpl::ECHO, "", 1));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm.unwrap())})).unwrap_err().to_string();
|
||||
assert!(e.contains("command `Bad`"), "{e}");
|
||||
assert!(vectorcraft_plugins::registry::get(&bad).is_none());
|
||||
}
|
||||
|
||||
/// A filter `id` of API level 2 that lists `settings` and `cache`, whose `vc_run` runs `first`
|
||||
/// (instructions that trap unless each storage call returns what it should), with the keys "zoom"
|
||||
/// at 0x2000 and "tile" at 0x2004 and the value "hello" at 0x2100.
|
||||
@@ -1086,10 +1305,11 @@ fn replace_storing(s: &mut Session, id: &str, first: &str) -> Value {
|
||||
|
||||
/// A plug-in's settings and cache are kept in the plug-in store under its id: the next session
|
||||
/// has them, replacing the plug-in keeps them, another plug-in can't read them, `plugin.clearCache`
|
||||
/// empties the cache alone and `plugin.remove` deletes both. The caps and the bytes each call is
|
||||
/// charged follow ([`plugin_storage_is_capped_and_survives_a_damaged_settings_file`],
|
||||
/// [`plugin_storage_calls_are_charged_the_files_they_read_and_write`]) in the same test, since
|
||||
/// clearing every plug-in's cache would empty theirs.
|
||||
/// with its id empties its cache alone and `plugin.remove` deletes both. The caps and the bytes
|
||||
/// each call is charged follow ([`plugin_storage_is_capped_and_survives_a_damaged_settings_file`],
|
||||
/// [`plugin_storage_calls_are_charged_the_files_they_read_and_write`]) in the same test.
|
||||
/// `plugin.clearCache` without an id empties the cache of every plug-in installed in the process,
|
||||
/// so it is tested in a binary of its own (`tests/plugin_clear_cache.rs`).
|
||||
#[test]
|
||||
fn plugins_keep_settings_and_a_cache_of_their_own_in_the_store() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-storage");
|
||||
@@ -1116,16 +1336,13 @@ fn plugins_keep_settings_and_a_cache_of_their_own_in_the_store() {
|
||||
install_storing(&mut next, other, READS);
|
||||
assert!(next.execute("plugin.run", &json!({"id": other, "ids": []})).is_err());
|
||||
|
||||
// Clearing the cache leaves the settings.
|
||||
assert_eq!(run(&mut next, "plugin.clearCache", json!({"id": id})), json!({"cleared": [id], "bytesFreed": 3}));
|
||||
assert_eq!(run(&mut next, "plugin.info", json!({"id": id}))["cacheBytes"], json!(0));
|
||||
run(&mut next, "plugin.run", json!({"id": id, "ids": []}));
|
||||
// Clearing the cache leaves the settings, and the other plug-in's cache.
|
||||
replace_storing(&mut next, other, WRITES);
|
||||
run(&mut next, "plugin.run", json!({"id": other, "ids": []}));
|
||||
let all = run(&mut next, "plugin.clearCache", json!({}));
|
||||
let cleared = all["cleared"].as_array().unwrap();
|
||||
assert!(cleared.contains(&json!(id)) && cleared.contains(&json!(other)) && all["bytesFreed"] == json!(3), "{all}");
|
||||
assert_eq!(run(&mut next, "plugin.info", json!({"id": other}))["cacheBytes"], json!(0));
|
||||
assert_eq!(run(&mut next, "plugin.clearCache", json!({"id": id})), json!({"cleared": [id], "bytesFreed": 3}));
|
||||
assert_eq!(run(&mut next, "plugin.info", json!({"id": id}))["cacheBytes"], json!(0));
|
||||
assert_eq!(run(&mut next, "plugin.info", json!({"id": other}))["cacheBytes"], json!(3));
|
||||
run(&mut next, "plugin.run", json!({"id": id, "ids": []}));
|
||||
assert!(next.execute("plugin.clearCache", &json!({"id": "test.engine.storing.missing"})).is_err());
|
||||
|
||||
run(&mut next, "plugin.remove", json!({"id": id}));
|
||||
|
||||
Reference in New Issue
Block a user