Merge main into #8458

# Conflicts:
#	crates/engine/src/cmd/brushlib.rs
#	crates/engine/src/tests/brushlib.rs
#	crates/ui-egui/src/i18n/bg.tsv
#	crates/ui-egui/src/i18n/bs.tsv
#	crates/ui-egui/src/i18n/ca.tsv
#	crates/ui-egui/src/i18n/cs.tsv
#	crates/ui-egui/src/i18n/da.tsv
#	crates/ui-egui/src/i18n/de.tsv
#	crates/ui-egui/src/i18n/el.tsv
#	crates/ui-egui/src/i18n/es.tsv
#	crates/ui-egui/src/i18n/fi.tsv
#	crates/ui-egui/src/i18n/fr.tsv
#	crates/ui-egui/src/i18n/gu.tsv
#	crates/ui-egui/src/i18n/hi.tsv
#	crates/ui-egui/src/i18n/hu.tsv
#	crates/ui-egui/src/i18n/id.tsv
#	crates/ui-egui/src/i18n/it.tsv
#	crates/ui-egui/src/i18n/ja.tsv
#	crates/ui-egui/src/i18n/ka.tsv
#	crates/ui-egui/src/i18n/ko.tsv
#	crates/ui-egui/src/i18n/nl.tsv
#	crates/ui-egui/src/i18n/pl.tsv
#	crates/ui-egui/src/i18n/pt-br.tsv
#	crates/ui-egui/src/i18n/ru.tsv
#	crates/ui-egui/src/i18n/sv.tsv
#	crates/ui-egui/src/i18n/tr.tsv
#	crates/ui-egui/src/i18n/uk.tsv
#	crates/ui-egui/src/i18n/vi.tsv
#	crates/ui-egui/src/i18n/zh-hans.tsv
#	crates/ui-egui/src/i18n/zh-hant.tsv
#	crates/ui-egui/src/panels/tests_brush_libraries.rs
This commit is contained in:
bflatastic
2026-11-20 02:07:18 +07:00
175 changed files with 9494 additions and 444 deletions
+62
View File
@@ -123,6 +123,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"engraving",
"arrows",
"image-brush",
"artistic",
"vector-packs"
]
);
@@ -181,6 +182,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("dry-media", "art"),
("arrows", "art"),
("image-brush", "scatter"),
("artistic", "art"),
("vector-packs", "scatter"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
@@ -212,6 +214,46 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap();
let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap();
assert_eq!(alias.brushes, lib.brushes);
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic");
let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap();
let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0);
for b in &lib.brushes {
let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name);
for path in [line_to(180.0), line_to(1.0)] {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name);
}
// The art is black, so with Tints every path takes the stroke color itself.
let mut fills = vec![];
for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) {
piece.walk(&mut |n| {
if n.path_data().is_some() {
fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb()));
}
});
}
let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5);
assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name);
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([line]));
assert_eq!(undo_len(&s), before + 1);
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn vector_packs_marks_are_editable_and_survive_a_saved_library() {
let mut s = session();
@@ -291,6 +333,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
assert_eq!(reopened.images, lib.doc.images);
}
#[test]
fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() {
let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]);
let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
let mut s = session();
let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"}));
assert_eq!(loaded["name"], "Artistic");
let id = loaded["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works");
// A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id.
let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"}));
assert_eq!(full["name"], "Artistic Brushes");
let full_id = full["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic");
assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id);
}
/// Every path of brush art `n`: (anchors, opacity).
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
let mut out = vec![];
+4 -1
View File
@@ -9491,9 +9491,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() {
assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25));
// Bad dividers are refused and change nothing.
let steps = s.doc().unwrap().history.undo.len();
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] {
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] {
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
}
// A null divider with another view is refused too, and the view stays.
assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err());
assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split);
assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25));
for edge in [0.0, 1.0] {
s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap();
+39
View File
@@ -318,6 +318,45 @@ fn convert_query_and_intents() {
assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err());
}
/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color;
/// a CMYK color's display color, not its naive separation, sets them.
#[test]
fn convert_to_oklch_answers_lightness_chroma_and_hue() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap();
assert_eq!(r["model"], "oklch");
let v: Vec<f64> = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}");
let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]);
assert!(!lowered);
assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000");
assert_eq!(r["hex"], "#ff0000");
let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap();
assert_eq!(gray["values"][2], 0.0, "{gray}");
let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0});
let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap();
let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
let c: Vec<f64> = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let got = [c[0] / 100.0, c[1], c[2]];
assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}");
assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}");
// A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB.
let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap();
let w: Vec<f64> = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0));
let clipped = vectorcraft_color::oklab::to_oklch(shown);
assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}");
assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}");
assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}");
// RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white.
let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap();
assert_eq!(past["hex"], "#ffffff");
let l = past["values"][0].as_f64().unwrap();
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+21
View File
@@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() {
assert!(marked(b), "the opaque image it overlaps");
}
/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a
/// distorted plate image does not stop an image replacing the group.
#[test]
fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() {
let dir = temp_dir("replace-distorted");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
let group = r["ids"][0].clone();
let image = image_of(&s, &group).id;
let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap();
let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1);
let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]);
s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap();
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
let png = crate::tests_links::png(2, 2, [0, 0, 255]);
let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
assert!(out.is_ok(), "{out:?}");
}
#[test]
fn dcs_transparency_counts_characters_with_a_transparent_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
+75
View File
@@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
}
/// Update Links gives a distorted image its file's new pixels between the same corners: its
/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size,
/// and Link Info measures its scale at its middle.
#[test]
fn update_links_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-update");
let photo = dir.file("photo.png");
write(&photo, &png(20, 10, RED));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
let before = corners(&s);
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
// The far corner of the pixels as the transform alone places them.
let far = |s: &Session| {
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
};
let far_before = far(&s);
// Link Info measures the scale where the effective resolution is measured: at the middle.
let scale_matches_ppi = |s: &mut Session| {
let info = s.execute("links.info", &json!({"id": id.0})).unwrap();
for i in 0..2 {
let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap());
assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}");
}
};
scale_matches_ppi(&mut s);
// A copy in a symbol, distorted the same way, shows the same file.
let copy = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
let in_symbol = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
if let NodeKind::Image(im) = &n.kind {
out.push((n.is_distorted_image(), (im.width, im.height)));
}
});
out
};
let symbol_corners = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners()));
out
};
assert_eq!(in_symbol(&s), [(true, (20, 10))]);
let symbol_before = symbol_corners(&s);
assert_eq!(symbol_before.len(), 1);
write(&photo, &png(60, 20, BLUE));
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}");
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(n.is_distorted_image());
assert_eq!(corners(&s), before);
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
assert_eq!((im.width, im.height), (60, 20));
// The transform takes the new pixel size, so a placement by the transform keeps the old size.
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
let d = &s.doc().unwrap().doc;
assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped");
let mut clipped = false;
d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. }));
assert!(!clipped, "the symbol's image is not clipped");
assert_eq!(in_symbol(&s), [(true, (60, 20))]);
assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners");
scale_matches_ppi(&mut s);
}
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
+160
View File
@@ -1907,6 +1907,166 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() {
assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err());
}
/// The leaf objects of `n`, in paint order.
fn leaves_of(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::Node>) {
match n.children() {
Some(children) => children.iter().for_each(|c| leaves_of(c, out)),
None => out.push(n.clone()),
}
}
/// Apply the live Pathfinder effect `effect` with `params` to the selection, then expand its
/// appearance: the objects it draws.
fn live_pieces(s: &mut Session, effect: &str, params: Value) -> Vec<vectorcraft_doc::Node> {
let g = ids(&s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap())[0];
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
let mut out = vec![];
leaves_of(&node(s, g), &mut out);
out
}
/// The parameters of the first effect of the selected object.
fn first_effect_params(s: &Session) -> Value {
let st = s.doc().unwrap();
st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[0].params.clone()
}
/// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those its params
/// give aside, and its journal entry carries them.
#[test]
fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("object.pathfinder.options", &json!({"precision": 1, "removeRedundantPoints": true, "removeUnpainted": true})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap();
let all = json!({"precision": 1.0, "removeRedundantPoints": true, "removeUnpainted": true});
assert_eq!(first_effect_params(&s), all);
assert_eq!(s.journal.last().unwrap().1["params"], all, "the journal entry gives the options it used");
s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"precision": 0.5}})).unwrap();
let st = s.doc().unwrap();
let mix = &st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[1].params;
assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true}));
}
/// A live Pathfinder effect evaluates with its own options as the panel's operations do with
/// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled
/// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing.
#[test]
fn a_pathfinder_effect_evaluates_with_its_own_options() {
for (precision, faces) in [(0.01, 3), (1.0, 2)] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(live_pieces(&mut s, "pathfinder.divide", json!({"precision": precision})).len(), faces, "precision {precision}");
}
for on in [false, true] {
let mut s = session();
filled_and_unfilled(&mut s);
let divided = live_pieces(&mut s, "pathfinder.divide", json!({"removeUnpainted": on}));
let unfilled = divided.iter().filter(|n| n.appearance.fill_paint().is_none()).count();
assert_eq!((unfilled, divided.len() - unfilled), (if on { 0 } else { 2 }, 1), "removeUnpainted {on}");
}
for on in [false, true] {
let mut s = session();
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let united = live_pieces(&mut s, "pathfinder.add", json!({"removeRedundantPoints": on}));
let count = united[0].path_data().unwrap().anchor_count();
assert!(if on { count == 4 } else { count > 4 }, "removeRedundantPoints {on}: {count} anchors");
}
}
/// An effect saved before Pathfinder effects kept their own options draws as one given their
/// defaults, so older documents look as they did.
#[test]
fn a_pathfinder_effect_saved_without_options_draws_as_before() {
let draw = |params: Value| {
let mut s = session();
filled_and_unfilled(&mut s);
let g = ids(&s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap())[0];
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = params;
Ok(())
})
.unwrap();
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
serde_json::to_value(node(&s, g)).unwrap()
};
assert_eq!(draw(json!({})), draw(json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false})));
}
/// `effect.setParams` edits a Pathfinder effect's options as one undo step, records none for the
/// values it already evaluates with, and refuses values out of range or of the wrong type.
#[test]
fn pathfinder_effect_options_edit_as_one_step_and_refuse_bad_values() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
let before = steps(&s);
let same = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 0.01, "removeUnpainted": false}})).unwrap();
assert_eq!((same, steps(&s)), (json!({"ids": []}), before), "the values it has: no step");
// An effect saved without options evaluates with the defaults: given them, it is unchanged.
let g = s.doc().unwrap().selection.objects[0];
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = json!({});
Ok(())
})
.unwrap();
let before = steps(&s);
let defaults = json!({"index": 0, "params": {"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}});
assert_eq!(s.execute("effect.setParams", &defaults).unwrap(), json!({"ids": []}));
assert_eq!(steps(&s), before);
s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 2, "removeRedundantPoints": true}})).unwrap();
assert_eq!(steps(&s), before + 1, "one step");
assert_eq!(first_effect_params(&s), json!({"precision": 2, "removeRedundantPoints": true}));
let kept = doc(&s);
for bad in [
json!({"precision": 0}),
json!({"precision": 11}),
json!({"precision": "1 pt"}),
json!({"precision": null}),
json!({"removeRedundantPoints": "yes"}),
json!({"removeUnpainted": 1}),
] {
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": bad})).is_err(), "setParams {bad}");
assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.trim", "params": bad})).is_err(), "apply {bad}");
assert_eq!(doc(&s), kept, "{bad} changes nothing");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first_effect_params(&s), json!({}), "undo restores the options");
}
/// A precision that Scale Strokes & Effects took past the range evaluates at its bound, and setting
/// the bound is still an edit: a later scale then starts from the value set.
#[test]
fn a_precision_set_after_a_scale_past_its_range_is_kept() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.add", "params": {"precision": 8}})).unwrap();
let precision = |s: &Session| first_effect_params(s)["precision"].as_f64();
s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap();
assert_eq!(precision(&s), Some(16.0));
let steps = s.doc().unwrap().history.undo.len();
let out = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 10}})).unwrap();
assert_ne!(out, json!({"ids": []}), "an edit");
assert_eq!((precision(&s), s.doc().unwrap().history.undo.len()), (Some(10.0), steps + 1));
s.execute("object.scale", &json!({"sx": 50, "strokes": true})).unwrap();
assert_eq!(precision(&s), Some(5.0));
// The value it stores is still no edit.
let steps = s.doc().unwrap().history.undo.len();
assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 5}})).unwrap(), json!({"ids": []}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
}
/// A single group containing multiple overlapping paths is accepted by Crop.
#[test]
fn crop_operates_on_a_single_selected_group_of_paths() {
+20
View File
@@ -1422,6 +1422,26 @@ fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
}
/// A distorted image is read where its pixels are drawn, between its corners.
#[test]
fn theme_picker_reads_a_distorted_image_where_it_is_drawn() {
let mut s = session();
let (id, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
let (x, y0, y1) = (b.x1 + 20.0, b.y0, b.y1);
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "object.distort", json!({"corners": [[x + 40.0, y0], [x + 60.0, y0], [x + 100.0, y1], [x, y1]]}));
// The lower left of the trapezoid, outside the rectangle the image was placed in: red.
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [x + 2.0, y1 - 4.0, x + 20.0, y1 - 1.0]}]})), ["rgb 255 0 0"]);
// Where the image was: nothing.
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [b.x0 + 1.0, b.y0 + 1.0, b.x1 - 1.0, b.y1 - 1.0]}]})).is_empty());
// A marquee reaching past the horizon its sides meet at (a quarter of its height above its
// top) still reads every pixel it covers.
let h = y1 - y0;
let mut both = pick_theme(&mut s, json!({"picks": [{"rect": [x - 10.0, y0 - h, x + 110.0, y1 + 1.0]}]}));
both.sort();
assert_eq!(both, ["rgb 0 0 255", "rgb 255 0 0"]);
}
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
#[test]
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
@@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() {
assert!(state(&s) == before);
}
/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque
/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke
/// that changes no instance adds no undo step.
#[test]
fn an_instance_left_as_it_is_is_not_counted() {
let mut s = session();
let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap();
let before = state(&s);
let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true}));
assert_eq!(r["count"], 0, "Alt on an opaque instance");
let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10}));
assert_eq!(r["count"], 0, "an instance at 5%");
assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history");
// A stroke over both counts only the instance it changes.
let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10}));
assert_eq!(r["count"], 1);
assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05);
}
/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and
/// the Symbol Screener's instances take the mean of the instances under the brush.
#[test]
fn average_keeps_a_mean_opacity_below_five_percent() {
let mut s = session();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let first = members(&s, set)[0];
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap();
s.select(|_, sel| sel.set([set])).unwrap();
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap();
let sprayed = *members(&s, set).last().unwrap();
assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity);
// Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it.
let mut s = session();
let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0));
s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap();
s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap();
adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"}));
let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity);
assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}");
}
/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing.
#[test]
fn average_evens_out_the_stain_and_the_spacing() {
@@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() {
assert_eq!(center(&s, a), Point::new(200.0, 150.0));
}
/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the
/// tool's options stay as they were.
#[test]
fn tool_set_option_refuses_bad_symbolism_options() {
let mut s = session();
let before = s.tool_options_of("symbolSizer");
for (key, bad, want) in [
("method", json!("smooth"), "`method` must be one of userDefined, average, random"),
("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"),
("usePressure", json!("yes"), "`usePressure` must be true or false"),
("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"),
("style", json!(3), "`style` must be a string or null"),
("diameter", json!(1), "`diameter` must be a number from 2 to 2000"),
] {
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}}));
assert_eq!(r, Err(want.to_string()), "{key}");
assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}");
}
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap();
assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined")));
// Every option the options dialog sends is taken, together.
let all = json!({
"diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false,
"sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined",
"sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true,
});
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap();
for (key, v) in all.as_object().unwrap() {
assert_eq!(&r[key], v, "{key}");
}
}
/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is
/// not used. A pressure that isn't a number is an error.
#[test]
@@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() {
json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}),
"a point's pressure must be a number, not \"hard\"",
);
// Also on a point without coordinates, beside one that has them.
refused(
&mut s,
"symbol.adjust",
json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}),
"a point's pressure must be a number, not \"bad\"",
);
}
for key in ["usePressure", "proportional", "affectsDensity"] {
let mut p = json!({"tool": "size", "points": [[200, 150]]});
@@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() {
assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a));
}
/// A set duplicated packs from the density recorded for its source, and a pasted set from the
/// density its source had at Copy: after Cut, after the source is given another density, and in
/// another document.
#[test]
fn a_copied_set_packs_from_the_density_of_its_source() {
for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] {
let mut s = session();
let row: Vec<Value> = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect();
let set =
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.set([set])).unwrap();
let first = match copy {
"duplicate" => "edit.duplicate",
"cut" => "edit.cut",
_ => "edit.copy",
};
s.execute(first, &json!({})).unwrap();
if copy == "changed after copy" {
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap();
}
if copy == "other document" {
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
}
if copy != "duplicate" {
s.execute("edit.paste", &json!({})).unwrap();
}
let copied = s.doc().unwrap().selection.objects.clone();
assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}");
let ids = members(&s, copied[0]);
let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::<Vec<_>>();
let was = xs(&s);
let middle = was.iter().sum::<f64>() / 4.0;
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap();
for (before, after) in was.iter().zip(xs(&s)) {
assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}");
}
}
}
/// A set of one instance takes the new density without moving, as one undo step, so a later change
/// packs it from that density; setting the density it already has adds no undo step.
#[test]
@@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() {
assert!(state(&s) == before);
}
/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen
/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives
/// each instance a share of that amount.
#[test]
fn the_styler_applies_the_style_by_the_brushs_strength() {
let styled = |extra: Value, x: f64| {
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
adjust(&mut s, p);
node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity)
};
let near = |a: f32, b: f32| (a - b).abs() < 1e-6;
assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center");
assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5));
assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge");
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25));
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0));
assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style");
// Random: instances the same distance from the point take different amounts, each from none to
// the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge).
let mut s = session();
let ring: Vec<NodeId> = (0..6)
.map(|i| {
let a = f64::from(i) * std::f64::consts::TAU / 6.0;
dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin())
})
.collect();
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"}));
let amounts: Vec<f32> = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect();
assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}");
assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}");
assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}");
}
/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one
/// at no opacity is passed over and counts as no stain in the mean amount.
#[test]
fn average_spray_passes_over_a_stain_at_no_opacity() {
use vectorcraft_color::{Color, Paint};
let mut s = session();
let set =
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let ids = members(&s, set);
assert_eq!(ids.len(), 2);
s.edit("Stains", |d, _| {
for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] {
let n = d.node_mut(id).unwrap();
n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_)));
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
f.opacity = amount;
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
}
Ok(())
})
.unwrap();
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap();
let new: Vec<NodeId> = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect();
assert_eq!(new.len(), 1);
let f = node(&s, new[0]).appearance.fill().cloned().unwrap();
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity);
}
/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves
/// any other, and counts it.
#[test]
fn the_shifter_moves_an_instance_without_a_size() {
let mut s = session();
let a = dot(&mut s, 200.0, 150.0);
s.edit("Flatten", |d, _| {
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
*xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]);
}
Ok(())
})
.unwrap();
let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10}));
assert_eq!(r["count"], 1);
assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a));
// Average has no mean of such instances to move toward: it leaves them as they are.
let (before, x) = (state(&s), center(&s, a).x);
let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10}));
assert_eq!(r["count"], 0);
assert!(state(&s) == before);
}
/// An instance with no size is shifted and screened as before; only Average, which needs its size,
/// leaves it as it is.
#[test]
@@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() {
assert!(state(&s) == before);
}
/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes
/// the stain the mean picks, not its hidden paint.
#[test]
fn average_stain_replaces_a_stain_at_no_opacity() {
use vectorcraft_color::{Color, Paint};
let mut s = session();
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0));
s.edit("Stains", |d, _| {
for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] {
let n = d.node_mut(id).unwrap();
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
f.opacity = amount;
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
}
Ok(())
})
.unwrap();
adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10}));
let f = node(&s, a).appearance.fill().cloned().unwrap();
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
assert!(f.opacity > 0.0, "{}", f.opacity);
}
/// A stroke that leaves every instance under the brush as it is (each already at full stain, or
/// at the least opacity) counts none and adds no undo step.
#[test]
+272
View File
@@ -0,0 +1,272 @@
//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking
//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler
//! keeping their amount while the color or style changes.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_geom::Point;
use crate::*;
/// A document with the 20 pt square symbol "Dot" and nothing selected.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
s
}
/// An instance of Dot centered on (`x`, `y`), not selected.
fn dot(s: &mut Session, x: f64, y: f64) -> NodeId {
let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.clear()).unwrap();
id
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn center(s: &Session, id: NodeId) -> Point {
match node(s, id).kind {
NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO,
other => panic!("not an instance: {other:?}"),
}
}
fn width(s: &Session, id: NodeId) -> f64 {
node(s, id).geometric_bounds().unwrap().width()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn state(s: &Session) -> (Document, usize) {
((*s.doc().unwrap().doc).clone(), undo_len(s))
}
fn adjust(s: &mut Session, p: Value) -> Value {
s.execute("symbol.adjust", &p).unwrap()
}
/// The children of symbol set `set`, in stacking order (the first is at the back).
fn members(s: &Session, set: NodeId) -> Vec<NodeId> {
node(s, set).children().unwrap().iter().map(|c| c.id).collect()
}
/// The instance's fill: its color as RGB and its amount.
fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> {
node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity))
}
/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected.
fn row(s: &mut Session) -> (NodeId, Vec<NodeId>) {
let pts: Vec<Value> = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap());
let ids = members(s, set);
assert_eq!(ids.len(), 4);
(set, ids)
}
/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in
/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas.
#[test]
fn shift_click_with_the_shifter_changes_the_stacking_order() {
let mut s = session();
let (set, ids) = row(&mut s);
let centers: Vec<Point> = ids.iter().map(|id| center(&s, *id)).collect();
let click = |s: &mut Session, x: f64, alt: bool| {
adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone()
};
let steps = undo_len(&s);
assert_eq!(click(&mut s, 120.0, false), 1);
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
assert_eq!(undo_len(&s), steps + 1, "one undo step");
assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::<Vec<_>>(), centers, "nothing moves on the canvas");
assert_eq!(click(&mut s, 120.0, false), 1);
assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]);
// Already in front of the others: nothing changes and no undo step is added.
let before = state(&s);
assert_eq!(click(&mut s, 120.0, false), 0);
assert!(state(&s) == before);
// Alt sends it back one place at a time; at the back it stays.
assert_eq!(click(&mut s, 120.0, true), 1);
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
click(&mut s, 120.0, true);
click(&mut s, 120.0, true);
assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]);
assert_eq!(click(&mut s, 120.0, true), 0);
// Two instances under the brush move together past the next one.
s.execute("edit.undo", &json!({})).unwrap();
let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true}));
assert_eq!(both["count"], 2);
assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]);
// Without Shift a drag moves the instances, as before.
adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10}));
assert!(center(&s, ids[3]).x > centers[3].x);
}
/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even
/// with Resizing Affects Density.
#[test]
fn shift_with_the_sizer_keeps_the_density() {
let at = |affects: bool, shift: bool| {
let mut s = session();
let a = dot(&mut s, 220.0, 150.0);
adjust(
&mut s,
json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}),
);
(center(&s, a), width(&s, a))
};
let (moved, _) = at(true, false);
assert!(moved.x > 220.5, "{moved:?}");
let (kept, grown) = at(true, true);
assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}");
// It resizes as the Sizer does with Resizing Affects Density off.
assert_eq!(at(false, false), (kept, grown));
assert_eq!(at(false, true), (kept, grown));
}
/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill
/// color; an instance without a stain is left as it is.
#[test]
fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() {
let mut s = session();
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
let (red, amount) = fill(&s, a).unwrap();
assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}");
// A second fill below the stain, which Shift leaves as it is.
s.edit("Add fill", |d, _| {
let n = d.node_mut(a).unwrap();
let lower = n.appearance.fill().unwrap().clone();
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower }));
Ok(())
})
.unwrap();
let lower = node(&s, a).appearance.items[0].clone();
let stain = |s: &mut Session, x: f64| {
adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true}))
};
assert_eq!(stain(&mut s, 100.0)["count"], 1);
let (color, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount, "the amount stays");
assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}");
assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays");
// More strokes go on toward blue, with the amount still the same.
for _ in 0..30 {
stain(&mut s, 100.0);
}
let (bluer, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount);
assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}");
// Alt has no effect with Shift.
let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true});
adjust(&mut s, green.clone());
let plain = fill(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
let mut with_alt = green;
with_alt["alt"] = json!(true);
adjust(&mut s, with_alt);
assert_eq!(fill(&s, a), plain);
// No stain on b: nothing changes and no undo step is added.
let before = state(&s);
assert_eq!(stain(&mut s, 300.0)["count"], 0);
assert!(state(&s) == before && fill(&s, b).is_none());
}
/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its
/// fill toward the selected style's fill.
#[test]
fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() {
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
// A red stain at part strength.
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
let (red, amount) = fill(&s, a).unwrap();
assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}");
// Half the brush's strength at a point 2.5 pt from the instance: half way to blue.
adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
let (mixed, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount);
assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}");
// At the brush's center with full intensity it takes the style's fill.
adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
let (blue, kept) = fill(&s, a).unwrap();
assert_eq!(kept, amount);
assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}");
}
/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes
/// the new paint at once, at any strength, and keeps its amount.
#[test]
fn shift_changes_a_paint_that_has_no_form_in_between() {
use vectorcraft_color::Paint;
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
s.edit("Pattern fill", |d, _| {
let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() });
f.opacity = 0.4;
d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
Ok(())
})
.unwrap();
// Low intensity, near the brush's edge: far below half strength.
let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true}));
assert_eq!(r["count"], 1);
let f = node(&s, a).appearance.fill().cloned().unwrap();
assert_eq!(f.opacity, 0.4, "the amount stays");
assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint);
}
/// A style name the document has no style for (the Styler's style from another document, or one
/// since renamed or deleted) moves the fill toward the document's first style after the default
/// one, as no name does, and the stain's amount stays.
#[test]
fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() {
use vectorcraft_color::{Color, Paint};
let styled = |style: Option<&str>| {
let mut s = session();
let a = dot(&mut s, 100.0, 150.0);
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true});
if let Some(n) = style {
p["style"] = json!(n);
}
let stained = node(&s, a).appearance.fill().map(|f| f.opacity);
adjust(&mut s, p);
let f = node(&s, a).appearance.fill().cloned().unwrap();
assert_eq!(Some(f.opacity), stained, "the amount stays");
let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint();
(f.paint, first)
};
let (missing, first) = styled(Some("No Such Style"));
let (none, _) = styled(None);
assert_eq!(missing, none);
// The paint is the first style's, not the active fill color.
assert_eq!(none, first);
assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
}
/// A `shift` that is not true, false or null is refused and changes nothing.
#[test]
fn a_bad_shift_is_refused() {
let mut s = session();
dot(&mut s, 100.0, 150.0);
for tool in ["shift", "size", "stain", "style"] {
let before = state(&s);
let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}");
assert!(state(&s) == before);
}
}
+80
View File
@@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() {
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides");
}
/// An option set with `tool.setOption` while a press is held survives the dropped press, in the
/// tool and in the stored options, while what the drag itself changed is put back in both.
#[test]
fn an_option_set_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "rectangularGrid");
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6)));
s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap();
s.drop_tool_press(v).unwrap();
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay");
let saved = &s.prefs.tool_settings["rectangularGrid"];
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are");
select(&mut s, "selection");
select(&mut s, "rectangularGrid");
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns");
// The same through the desktop app's setter.
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
s.set_tool_option("columns", &json!(3));
s.drop_tool_press(v).unwrap();
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3)));
let saved = &s.prefs.tool_settings["rectangularGrid"];
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3)));
}
/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped
/// press, in the tool and in the preference.
#[test]
fn a_corner_radius_set_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "roundedRectangle");
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
let mut p = s.prefs.clone();
p.corner_radius = 30.0;
s.apply_prefs(p);
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
}
/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag
/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius
/// preference set while the Rounded Rectangle lends one.
#[test]
fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "rectangularGrid");
let v = ViewInfo { smart_guides: false, ..Default::default() };
let cmd = Mods { cmd: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool");
s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back");
assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns");
assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them");
select(&mut s, "roundedRectangle");
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool");
let mut p = s.prefs.clone();
p.corner_radius = 30.0;
s.apply_prefs(p);
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
}
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
/// the next click.
#[test]
+400
View File
@@ -754,6 +754,406 @@ fn distort_perspective_midpoint_is_projective() {
assert!((c.y - 100.0 / 6.0).abs() < 1e-3, "{c:?}");
}
/// A 2 × 2 px image placed at (0, 0)–(100, 100), selected.
fn placed_image(s: &mut Session) -> NodeId {
s.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![]));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 2,
height: 2,
xf: vectorcraft_geom::Affine::scale(50.0),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap()
}
fn corners(s: &Session, id: NodeId) -> [Point; 4] {
s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap()
}
fn assert_corners(got: [Point; 4], want: [(f64, f64); 4]) {
for (g, (x, y)) in got.iter().zip(want) {
assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?} against {want:?}");
}
}
/// Perspective Distort and Free Distort put an image's corners exactly on the handles, in one
/// undo step; the image is bounded and clicked by its corners, and a move takes them along.
#[test]
fn distort_puts_an_images_corners_on_the_handles() {
for want in [[(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)], [(10.0, 5.0), (90.0, 0.0), (120.0, 110.0), (0.0, 100.0)]] {
let mut s = session();
let img = placed_image(&mut s);
let undo = undo_len(&s);
let corners_json: Vec<[f64; 2]> = want.iter().map(|(x, y)| [*x, *y]).collect();
s.execute("object.distort", &json!({ "corners": corners_json })).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert_corners(corners(&s, img), want);
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
let b = bounds(&s, img);
let xs = want.map(|c| c.0);
let ys = want.map(|c| c.1);
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
assert!(near(b.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(b.x1, xs.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
assert!(near(b.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(b.y1, ys.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
assert_corners(corners(&s, img), want.map(|(x, y)| (x + 10.0, y + 20.0)));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
}
// Clicks: inside the trapezoid hits the image; inside its old square but outside the
// trapezoid does not.
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let doc = &s.doc().unwrap().doc;
let opt = vectorcraft_doc::hit::HitOptions::default();
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(50.0, 50.0), opt).map(|h| h.leaf), Some(img));
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(5.0, 10.0), opt).map(|h| h.leaf), None);
}
/// Distorted together with a path, the image's corners and the path's anchors follow one warp.
#[test]
fn distort_moves_an_image_and_a_path_as_one() {
let mut s = session();
let img = placed_image(&mut s);
let path = rect(&mut s, 100.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [200, 100], [50, 100]]})).unwrap();
let d = &s.doc().unwrap().doc;
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
let q = corners(&s, img);
// The image's right edge and the path's left edge were one line, and stay one where the warp
// moves it.
assert!(q[2].distance(Point::new(100.0, 100.0)) > 1.0, "{q:?}");
for p in [q[1], q[2]] {
assert!(anchors.iter().any(|a| a.distance(p) < 1e-9), "{p:?} not in {anchors:?}");
}
}
/// Corners that would fold an image over are refused: nothing changes and no undo step is kept.
/// A distorted image keeps its distortion where commands that cannot keep it are asked to work.
#[test]
fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
let mut s = session();
let img = placed_image(&mut s);
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [0, 100], [100, 100]]})).unwrap_err().to_string();
assert!(e.contains("convex"), "{e}");
assert_eq!(undo_len(&s), undo);
assert_eq!(s.doc().unwrap().doc, before);
// Three corners on one line give no perspective map at all.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [100, 50], [0, 100]]})).unwrap_err().to_string();
assert!(e.contains("convex"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
// A convex shape too small for a perspective map: the corners could not reach the handles.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1e-7, 0], [8e-8, 1e-7], [0, 1e-7]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
// The same shape far from the origin: its distance from it does not hide the missed corner.
let x = 1_000_000.0;
let e = s.execute("object.distort", &json!({"corners": [[x, 0], [x + 1e-7, 0], [x + 8e-8, 1e-7], [x, 1e-7]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
// A long, thin shape with one side all but gone.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1_000_000, 0], [1_000_000, 1e-19], [0, 1]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
// A small shape near the edge of the canvas is still distorted.
let o = vectorcraft_doc::MAX_COORD - 2.0;
let far = [[o, o], [o + 1.0, o], [o + 0.2130712, o + 1.0], [o, o + 1.0]];
s.execute("object.distort", &json!({ "from": [0, 0, 100, 100], "corners": far })).unwrap();
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(undo_len(&s), undo);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
for (cmd, params) in [
("object.cropImage", json!({})),
("imageTrace.make", json!({})),
("links.relink", json!({"path": "/nowhere/pic.png"})),
// Refused before the folder is searched, so a file missing there does not hide it.
("links.relink", json!({"folder": "/nowhere"})),
("links.embed", json!({"ids": [img.0]})),
("links.unembed", json!({})),
// Refused before any file is written.
("links.unembed", json!({"folder": "/nowhere"})),
("object.createObjectMosaic", json!({})),
("object.mesh.create", json!({})),
(
"file.place",
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
// Every command gives the one shared refusal, which the complete-message catalogs translate.
assert!(e.contains("is an image changed by Perspective Distort or Free Distort, which this command does not work on"), "{cmd}: {e}");
}
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
assert_eq!(undo_len(&s), undo + 1);
// Type replaces a distorted image by its bounds, which the corners give: not refused.
let text = json!({"replace": true, "name": "note.txt", "dataBase64": vectorcraft_format::base64_encode(b"Hello")});
let out = s.execute("file.place", &text).unwrap();
let id = NodeId(out["ids"][0].as_u64().unwrap());
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Text(_)));
}
/// Create Gradient Mesh on a path and a distorted image converts the path and names the image it
/// left as it is, with the shared refusal.
#[test]
fn mesh_create_reports_the_distorted_image_it_skips() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let path = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
let out = s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}");
let skipped = out["skipped"].as_array().expect("the skipped image");
assert_eq!(skipped.len(), 1, "{out}");
assert_eq!(skipped[0]["id"], json!(img.0));
assert!(skipped[0]["reason"].as_str().unwrap().contains("Perspective Distort or Free Distort"), "{out}");
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
// Without a distorted image, no `skipped`.
let other = rect(&mut s, 400.0, 0.0, 100.0, 100.0);
let out = s.execute("object.mesh.create", &json!({"ids": [other.0], "rows": 1, "cols": 1})).unwrap();
assert!(out.get("skipped").is_none(), "{out}");
}
/// A blend takes the warp's affine approximation whole, so an image inside it does not stop a
/// distort whose corners an image could not follow.
#[test]
fn distort_of_a_blend_holding_an_image_is_not_refused() {
let mut s = session();
let img = placed_image(&mut s);
let r = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
let out = s.execute("object.blend.make", &json!({"ids": [img.0, r.0]})).unwrap();
let blend = NodeId(out["id"].as_u64().unwrap());
let undo = undo_len(&s);
s.execute("object.distort", &json!({"ids": [blend.0], "corners": [[0, 0], [300, 0], [100, 50], [0, 100]]})).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
}
/// The Control bar's Mask clips a distorted image to the shape between its corners.
#[test]
fn mask_on_a_distorted_image_follows_its_corners() {
let mut s = session();
let img = placed_image(&mut s);
let want = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let out = s.execute("object.maskImage", &json!({})).unwrap();
let path = NodeId(out["path"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
assert_eq!(anchors.len(), 4, "{anchors:?}");
for (x, y) in want {
assert!(anchors.iter().any(|a| a.distance(Point::new(x, y)) < 1e-9), "{x},{y} not in {anchors:?}");
}
assert!(d.node(img).unwrap().is_distorted_image());
}
/// A Transform effect moves a distorted image's corners with it: expanded, the image stands
/// where the effect drew it.
#[test]
fn a_transform_effect_moves_a_distorted_images_corners() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let mut found = vec![];
for layer in &s.doc().unwrap().doc.layers {
layer.walk(&mut |n| {
if let Some(q) = n.image_corners() {
found.push(q);
}
});
}
let want = [(240.0, 0.0), (260.0, 0.0), (300.0, 100.0), (200.0, 100.0)];
assert!(found.iter().any(|q| q.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-6)), "{found:?}");
}
/// A Transform effect after a Warp effect moves a distorted image's warped pixels once: the art
/// stands where the Warp alone draws it, moved by the Transform.
#[test]
fn a_transform_after_a_warp_moves_a_distorted_image_once() {
let expanded_bounds = |transform: bool| {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "warp.bulge", "params": {"bend": 50}})).unwrap();
if transform {
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
}
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let mut images = None;
for layer in &s.doc().unwrap().doc.layers {
layer.walk(&mut |n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
let r = im.xf.transform_rect_bbox(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)));
images = Some(images.map_or(r, |b: vectorcraft_geom::Rect| b.union(r)));
}
});
}
images.expect("the warped pieces")
};
let (alone, moved) = (expanded_bounds(false), expanded_bounds(true));
assert!((moved.x0 - alone.x0 - 200.0).abs() < 1e-6 && (moved.x1 - alone.x1 - 200.0).abs() < 1e-6, "{alone:?} {moved:?}");
assert!((moved.y0 - alone.y0).abs() < 1e-6 && (moved.y1 - alone.y1).abs() < 1e-6, "{alone:?} {moved:?}");
}
/// A raster effect's baked pixels already show the distortion: the image that replaces a
/// distorted one is placed by its own transform.
#[test]
fn baked_raster_effect_pixels_replace_a_distortion() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let v = s.doc().unwrap().doc.node(img).unwrap().clone();
let baked = Node::new(NodeId(99), v.kind.clone());
let out = crate::cmd::rasterfx::replace_with_image(v, baked);
assert!(!out.is_distorted_image());
assert!(out.extras().image_quad.is_none());
}
/// A distorted image is saved with its corners and reads back the same.
#[test]
fn a_distorted_image_saves_and_reads_back() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let doc = &s.doc().unwrap().doc;
let bytes = vectorcraft_format::save(doc, false);
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(img).unwrap().image_corners(), doc.node(img).unwrap().image_corners());
assert!(back.node(img).unwrap().is_distorted_image());
assert!(String::from_utf8_lossy(&bytes).contains("image_quad"));
// An image without a distortion is saved without the field, and opens as it was.
let mut plain = session();
let img = placed_image(&mut plain);
let doc = &plain.doc().unwrap().doc;
let bytes = vectorcraft_format::save(doc, false);
assert!(!String::from_utf8_lossy(&bytes).contains("image_quad"));
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(img), doc.node(img));
// Corners in a file that fold the image over leave it placed by its transform.
let mut bad = (**doc).clone();
bad.node_mut(img).unwrap().extras_mut().image_quad =
Some(Box::new([(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)].map(|(x, y)| Point::new(x, y))));
let back = vectorcraft_format::load(&vectorcraft_format::save(&bad, false)).unwrap();
assert!(!back.node(img).unwrap().is_distorted_image());
assert_corners(back.node(img).unwrap().image_corners().unwrap(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
}
/// A distort whose corners cross the warp's horizon at the image is refused with that reason, and
/// a distort that leaves a distorted image where it is records nothing.
#[test]
fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing() {
let mut s = session();
let img = placed_image(&mut s);
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
// The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
// y = 15, inside the image.
let e = s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
assert!(e.contains("horizon"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let b = bounds(&s, img);
let at = [[b.x0, b.y0], [b.x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]];
s.execute("object.distort", &json!({ "from": [b.x0, b.y0, b.x1, b.y1], "corners": at })).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
}
/// Image info gives a distorted image's resolution at its middle, not the resolution it had
/// before the distort.
#[test]
fn image_info_measures_a_distorted_image_at_its_middle() {
let mut s = session();
placed_image(&mut s);
// 2 pixels across 100 pt: 1.44 ppi.
let ppi = |s: &mut Session| {
let out = s.execute("image.info", &json!({})).unwrap();
[out["ppi"][0].as_f64().unwrap(), out["ppi"][1].as_f64().unwrap()]
};
assert!((ppi(&mut s)[0] - 1.44).abs() < 1e-9);
// The top squeezed to half the width: the middle of the pixels spans less than 100 pt across,
// so the resolution across there is higher.
s.execute("object.distort", &json!({ "corners": [[25, 0], [75, 0], [100, 100], [0, 100]] })).unwrap();
let [x, _] = ppi(&mut s);
assert!(x > 1.44 * 1.1, "{x}");
}
/// Rasterize draws a distorted image's pixels between its corners, and the image it makes is a
/// plain one.
#[test]
fn rasterize_draws_a_distorted_image_between_its_corners() {
let mut s = session();
let img = placed_image(&mut s);
let mut png = std::io::Cursor::new(vec![]);
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();
s.edit("Pixels", |d, _| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png.into_inner()));
Ok(())
})
.unwrap();
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("select.set", &json!({ "ids": [img.0] })).unwrap();
let out = s.execute("object.rasterize", &json!({ "ppi": 72, "background": "transparent", "addAround": 0 })).unwrap();
let d = &s.doc().unwrap().doc;
let id = NodeId(out["id"].as_u64().unwrap());
let n = d.node(id).unwrap();
assert!(!n.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &n.kind else { panic!("an image") };
// The raster covers the corners' bounds.
let b = n.geometric_bounds().unwrap();
assert!([b.x0, b.y0, b.x1 - 100.0, b.y1 - 100.0].iter().all(|v| v.abs() <= 1.0), "{b:?}");
let px = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
let (w, h) = px.dimensions();
let rgba = px.to_rgba8();
let alpha = |x: f64, y: f64| {
let p = im.xf.inverse() * Point::new(x, y);
assert!(p.x >= 0.0 && p.y >= 0.0 && p.x < f64::from(w) && p.y < f64::from(h), "({x}, {y}) is outside the raster: {p:?}");
let (i, j) = (p.x as u32, p.y as u32);
rgba[((j * w + i) * 4 + 3) as usize]
};
assert_eq!(alpha(50.0, 90.0), 255, "inside the corners");
assert_eq!(alpha(10.0, 10.0), 0, "inside the old rectangle, outside the corners");
}
/// A Free Transform drag in Free Distort mode on an image puts the dragged corner where the drag
/// ends, in one undo step, also when a position on the way would have folded the image.
#[test]
fn free_transform_distort_drag_on_an_image_is_one_undo_step() {
let mut s = session();
let img = placed_image(&mut s);
let undo = undo_len(&s);
let v = ViewInfo::default();
s.select_tool("freeTransform", v).unwrap();
s.set_tool_option("mode", &json!("distort"));
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
// Past the top left corner: the image would fold over.
s.pointer(&PointerEvent::new(PointerKind::Drag, -50.0, -50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 120.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 120.0), v).unwrap();
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (130.0, 120.0), (0.0, 100.0)]);
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
assert_eq!(undo_len(&s), undo + 1);
}
#[test]
fn free_transform_distort_mode_via_pointer() {
let mut s = session();