mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 03:51:16 +00:00
Merge main into feat/live-paint-bucket-multi-click
This commit is contained in:
@@ -1490,6 +1490,93 @@ fn shape_builder_open_filled_paths_cut_without_open_filled_as_closed() {
|
||||
assert!((area(&s, NodeId(r["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The fill rows of an open path's appearance (bottom first) for the open-path tests below, with
|
||||
/// a 1 pt black stroke on top: a painted fill under an unpainted top fill, a painted fill that is
|
||||
/// hidden, one with an opacity of 0, and a painted fill under a hidden painted top fill.
|
||||
fn open_path_fill_stacks() -> [(&'static str, Vec<AppearanceItem>, bool); 4] {
|
||||
use vectorcraft_doc::{FillLayer, StrokeLayer};
|
||||
let fill = |p: Paint, visible: bool, opacity: f32| {
|
||||
let mut f = FillLayer::new(p);
|
||||
f.visible = visible;
|
||||
f.opacity = opacity;
|
||||
AppearanceItem::Fill(f)
|
||||
};
|
||||
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0));
|
||||
[
|
||||
("a painted fill under an unpainted top fill", vec![fill(red(), true, 1.0), fill(Paint::None, true, 1.0), stroke()], true),
|
||||
("a hidden painted fill", vec![fill(red(), false, 1.0), stroke()], false),
|
||||
("a painted fill with an opacity of 0", vec![fill(red(), true, 0.0), stroke()], false),
|
||||
("a painted fill under a hidden painted top fill", vec![fill(red(), true, 1.0), fill(blue(), false, 1.0), stroke()], true),
|
||||
]
|
||||
}
|
||||
|
||||
/// Consider Open Filled Paths as Closed: an open path counts as filled when any of its fill rows
|
||||
/// draws (shown, painted and above 0% opacity), whichever row is on top. The map, a merge inside
|
||||
/// the area and what a merge keeps of the path follow the rows that draw; with the option off, none
|
||||
/// of the paths closes.
|
||||
#[test]
|
||||
fn shape_builder_closes_open_paths_by_the_fill_rows_that_draw() {
|
||||
for (what, items, closes) in open_path_fill_stacks() {
|
||||
let mut s = session();
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
|
||||
let p = NodeId(r["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(p).unwrap().appearance.items = items;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
(r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()),
|
||||
if closes { (1, 0) } else { (0, 1) },
|
||||
"{what}: {r}"
|
||||
);
|
||||
let r = s.execute("shapeBuilder.regions", &json!({"openFilledAsClosed": false})).unwrap();
|
||||
assert_eq!((r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), (0, 1), "{what}, option off: {r}");
|
||||
let n = node(&s, p);
|
||||
for on in [true, false] {
|
||||
let inputs = vectorcraft_tools::builder::merge_inputs(&[&n], on);
|
||||
assert_eq!(inputs.iter().map(|i| i.fill_closes).collect::<Vec<_>>(), vec![closes && on], "{what}, option {on}");
|
||||
}
|
||||
let merged = s.execute("shapeBuilder.merge", &json!({"points": [[75, 25]]}));
|
||||
if closes {
|
||||
assert!((area(&s, NodeId(merged.unwrap()["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6, "{what}");
|
||||
} else {
|
||||
assert!(merged.is_err(), "{what}: the open path encloses no region");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clicking Stroke Splits the Path on the middle side of an open U cuts it along the outline its
|
||||
/// drawn fill closes: with a fill row that draws, what is left runs on from the cut round the
|
||||
/// implied closing edge (the top side, then the bottom side); without one, what is left is the
|
||||
/// open path's two ends in path order (the bottom side, then the top side).
|
||||
#[test]
|
||||
fn shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw() {
|
||||
for (what, items, closes) in open_path_fill_stacks() {
|
||||
let mut s = session();
|
||||
let r =
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}]})).unwrap();
|
||||
let p = NodeId(r["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(p).unwrap().appearance.items = items;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[101, 50]], "splitStroke": true})).unwrap();
|
||||
let out = ids(&r);
|
||||
assert_eq!(shapes_of(&s, &out), vec![(false, 4, 200.0), (false, 2, 100.0)], "{what}");
|
||||
let (rest, _) = outline(&node(&s, out[0]));
|
||||
let starts: Vec<(f64, f64)> = rest.subpaths.iter().map(|sp| (sp.anchors[0].p.x.round(), sp.anchors[0].p.y.round())).collect();
|
||||
let order = if closes { vec![(100.0, 100.0), (0.0, 0.0)] } else { vec![(0.0, 0.0), (100.0, 100.0)] };
|
||||
assert_eq!(starts, order, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick Color From Color Swatches: the merged shape takes the current fill, not the fill of the
|
||||
/// object under the first point; setting the current fill without `ids` leaves the selection's.
|
||||
#[test]
|
||||
@@ -4607,6 +4694,58 @@ fn shape_builder_uses_the_filled_faces_of_a_live_paint_group() {
|
||||
assert!((stroked_length(&s, &out) - 600.0).abs() < 1.0, "{}", stroked_length(&s, &out));
|
||||
}
|
||||
|
||||
/// The Shape Builder takes a Live Paint face or edge when any of its fill or stroke rows draws,
|
||||
/// whichever row is on top: a painted lower row under an unpainted top row counts, and a part
|
||||
/// whose only painted row is hidden, transparent or (for an edge) 0 pt wide, or whose own opacity
|
||||
/// is 0, does not.
|
||||
#[test]
|
||||
fn shape_builder_takes_the_live_paint_faces_and_edges_that_draw() {
|
||||
use vectorcraft_doc::{FillLayer, StrokeLayer};
|
||||
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
|
||||
let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w));
|
||||
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let hidden = |mut i: AppearanceItem| {
|
||||
match &mut i {
|
||||
AppearanceItem::Fill(f) => f.visible = false,
|
||||
AppearanceItem::Stroke(st) => st.visible = false,
|
||||
}
|
||||
i
|
||||
};
|
||||
let clear = |mut i: AppearanceItem| {
|
||||
match &mut i {
|
||||
AppearanceItem::Fill(f) => f.opacity = 0.0,
|
||||
AppearanceItem::Stroke(st) => st.opacity = 0.0,
|
||||
}
|
||||
i
|
||||
};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let lower_fill = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), fill(Paint::None)], 1.0);
|
||||
let hidden_fill = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red()))], 1.0);
|
||||
let clear_fill = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![clear(fill(red()))], 1.0);
|
||||
let lower_stroke = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 2.0), stroke(Paint::None, 1.0)], 1.0);
|
||||
let hidden_stroke = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![hidden(stroke(red(), 2.0))], 1.0);
|
||||
let thin_stroke = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0);
|
||||
let clear_stroke = set_live_part(&mut s, g, None, Some((50.0, 50.0)), vec![clear(stroke(red(), 2.0))], 1.0);
|
||||
let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0);
|
||||
let parts = [lower_fill, hidden_fill, clear_fill, lower_stroke, hidden_stroke, thin_stroke, clear_stroke, clear_edge];
|
||||
assert_eq!(parts.iter().collect::<std::collections::HashSet<_>>().len(), parts.len());
|
||||
let d = s.doc().unwrap();
|
||||
let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true);
|
||||
let taken: Vec<NodeId> = leaves.iter().map(|l| l.id).collect();
|
||||
assert!(taken.contains(&lower_fill) && taken.contains(&lower_stroke), "a painted lower row draws: {taken:?}");
|
||||
for id in [hidden_fill, clear_fill, hidden_stroke, thin_stroke, clear_stroke, clear_edge] {
|
||||
assert!(!taken.contains(&id), "{id:?} draws nothing: {taken:?}");
|
||||
}
|
||||
// A face with a painted fill whose own opacity is 0 is left out too.
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let clear_face = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![fill(red())], 0.0);
|
||||
let d = s.doc().unwrap();
|
||||
let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true);
|
||||
assert!(!leaves.iter().any(|l| l.id == clear_face), "a face with an opacity of 0 draws nothing");
|
||||
}
|
||||
|
||||
/// An edge that closes on itself is a line around its face, not a second shape over it.
|
||||
#[test]
|
||||
fn shape_builder_takes_a_closed_live_paint_edge_as_a_line() {
|
||||
|
||||
@@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() {
|
||||
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art));
|
||||
assert!(b.x1 < 95.0, "{b:?}");
|
||||
assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text");
|
||||
// An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame.
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap();
|
||||
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow");
|
||||
// Release gives the text back.
|
||||
select(&mut s, &[g]);
|
||||
s.execute("object.clippingMask.release", &json!({})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() {
|
||||
// The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The
|
||||
// hidden rectangle does not clip, so clicks inside the clip group still count the type by its
|
||||
// frame, the counter of the "O" included.
|
||||
let mut s = session();
|
||||
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap());
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap());
|
||||
let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap();
|
||||
let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap();
|
||||
select(&mut s, &[art, t]);
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
// Make Clipping Mask takes no group on top, so the group goes in place of the type.
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
let mut rect = (*d.remove(r).unwrap()).clone();
|
||||
rect.visible = false;
|
||||
let text = d.remove(t).unwrap();
|
||||
let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]);
|
||||
d.insert(Some(g), 0, group).unwrap();
|
||||
let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf);
|
||||
let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
|
||||
assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame");
|
||||
assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_follow_the_region_a_clipping_paths_effects_give_it() {
|
||||
// Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves
|
||||
// 50 pt right: the art shows on the right half, as clicks find it.
|
||||
let mut s = session();
|
||||
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap());
|
||||
let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap());
|
||||
select(&mut s, &[art, clip]);
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap();
|
||||
let r = render(&s);
|
||||
assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region");
|
||||
assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path");
|
||||
assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None);
|
||||
assert_eq!(at(75.0), [g]);
|
||||
assert!(at(25.0).is_empty());
|
||||
// A marquee across the art's edge reaches it within the moved region only.
|
||||
let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true);
|
||||
assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region");
|
||||
assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place");
|
||||
|
||||
// The same with a sublayer that clips by its first object.
|
||||
let mut d = (**d).clone();
|
||||
let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec();
|
||||
let top = d.layers[0].id;
|
||||
d.remove(g).unwrap();
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
|
||||
(*children, *clip) = (members, true);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf);
|
||||
assert_eq!(leaf(75.0), Some(art));
|
||||
assert_eq!(leaf(25.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_refuses_a_top_object_that_cannot_clip() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -248,7 +248,42 @@ fn the_list_shows_each_image_with_its_status() {
|
||||
assert_eq!(run(&mut s, "links.list", json!({"show": "missing"}))["links"][0]["id"], linked.0);
|
||||
assert_eq!(run(&mut s, "links.list", json!({"sort": "name"}))["links"][0]["name"], "a.png");
|
||||
assert!(s.execute("links.list", &json!({"show": "broken"})).is_err());
|
||||
assert!(s.execute("links.list", &json!({"sort": "size"})).is_err());
|
||||
assert!(s.execute("links.list", &json!({"sort": "date"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_size_lists_the_smallest_file_first() {
|
||||
let dir = Folder::new("list-size");
|
||||
let files = [("a.png", png(600, 300, RED)), ("b.png", png(10, 10, BLUE)), ("c.png", png(100, 100, RED)), ("d.png", png(10, 10, BLUE))];
|
||||
let mut s = session();
|
||||
for (name, bytes) in &files {
|
||||
let path = dir.file(name);
|
||||
write(&path, bytes);
|
||||
place(&mut s, &path);
|
||||
}
|
||||
let e = dir.file("e.png");
|
||||
write(&e, &png(1, 1, RED));
|
||||
place_embedded(&mut s, &e);
|
||||
let names = |s: &mut Session| -> Vec<String> {
|
||||
let l = run(s, "links.list", json!({"sort": "size"}));
|
||||
l["links"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap_or_default().to_string()).collect()
|
||||
};
|
||||
// Smallest first, equal sizes by name, the embedded image (no file) last.
|
||||
let mut want: Vec<(usize, &str)> = files.iter().map(|(n, b)| (b.len(), *n)).collect();
|
||||
want.sort();
|
||||
assert!(want[0].0 < want[2].0 && want[2].0 < want[3].0, "{want:?}");
|
||||
let mut want: Vec<String> = want.iter().map(|(_, n)| n.to_string()).collect();
|
||||
want.push("e.png".into());
|
||||
assert_eq!(names(&mut s), want);
|
||||
// A missing file sorts by the size the document keeps of it.
|
||||
std::fs::remove_file(dir.file("a.png")).unwrap();
|
||||
assert_eq!(names(&mut s), want);
|
||||
// A modified file sorts by its size now.
|
||||
let bigger = png(900, 900, BLUE);
|
||||
assert!(bigger.len() > files[0].1.len());
|
||||
write(&dir.file("c.png"), &bigger);
|
||||
let got = names(&mut s);
|
||||
assert_eq!(got[got.len() - 2..], ["c.png".to_string(), "e.png".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2234,6 +2234,10 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
|
||||
("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")),
|
||||
("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")),
|
||||
("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")),
|
||||
("type.smartPunctuation", json!({"fiLigatures": 1}), switch("fiLigatures")),
|
||||
("type.smartPunctuation", json!({"flLigatures": "true"}), switch("flLigatures")),
|
||||
("type.smartPunctuation", json!({"spaces": "on"}), switch("spaces")),
|
||||
("type.smartPunctuation", json!({"fractions": [true]}), switch("fractions")),
|
||||
("type.smartPunctuation", json!({"scope": 5}), scope.clone()),
|
||||
("type.smartPunctuation", json!({"scope": "page"}), scope),
|
||||
("type.changeCase", json!({"case": 5}), string("case")),
|
||||
@@ -3563,12 +3567,154 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() {
|
||||
for id in [t, r] {
|
||||
select_with_a_step_to_redo(&mut s, &[id]);
|
||||
let before = history(&s);
|
||||
assert_eq!(s.execute("type.smartPunctuation", &json!({})).unwrap(), json!({"changed": 0}), "{id:?}");
|
||||
let r = s.execute("type.smartPunctuation", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 0, "{id:?}");
|
||||
assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}");
|
||||
assert_eq!(history(&s), before, "{id:?}");
|
||||
}
|
||||
assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…");
|
||||
}
|
||||
|
||||
/// Does the face text `font` draws with have a glyph for every character of `chars`?
|
||||
fn font_covers(font: &str, chars: &str) -> bool {
|
||||
let face = vectorcraft_text::FontDb::global().face(font, "Regular");
|
||||
face.is_some_and(|f| chars.chars().all(|c| f.covers(c)))
|
||||
}
|
||||
|
||||
/// Every option on: the ligatures, Smart Spaces and Expert Fractions, each counted on its own, in
|
||||
/// one undo step. Fractions next to a digit, a slash or a decimal part are left as they are.
|
||||
#[test]
|
||||
fn smart_punctuation_ligatures_spaces_and_fractions_are_counted() {
|
||||
let mut s = session();
|
||||
assert!(font_covers("Source Sans 3", "\u{FB00}\u{FB01}\u{FB02}\u{FB03}\u{FB04}½¾"), "Source Sans 3 draws the ligatures and fractions");
|
||||
let words = "An office's fluffy flow. Then 1/2 and 3/4, not 1/25, 1/2/26 or 1/2.5.";
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
|
||||
sel(&mut s, &[t]);
|
||||
let undo = history(&s).0;
|
||||
let all = json!({"fiLigatures": true, "flLigatures": true, "quotes": true, "spaces": true, "dashes": true, "ellipsis": true, "fractions": true});
|
||||
let r = s.execute("type.smartPunctuation", &all).unwrap();
|
||||
assert_eq!(plain(&s, t), "An o\u{FB03}ce’s \u{FB02}u\u{FB00}y \u{FB02}ow. Then ½ and ¾, not 1/25, 1/2/26 or 1/2.5.");
|
||||
let replaced = json!({"fiLigatures": 2, "flLigatures": 2, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2});
|
||||
assert_eq!(r, json!({"changed": 1, "replaced": replaced}));
|
||||
assert_eq!(history(&s).0, undo + 1);
|
||||
}
|
||||
|
||||
/// The ff, fl, ffl option alone leaves fi and ffi as letters (ffi keeps its ff ligature, counted
|
||||
/// with this option), and the other options are off unless asked for.
|
||||
#[test]
|
||||
fn smart_punctuation_fl_ligatures_alone() {
|
||||
let mut s = session();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "office fit baffle. 1/2", "font": "Source Sans 3"})).unwrap());
|
||||
sel(&mut s, &[t]);
|
||||
let r = s.execute("type.smartPunctuation", &json!({"flLigatures": true})).unwrap();
|
||||
assert_eq!(plain(&s, t), "o\u{FB00}ice fit ba\u{FB04}e. 1/2");
|
||||
assert_eq!(r["replaced"], json!({"fiLigatures": 0, "flLigatures": 2, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0}));
|
||||
}
|
||||
|
||||
/// A ligature or a fraction the run's font has no glyph for stays as its letters, while the run's
|
||||
/// other replacements still happen.
|
||||
#[test]
|
||||
fn smart_punctuation_skips_ligatures_and_fractions_the_font_lacks() {
|
||||
let mut s = session();
|
||||
let mono = "JetBrains Mono";
|
||||
assert!(!font_covers(mono, "\u{FB01}") && !font_covers(mono, "⅐"), "{mono} has no fi ligature or one-seventh");
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "fit 1/7 a--b", "font": mono})).unwrap());
|
||||
sel(&mut s, &[t]);
|
||||
let r = s.execute("type.smartPunctuation", &json!({"fiLigatures": true, "fractions": true})).unwrap();
|
||||
assert_eq!(plain(&s, t), "fit 1/7 a–b");
|
||||
let counts = (&r["replaced"]["fiLigatures"], &r["replaced"]["fractions"], &r["replaced"]["dashes"]);
|
||||
assert_eq!(counts, (&json!(0), &json!(0), &json!(1)));
|
||||
}
|
||||
|
||||
/// A fraction at the end of a run is checked against the start of the next run: 1/25 and 1/2.5
|
||||
/// split after their 1/2 stay as they are, and a 1/2 the next run's space ends is replaced.
|
||||
#[test]
|
||||
fn expert_fractions_look_past_the_end_of_a_run() {
|
||||
let mut s = session();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "1/25 1/2.5 1/2 x", "font": "Source Sans 3"})).unwrap());
|
||||
for (start, end) in [(0, 3), (5, 8), (11, 14)] {
|
||||
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": start, "end": end, "size": 30})).unwrap();
|
||||
}
|
||||
sel(&mut s, &[t]);
|
||||
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
|
||||
assert_eq!(plain(&s, t), "1/25 1/2.5 ½ x");
|
||||
assert_eq!(r["replaced"]["fractions"], 1);
|
||||
}
|
||||
|
||||
/// An inline graphic separates the text on either side of it: the space after it is not a second
|
||||
/// space after the period before it, and the digit before it does not stop a fraction after it.
|
||||
#[test]
|
||||
fn an_inline_graphic_separates_smart_spaces_and_fractions() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 600.0, 500.0, 10.0, 10.0);
|
||||
sel(&mut s, &[r]);
|
||||
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "A. B 71/2", "font": "Source Sans 3"})).unwrap());
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 7, "symbol": "Mark"})).unwrap();
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 3, "symbol": "Mark"})).unwrap();
|
||||
let texts = |s: &Session| match node(s, t).kind {
|
||||
NodeKind::Text(o) => o.runs.iter().map(|r| if r.inline.is_some() { "[g]".to_string() } else { r.text.clone() }).collect::<String>(),
|
||||
_ => String::new(),
|
||||
};
|
||||
assert_eq!(texts(&s), "A. [g] B 7[g]1/2");
|
||||
sel(&mut s, &[t]);
|
||||
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fractions": true})).unwrap();
|
||||
assert_eq!(texts(&s), "A. [g] B 7[g]½");
|
||||
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fractions"]), (&json!(0), &json!(1)));
|
||||
}
|
||||
|
||||
/// Smart Spaces keeps one space after each period, also when the spaces start in the next run,
|
||||
/// and leaves single spaces and spaces after other characters alone.
|
||||
#[test]
|
||||
fn smart_spaces_keeps_one_space_after_a_period() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "A. B. C. D E");
|
||||
// "C." is in a run of its own, and the spaces after it start the next one.
|
||||
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": 8, "end": 10, "size": 30})).unwrap();
|
||||
assert!(matches!(node(&s, t).kind, NodeKind::Text(ref o) if o.runs.len() > 1));
|
||||
sel(&mut s, &[t]);
|
||||
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "quotes": false, "dashes": false, "ellipsis": false})).unwrap();
|
||||
assert_eq!(plain(&s, t), "A. B. C. D E");
|
||||
assert_eq!(r["replaced"]["spaces"], 2);
|
||||
}
|
||||
|
||||
/// Ruby stays on the characters it was set on when Smart Punctuation makes the text before them
|
||||
/// longer (curly quotes) or shorter (Smart Spaces), and no replacement takes in characters on both
|
||||
/// sides of a ruby span's end: the fi with ruby on its i stays as letters, and a second space after
|
||||
/// a period with ruby of its own stays.
|
||||
#[test]
|
||||
fn smart_punctuation_keeps_ruby_on_its_characters() {
|
||||
let mut s = session();
|
||||
let spans = |s: &Session, t| match node(s, t).kind {
|
||||
NodeKind::Text(o) => o.ruby.iter().map(|r| (r.start, r.end)).collect::<Vec<_>>(),
|
||||
_ => vec![],
|
||||
};
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "'A'. base fit X. Y", "font": "Source Sans 3"})).unwrap());
|
||||
sel(&mut s, &[t]);
|
||||
for (start, end) in [(1, 2), (6, 10), (12, 13), (18, 19)] {
|
||||
s.execute("type.ruby", &json!({"text": "r", "start": start, "end": end})).unwrap();
|
||||
}
|
||||
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fiLigatures": true})).unwrap();
|
||||
assert_eq!(plain(&s, t), "‘A’. base fit X. Y");
|
||||
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fiLigatures"]), (&json!(1), &json!(0)));
|
||||
let text = plain(&s, t);
|
||||
let on: Vec<&str> = spans(&s, t).into_iter().map(|(a, b)| &text[a..b]).collect();
|
||||
assert_eq!(on, ["A", "base", "i", " "]);
|
||||
}
|
||||
|
||||
/// Expert Fractions leaves a fraction next to a digit of another script as it is.
|
||||
#[test]
|
||||
fn expert_fractions_skip_fractions_next_to_digits_of_any_script() {
|
||||
let mut s = session();
|
||||
let words = "\u{662}1/2 1/2\u{662} 1/2.\u{662} 1/2";
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
|
||||
sel(&mut s, &[t]);
|
||||
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
|
||||
assert_eq!(plain(&s, t), "\u{662}1/2 1/2\u{662} 1/2.\u{662} ½");
|
||||
assert_eq!(r["replaced"]["fractions"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_point_area_roundtrip() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -775,6 +775,78 @@ fn create_outlines_draws_the_type_objects_own_paint() {
|
||||
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
|
||||
}
|
||||
|
||||
/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled
|
||||
/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20
|
||||
/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space).
|
||||
fn transformed_gradient_type(s: &mut Session, fill: Value) -> NodeId {
|
||||
let t = run(s, "text.create", json!({"x": 30, "y": 110, "text": "HIH", "size": 40}))["id"].as_u64().unwrap();
|
||||
run(s, "select.set", json!({"ids": [t]}));
|
||||
run(s, "type.ruby", json!({"text": "ab"}));
|
||||
run(s, "text.setFormat", json!({"ids": [t], "underline": true, "strikethrough": true}));
|
||||
run(s, "paint.setFill", fill);
|
||||
run(s, "paint.setStroke", json!({"color": "#008000"}));
|
||||
run(s, "stroke.set", json!({"weight": 2}));
|
||||
run(s, "object.scale", json!({"ids": [t], "sx": 150, "sy": 150}));
|
||||
run(s, "object.rotate", json!({"ids": [t], "angle": 20}));
|
||||
NodeId(t)
|
||||
}
|
||||
|
||||
/// Create Outlines draws what the type drew: a gradient on the characters that has no vector of
|
||||
/// its own keeps one gradient across every glyph, ruby glyph and bar, fitted to the layout's box,
|
||||
/// and one with a vector keeps it where it was, both with the type's scale and rotation. The
|
||||
/// characters' stroke keeps the weight it was drawn at.
|
||||
#[test]
|
||||
fn create_outlines_keeps_a_character_gradient_across_the_type() {
|
||||
let placed = json!({"gradient": {"kind": "linear", "start": [40, 100], "end": [110, 100],
|
||||
"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}});
|
||||
for fill in [red_blue(), placed] {
|
||||
let mut s = session();
|
||||
let t = transformed_gradient_type(&mut s, fill.clone());
|
||||
let NodeKind::Text(text) = &node(&s, t).kind else { panic!("not type") };
|
||||
assert!(!text.ruby.is_empty() && text.runs.iter().all(|r| r.style.underline && r.style.strikethrough), "{fill}");
|
||||
// The characters' stroke is kept in text space and drawn scaled by the type's transform.
|
||||
let weight = text.runs[0].style.stroke_layer().width;
|
||||
let drawn = weight * vectorcraft_doc::Scaling::factor(text.xf).unwrap_or(1.0);
|
||||
assert!((drawn - weight).abs() > 0.1, "the type's transform scales: {weight} {drawn}");
|
||||
let before = render(&s);
|
||||
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
|
||||
let after = render(&s);
|
||||
let n = differing(&before, &after, 24);
|
||||
assert!(n < 60, "{fill}: {n} pixels differ");
|
||||
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
|
||||
// Every glyph, ruby glyph and bar takes the same gradient, placed, and the stroke at the
|
||||
// weight it was drawn at.
|
||||
let mut gradients = vec![];
|
||||
let mut widths = vec![];
|
||||
node(&s, NodeId(g)).walk(&mut |c: &Node| {
|
||||
if let Paint::Gradient(gr) = c.appearance.fill_paint() {
|
||||
gradients.push(gr.clone());
|
||||
}
|
||||
widths.extend(c.appearance.stroke().map(|st| st.width));
|
||||
});
|
||||
assert!(gradients.len() >= 6, "{fill}: three glyphs, ruby and two bars: {}", gradients.len());
|
||||
assert!(gradients.iter().all(|gr| gr.is_placed() && *gr == gradients[0]), "{fill}: {gradients:?}");
|
||||
assert!(widths.len() == gradients.len() && widths.iter().all(|w| (w - drawn).abs() < 1e-9), "{fill}: {drawn} {widths:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand outlines the type before its fills expand, so a gradient on its characters that has no
|
||||
/// vector of its own expands across the whole type, as the canvas draws it, and the query reports
|
||||
/// it.
|
||||
#[test]
|
||||
fn expand_keeps_a_character_gradient_across_the_type() {
|
||||
let mut s = session();
|
||||
transformed_gradient_type(&mut s, red_blue());
|
||||
let info = run(&mut s, "object.expand.info", json!({}));
|
||||
assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(true), json!(true), json!(true)), "{info}");
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", json!({}));
|
||||
let after = render(&s);
|
||||
assert_eq!(gradients_and_type(&s), (0, 0), "outlined and expanded");
|
||||
let d = mean_diff(&before, &after);
|
||||
assert!(d < 0.5, "{d}");
|
||||
}
|
||||
|
||||
/// `object.expand.info` reports the type object's own stroke, pattern fill and gradient fill, which
|
||||
/// Object turns into paths of its whole outline: a gradient only when that outline's box needs no
|
||||
/// more runs than are written.
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Automatic Plane Positioning: Shift held over an anchor point of art in perspective or over a
|
||||
//! gridline intersection moves the active plane through it for now (`perspective.plane.infer`),
|
||||
//! the two Perspective Grid Options that turn the targets on and off, and what ends it.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{Point, Vec2};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::tests_persp_select::{attached, bounds_of, drag, grid, persp_session, plane_pts, undo_len};
|
||||
use crate::*;
|
||||
|
||||
fn shift() -> Mods {
|
||||
Mods { shift: true, ..Default::default() }
|
||||
}
|
||||
|
||||
/// The top anchor of path `id` (on the right wall at depth 0): its page point and its height.
|
||||
fn top_anchor(s: &Session, id: NodeId) -> (Point, f64) {
|
||||
let page: Vec<Point> = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
|
||||
let plane = plane_pts(s, id, Plane::Right, 0.0);
|
||||
page.into_iter().zip(plane).map(|(p, q)| (p, q.y)).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap()
|
||||
}
|
||||
|
||||
fn hover(s: &mut Session, p: Point, mods: Mods) {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, p.x, p.y).with_mods(mods), ViewInfo::default()).unwrap();
|
||||
}
|
||||
|
||||
fn revision(s: &Session) -> u64 {
|
||||
s.doc().unwrap().revision
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_over_an_anchor_holds_the_active_plane_at_its_height_until_an_object_is_drawn() {
|
||||
let (mut s, id) = persp_session();
|
||||
let v = ViewInfo::default();
|
||||
let (anchor, height) = top_anchor(&s, id);
|
||||
assert!(height > 10.0, "{height}");
|
||||
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
|
||||
s.select_tool("perspectiveSelection", v).unwrap();
|
||||
let steps = undo_len(&s);
|
||||
// Without Shift the pointer only hovers.
|
||||
hover(&mut s, anchor, Mods::default());
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
hover(&mut s, anchor, shift());
|
||||
let g = grid(&s);
|
||||
assert!(g.inferred.is_some());
|
||||
assert!((g.offset(Plane::Ground) - height).abs() < 1e-6, "{} {height}", g.offset(Plane::Ground));
|
||||
assert_eq!((g.ground_offset, g.shown_planes(), undo_len(&s)), (0.0, vec![Plane::Ground], steps));
|
||||
// Held there already, another hover over the anchor changes nothing.
|
||||
let rev = revision(&s);
|
||||
hover(&mut s, anchor, shift());
|
||||
assert_eq!(revision(&s), rev);
|
||||
// The Rectangle tool draws on the plane where it is held, and the plane stays put for the drag.
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 400.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 470.0, 430.0), v).unwrap();
|
||||
assert!(grid(&s).inferred.is_some(), "held while the object is drawn");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 470.0, 430.0), v).unwrap();
|
||||
let drawn = s.doc().unwrap().selection.objects[0];
|
||||
assert_ne!(drawn, id);
|
||||
let (plane, depth) = attached(&s, drawn).unwrap();
|
||||
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
|
||||
// Drawn, the plane is back in its place and the other planes show: one undo step for the drag.
|
||||
let g = grid(&s);
|
||||
assert_eq!((g.inferred, g.offset(Plane::Ground), g.shown_planes().len(), undo_len(&s)), (None, 0.0, 3, steps + 1));
|
||||
// Undoing the drag holds the plane again; Escape with the Perspective Selection tool ends that.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
s.select_tool("perspectiveSelection", v).unwrap();
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_during_a_drag_still_constrains_the_move() {
|
||||
let (mut s, id) = persp_session();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("perspectiveSelection", v).unwrap();
|
||||
let before = plane_pts(&s, id, Plane::Right, 0.0);
|
||||
let h = grid(&s).homography(Plane::Right).unwrap();
|
||||
// From the middle of the object, along the wall and a little up.
|
||||
let start = bounds_of(&before).center();
|
||||
let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap());
|
||||
drag(&mut s, &[from, to, to], shift());
|
||||
assert_eq!(grid(&s).inferred, None, "with a button down Shift constrains the move");
|
||||
for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) {
|
||||
assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "{a:?} → {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gridline_intersection_brings_each_plane_made_active_through_it() {
|
||||
let (mut s, _) = persp_session();
|
||||
let (g, steps) = (grid(&s), undo_len(&s));
|
||||
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
|
||||
let at = g.to_page(Plane::Left, Point::new(3.0 * g.cell, 2.0 * g.cell)).unwrap();
|
||||
let r = s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y], "tolerance": 1})).unwrap();
|
||||
assert_eq!((r["active"].as_bool(), r["source"].as_str(), r["plane"].as_str()), (Some(true), Some("gridline"), Some("left")));
|
||||
for (got, want) in r["point"].as_array().unwrap().iter().zip([0.0, 2.0 * g.cell, 3.0 * g.cell]) {
|
||||
assert!((got.as_f64().unwrap() - want).abs() < 1e-6, "{r}");
|
||||
}
|
||||
for (plane, want) in [("ground", 2.0 * g.cell), ("right", 3.0 * g.cell), ("left", 0.0)] {
|
||||
s.execute("perspective.plane.set", &json!({"plane": plane})).unwrap();
|
||||
let r = s.execute("perspective.plane.infer", &json!({})).unwrap();
|
||||
assert!((r["offset"].as_f64().unwrap() - want).abs() < 1e-6 && r["active"] == json!(true) && r.get("source").is_none(), "{plane}: {r}");
|
||||
}
|
||||
let held = grid(&s);
|
||||
assert_eq!((held.left_offset, held.right_offset, held.ground_offset, undo_len(&s)), (0.0, 0.0, 0.0, steps));
|
||||
// Nothing within reach leaves the plane where it is held.
|
||||
let rev = revision(&s);
|
||||
let mid = held.to_page(Plane::Left, Point::new(3.5 * g.cell, 2.5 * g.cell)).unwrap();
|
||||
let r = s.execute("perspective.plane.infer", &json!({"at": [mid.x, mid.y], "tolerance": 0.5})).unwrap();
|
||||
assert!(r["active"] == json!(true) && r.get("source").is_none() && revision(&s) == rev, "{r}");
|
||||
// With no active plane nothing is held.
|
||||
s.execute("perspective.plane.set", &json!({"plane": "none"})).unwrap();
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
assert!(s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y]})).is_err(), "no active plane");
|
||||
assert_eq!(s.execute("perspective.plane.infer", &json!({})).unwrap()["active"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_options_turn_the_targets_on_and_off_and_are_kept() {
|
||||
let (mut s, id) = persp_session();
|
||||
assert!(s.prefs.perspective_widget.anchor_point && s.prefs.perspective_widget.gridline_intersection, "both on by default");
|
||||
let (anchor, _) = top_anchor(&s, id);
|
||||
let infer = |s: &mut Session| s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01}));
|
||||
assert_eq!(infer(&mut s).unwrap()["source"], json!("anchor"));
|
||||
s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap();
|
||||
let r = s.execute("perspective.widget.options", &json!({"anchorPoint": false})).unwrap();
|
||||
assert_eq!((r["anchorPoint"].as_bool(), r["gridlineIntersection"].as_bool(), r["show"].as_bool()), (Some(false), Some(true), Some(true)));
|
||||
assert!(infer(&mut s).unwrap().get("source").is_none(), "the anchor is no target now");
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
let back: Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
|
||||
assert!(!back.perspective_widget.anchor_point && back.perspective_widget.gridline_intersection);
|
||||
s.execute("perspective.widget.options", &json!({"gridlineIntersection": false})).unwrap();
|
||||
assert!(infer(&mut s).is_err(), "both off");
|
||||
for bad in [json!({"anchorPoint": "yes"}), json!({"gridlineIntersection": 1})] {
|
||||
assert!(s.execute("perspective.widget.options", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(!s.prefs.perspective_widget.anchor_point, "a refused value changes nothing");
|
||||
s.execute("prefs.set", &json!({"key": "perspectiveWidget", "value": {"anchorPoint": true}})).unwrap();
|
||||
assert!(s.prefs.perspective_widget.anchor_point && !s.prefs.perspective_widget.gridline_intersection);
|
||||
// Preferences saved before the options existed read as both on.
|
||||
let old: vectorcraft_tools::distort::perspective::widget::WidgetOptions = serde_json::from_value(json!({"show": false})).unwrap();
|
||||
assert!(old.anchor_point && old.gridline_intersection && !old.show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_leave_the_grid_as_it_is() {
|
||||
let (mut s, id) = persp_session();
|
||||
let (anchor, _) = top_anchor(&s, id);
|
||||
let rev = revision(&s);
|
||||
for bad in [
|
||||
json!({"at": "here"}),
|
||||
json!({"at": [1]}),
|
||||
json!({"at": [anchor.x, anchor.y], "tolerance": -1}),
|
||||
json!({"at": [anchor.x, anchor.y], "tolerance": "wide"}),
|
||||
json!({"at": [anchor.x, anchor.y], "clear": true}),
|
||||
json!({"clear": "yes"}),
|
||||
] {
|
||||
assert!(s.execute("perspective.plane.infer", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!((grid(&s).inferred, revision(&s)), (None, rev));
|
||||
// Clearing when nothing is held changes nothing.
|
||||
assert_eq!(s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap()["active"], json!(false));
|
||||
assert_eq!(revision(&s), rev);
|
||||
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
|
||||
assert!(s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y]})).is_err(), "hidden grid");
|
||||
}
|
||||
|
||||
/// A session whose ground plane is held at the height of the attached rectangle's top anchor.
|
||||
fn held_session() -> (Session, NodeId, f64) {
|
||||
let (mut s, id) = persp_session();
|
||||
let (anchor, height) = top_anchor(&s, id);
|
||||
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
|
||||
let r = s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})).unwrap();
|
||||
assert_eq!(r["source"], json!("anchor"));
|
||||
(s, id, height)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attaching_an_object_ends_it_and_the_object_sits_where_the_plane_was_held() {
|
||||
let (mut s, _, height) = held_session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
|
||||
let flat = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("perspective.attach", &json!({"ids": [flat.0]})).unwrap();
|
||||
let (plane, depth) = attached(&s, flat).unwrap();
|
||||
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
|
||||
assert_eq!((grid(&s).inferred, grid(&s).ground_offset), (None, 0.0));
|
||||
// An attach of nothing, or to a plane it doesn't hold, leaves it held.
|
||||
let (mut s, ..) = held_session();
|
||||
s.execute("perspective.attach", &json!({"ids": []})).unwrap();
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
|
||||
let other = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("perspective.attach", &json!({"ids": [other.0], "plane": "right"})).unwrap();
|
||||
assert_eq!(attached(&s, other).map(|a| a.0), Some(Plane::Right));
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
// A move of an object already in perspective leaves it held; one brought into perspective ends it.
|
||||
let (mut s, id, height) = held_session();
|
||||
s.execute("perspective.move", &json!({"ids": [id.0], "from": [460, 400], "to": [470, 400]})).unwrap();
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
|
||||
let flat = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("perspective.move", &json!({"ids": [flat.0], "from": [430, 410], "to": [440, 410]})).unwrap();
|
||||
let (plane, depth) = attached(&s, flat).unwrap();
|
||||
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_plane_hiding_the_grid_and_reopening_the_file_end_it() {
|
||||
// A moved plane moves from where it is held and is placed there for good, in one undo step;
|
||||
// undoing the move holds it again.
|
||||
let (mut s, _, height) = held_session();
|
||||
let steps = undo_len(&s);
|
||||
s.execute("perspective.plane.move", &json!({"plane": "ground", "by": 10})).unwrap();
|
||||
let g = grid(&s);
|
||||
assert_eq!((g.inferred, undo_len(&s)), (None, steps + 1));
|
||||
assert!((g.ground_offset - (height + 10.0)).abs() < 1e-6, "{}", g.ground_offset);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((grid(&s).inferred.is_some(), grid(&s).ground_offset), (true, 0.0));
|
||||
// A refused move leaves it held.
|
||||
let (mut s, ..) = held_session();
|
||||
assert!(s.execute("perspective.plane.move", &json!({"plane": "ground", "offset": 1, "objects": "all"})).is_err());
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
// A plane dragged while it is held, then the drag canceled, is held again.
|
||||
let (mut s, ..) = held_session();
|
||||
s.begin_interaction("Move Plane").unwrap();
|
||||
s.preview("perspective.plane.move", &json!({"plane": "ground", "by": 20})).unwrap();
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
s.cancel_interaction().unwrap();
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
// Move Plane to Match Object.
|
||||
let (mut s, id, _) = held_session();
|
||||
s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap();
|
||||
assert_eq!((grid(&s).inferred, grid(&s).plane), (None, Plane::Right));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((grid(&s).inferred.is_some(), grid(&s).plane), (true, Plane::Ground), "undo holds it again");
|
||||
// With the plane placed at the object already, matching only puts the held plane back there.
|
||||
s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap();
|
||||
assert!(grid(&s).inferred.is_some());
|
||||
let steps = undo_len(&s);
|
||||
s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap();
|
||||
assert_eq!((grid(&s).inferred, grid(&s).offset(Plane::Right), undo_len(&s)), (None, 0.0, steps));
|
||||
// Hide Grid.
|
||||
let (mut s, ..) = held_session();
|
||||
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
// The grid's definition changing leaves it held, and it is not `perspective.grid.set`'s to set.
|
||||
let (mut s, ..) = held_session();
|
||||
let held = grid(&s).inferred;
|
||||
s.execute("perspective.grid.set", &json!({"cell": 31, "inferred": [1, 2, 3]})).unwrap();
|
||||
assert_eq!(grid(&s).inferred, held);
|
||||
// `perspective.grid.set` hiding the grid or choosing no plane ends it.
|
||||
for patch in [json!({"visible": false}), json!({"plane": "none"})] {
|
||||
let (mut s, ..) = held_session();
|
||||
s.execute("perspective.grid.set", &patch).unwrap();
|
||||
assert_eq!(grid(&s).inferred, None, "{patch}");
|
||||
}
|
||||
// Another preset leaves it held, as other changes to the grid's definition do.
|
||||
let (mut preset, ..) = held_session();
|
||||
let before = grid(&preset).inferred;
|
||||
preset.execute("perspective.grid.preset", &json!({"kind": 3})).unwrap();
|
||||
assert_eq!((grid(&preset).kind, grid(&preset).inferred), (3, before));
|
||||
// A file saved while a plane is held opens with the plane in its place.
|
||||
let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false);
|
||||
let back = vectorcraft_format::load(&saved).unwrap();
|
||||
assert!(PerspectiveGrid::positioning(&back), "the saved file still holds the point");
|
||||
s.add_document(back, None);
|
||||
assert_eq!(grid(&s).inferred, None);
|
||||
assert_eq!(grid(&s).cell, 31.0);
|
||||
}
|
||||
@@ -520,7 +520,10 @@ fn the_plane_widget_stays_on_screen_and_takes_clicks_with_any_tool() {
|
||||
click(&mut s, q, view);
|
||||
assert_eq!(grid(&s).plane, Plane::Ground);
|
||||
// Perspective Grid Options move it to another corner or hide it.
|
||||
assert_eq!(run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), json!({"show": true, "position": "bottomRight"}));
|
||||
assert_eq!(
|
||||
run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})),
|
||||
json!({"show": true, "position": "bottomRight", "anchorPoint": true, "gridlineIntersection": true})
|
||||
);
|
||||
let r = face(&s, view, WidgetCorner::BottomRight, Plane::Left);
|
||||
assert!(r.x > 100.0 + 450.0 && r.y > 50.0 + 300.0, "{r:?}");
|
||||
click(&mut s, r, view);
|
||||
|
||||
@@ -599,6 +599,100 @@ fn with_link_a_pdf_page_places_linked() {
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// The colour at the centre of `r` in `doc`.
|
||||
fn colour_at(doc: &Document, r: Rect) -> [u8; 3] {
|
||||
let img = vectorcraft_render::Renderer::new().render_region(doc, r, 1.0, true);
|
||||
let [red, g, b, _] = img.pixel((r.width() / 2.0) as u32, (r.height() / 2.0) as u32);
|
||||
[red, g, b]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_pages_opens_each_picked_pdf_page_as_a_linked_placed_document() {
|
||||
let dir = Folder::new("open-pdf-link-pages");
|
||||
let src = dir.file("flyer.pdf");
|
||||
pdf_source(&src, "pdf", &[RED, BLUE, RED], 0);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"path": src, "linkPages": true, "pages": "2-3"})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["restored"].as_bool()), (Some("pdf"), Some(false)), "{r}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.path, None, "Save asks for a name instead of writing over the PDF");
|
||||
let d = &st.doc;
|
||||
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
|
||||
assert_eq!(boards, [Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(136.0, 0.0, 236.0, 50.0)]);
|
||||
let layers: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(layers, ["Page 2", "Page 3"]);
|
||||
let mut ids = vec![];
|
||||
for (layer, (page, board)) in d.layers.iter().zip([(2, boards[0]), (3, boards[1])]) {
|
||||
let kids = layer.children().unwrap();
|
||||
assert_eq!(kids.len(), 1);
|
||||
let p = placed(&s, kids[0].id);
|
||||
assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(page), false), "{p:?}");
|
||||
assert_eq!(bounds(&s, kids[0].id), board);
|
||||
ids.push(kids[0].id);
|
||||
}
|
||||
assert!(near(colour_at(d, boards[0]), BLUE));
|
||||
assert!(near(colour_at(d, boards[1]), RED));
|
||||
let links = s.execute("links.list", &json!({})).unwrap()["links"].clone();
|
||||
assert_eq!(links.as_array().map(Vec::len), Some(2), "{links}");
|
||||
assert!(links.as_array().unwrap().iter().all(|row| row["document"] == true && row["status"] == "ok"), "{links}");
|
||||
// Embed makes a page editable art.
|
||||
s.execute("links.embed", &json!({"ids": [ids[0].0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(ids[0]).unwrap().kind_label(), "Clip Group");
|
||||
assert_eq!(bounds(&s, ids[0]), boards[0]);
|
||||
assert!(near(colour_at(d, boards[0]), BLUE));
|
||||
// Every page, with the art's bounds as the artboard.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.artboards.len(), 3);
|
||||
assert!(d.layers.iter().flat_map(|l| l.children().unwrap()).all(|n| matches!(&n.kind, NodeKind::PlacedDocument(p) if p.bounding)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
let dir = Folder::new("open-pdf-link-pages-cmyk");
|
||||
let src = dir.file("cmyk.pdf");
|
||||
let page = || PdfPage::new(100.0, 50.0, "0 0.5 1 0 k 0 0 100 50 re f");
|
||||
write(&src, &pdf(&[page(), page(), page()], None));
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.color_mode, vectorcraft_doc::ColorMode::Cmyk, "pages painted in CMYK open as a CMYK document");
|
||||
let blobs: Vec<_> = d.images.values().map(|b| b.bytes.clone()).collect();
|
||||
assert_eq!(blobs.len(), 3);
|
||||
assert!(blobs.iter().all(|b| std::sync::Arc::ptr_eq(b, &blobs[0])), "one copy of the file for every page");
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "colorMode": "rgb"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() {
|
||||
let dir = Folder::new("open-pdf-link-pages-refused");
|
||||
let src = dir.file("flyer.pdf");
|
||||
pdf_source(&src, "pdf", &[RED, BLUE], 0);
|
||||
let bytes = std::fs::read(&src).unwrap();
|
||||
let logo = dir.file("logo.vectorcraft");
|
||||
source(&logo, 100.0, 50.0, RED, 0);
|
||||
let mut s = Session::new();
|
||||
let cases = [
|
||||
(json!({"name": "flyer.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "linkPages": true}), "needs the file's path"),
|
||||
(json!({"path": logo, "linkPages": true}), "isn't a PDF"),
|
||||
(json!({"path": src, "linkPages": true, "password": "secret"}), "password"),
|
||||
(json!({"path": src, "linkPages": true, "textAs": "outlines"}), "textAs: outlines"),
|
||||
(json!({"path": src, "linkPages": "yes"}), "linkPages must be true or false"),
|
||||
(json!({"path": src, "linkPages": true, "pages": "3"}), "pages:"),
|
||||
];
|
||||
for (p, says) in cases {
|
||||
let e = s.execute("document.open", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{p}: {e}");
|
||||
}
|
||||
assert!(s.documents().is_empty(), "nothing opened");
|
||||
// Off, the pages open as editable art.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": false})).unwrap();
|
||||
assert!(!s.doc().unwrap().doc.has_placed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_pdf_is_modified_and_update_links_reads_it_again() {
|
||||
let dir = Folder::new("placed-pdf-update");
|
||||
|
||||
@@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() {
|
||||
assert_eq!((out.contains("<image"), out.contains("<feBlend")), (image, !image), "{mode}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The `defaults` of `svgFilter.list`: each one's name and whether the document holds it.
|
||||
fn defaults(s: &mut Session) -> Vec<(String, bool)> {
|
||||
let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default();
|
||||
listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// Every document lists the default filters without holding them; applying one adds the effect and
|
||||
/// the document's copy in one undo step.
|
||||
#[test]
|
||||
fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() {
|
||||
use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS;
|
||||
let mut s = session();
|
||||
let listed = defaults(&mut s);
|
||||
assert_eq!(listed.len(), DEFAULT_FILTERS.len());
|
||||
assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them");
|
||||
assert!(names(&mut s).is_empty());
|
||||
let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap();
|
||||
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false}));
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let before = steps(&s);
|
||||
let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"}));
|
||||
assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0)));
|
||||
assert_eq!(steps(&s), before + 1, "the effect and the copy are one step");
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
|
||||
assert_eq!(names(&mut s), ["Soft Shadow"]);
|
||||
assert_eq!(drawn(&s, a), json!(soft.xml));
|
||||
assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true)));
|
||||
// Applied again, the document's copy is the filter: nothing more is added.
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]}));
|
||||
assert_eq!(names(&mut s), ["Soft Shadow"]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect");
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml)));
|
||||
// Nothing to apply it to: no copy and no step.
|
||||
let mut s = session();
|
||||
assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected");
|
||||
assert!(names(&mut s).is_empty());
|
||||
assert_eq!(steps(&s), 0);
|
||||
assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly");
|
||||
}
|
||||
|
||||
/// With a full history, applying a default lets one old step go, as any edit does: the copy joins
|
||||
/// the step that applied it, and one Undo takes both back.
|
||||
#[test]
|
||||
fn a_default_applied_with_a_full_history_is_still_one_step() {
|
||||
let mut s = session();
|
||||
s.active_mut().unwrap().history.limit = 3;
|
||||
let a = rect(&mut s, 10.0);
|
||||
rect(&mut s, 30.0);
|
||||
rect(&mut s, 50.0);
|
||||
assert_eq!(steps(&s), 3);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]}));
|
||||
// The application takes one place in the history: only the oldest step went.
|
||||
assert_eq!(steps(&s), 3);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(names(&mut s).is_empty(), "the copy is undone with the effect");
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
/// Edit SVG Filter on a default saves the edited copy in the document under the default's name;
|
||||
/// the document's filter then stands in the default's place, and deleting it lists the default again.
|
||||
#[test]
|
||||
fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() {
|
||||
use vectorcraft_render::effects::svg_filter::defaults::default_filter;
|
||||
let mut s = session();
|
||||
let glow = default_filter("Glow").unwrap();
|
||||
// Saved with its own code: nothing to keep, and no undo step.
|
||||
run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"}));
|
||||
assert_eq!((names(&mut s).len(), steps(&s)), (0, 0));
|
||||
let edited = r#"<filter id="Renamed"><feGaussianBlur stdDeviation="9"/></filter>"#;
|
||||
assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow");
|
||||
assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1));
|
||||
assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter");
|
||||
let kept = r#"<filter id="Glow"><feGaussianBlur stdDeviation="9"/></filter>"#;
|
||||
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name");
|
||||
// Applying the name now applies the document's filter.
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]}));
|
||||
assert_eq!(drawn(&s, a), json!(kept));
|
||||
// Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default.
|
||||
run(&mut s, "svgFilter.delete", json!({"name": "Glow"}));
|
||||
assert_eq!(drawn(&s, a), json!(""));
|
||||
assert!(defaults(&mut s).contains(&("Glow".to_string(), false)));
|
||||
// The default itself is not deleted.
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter"));
|
||||
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named"));
|
||||
assert_eq!(steps(&s), before);
|
||||
// Applied again, the default is copied back, and the object that named it draws with it.
|
||||
let b = rect(&mut s, 50.0);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]}));
|
||||
assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml)));
|
||||
assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application");
|
||||
// A new filter may take a default's name the document does not hold.
|
||||
let mut s = session();
|
||||
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Invert"><feOffset dx="1"/></filter>"#}));
|
||||
assert!(defaults(&mut s).contains(&("Invert".to_string(), true)));
|
||||
// An unknown name is still refused.
|
||||
assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\""));
|
||||
}
|
||||
|
||||
/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in
|
||||
/// the same undo step; any other effect keeps its place.
|
||||
#[test]
|
||||
fn apply_with_an_index_replaces_an_applied_filter() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]}));
|
||||
let before = steps(&s);
|
||||
let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null}));
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
assert_eq!(steps(&s), before + 1, "one step");
|
||||
let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone();
|
||||
assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather"));
|
||||
assert_eq!(names(&mut s), ["Shift", "Invert"]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(names(&mut s), ["Shift"]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift");
|
||||
// Not an SVG filter, no effect there, or not an index: refused, and the default is not copied.
|
||||
let before = steps(&s);
|
||||
for (index, why) in [
|
||||
(json!(1), "applied SVG filter"),
|
||||
(json!(7), "applied SVG filter"),
|
||||
(json!("x"), "`index`"),
|
||||
(json!(-1), "`index`"),
|
||||
(json!(null), "`index`"),
|
||||
] {
|
||||
let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null}));
|
||||
assert!(e.contains(why), "{index}: {e}");
|
||||
}
|
||||
assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before));
|
||||
}
|
||||
|
||||
/// A default needs room in the document: at 64 filters applying one is refused, and a filter the
|
||||
/// document holds still applies.
|
||||
#[test]
|
||||
fn a_full_document_refuses_a_default_it_does_not_hold() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
for i in 0..64 {
|
||||
run(&mut s, "svgFilter.define", json!({"xml": format!("<filter id=\"f{i}\"><feOffset/></filter>")}));
|
||||
}
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters"));
|
||||
let edited = r#"<filter id="Glow"><feOffset dx="2"/></filter>"#;
|
||||
assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]}));
|
||||
}
|
||||
|
||||
/// A default applied in one document is written to SVG as a filter and read back from the native
|
||||
/// format with the document's copy.
|
||||
#[test]
|
||||
fn an_applied_default_survives_svg_export_and_a_native_round_trip() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]}));
|
||||
let out = svg(&mut s);
|
||||
assert!(out.contains("<feColorMatrix") && out.contains("saturate"), "{out}");
|
||||
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(back.any_node(|n| n.appearance.effects.iter().any(|e| e.id == "svg.filter")), "SVG import reads the filter back");
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let again = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
assert_eq!(again.svg_filters, doc.svg_filters);
|
||||
assert_eq!(again.svg_filters[0].name, "Grayscale");
|
||||
}
|
||||
|
||||
@@ -2265,6 +2265,36 @@ fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
|
||||
assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames() {
|
||||
for command in ["object.lock", "object.hide"] {
|
||||
for held_first in [false, true] {
|
||||
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
|
||||
let (held, other) = if held_first { (a, b) } else { (b, a) };
|
||||
let unrelated = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
let unrelated = NodeId(unrelated);
|
||||
s.execute(command, &json!({"ids": [held.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
s.select_tool("type", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
|
||||
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
|
||||
let case = format!("{command}, held first: {held_first}");
|
||||
let steps = undo_labels(&s).len();
|
||||
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
|
||||
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step");
|
||||
assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed");
|
||||
let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text());
|
||||
assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "{case}: every frame's returns go");
|
||||
assert_eq!(obj(&s, unrelated).plain_text(), "One\nTwo", "{case}: other type is as it was");
|
||||
// No return is left: another call fails and adds no undo step.
|
||||
assert!(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).is_err());
|
||||
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() {
|
||||
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
|
||||
@@ -2306,41 +2336,72 @@ fn convert_to_text_takes_the_whole_story_that_select_all_selected() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether no paragraph of type `id` is a list.
|
||||
fn no_list(s: &Session, id: NodeId) -> bool {
|
||||
let t = obj(s, id);
|
||||
(0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none())
|
||||
}
|
||||
|
||||
/// The bullets held as characters in the frames `ids`.
|
||||
fn bullet_chars(s: &Session, ids: &[NodeId]) -> usize {
|
||||
ids.iter().map(|id| obj(s, *id).plain_text().matches("\u{2022}\t").count()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() {
|
||||
// Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story.
|
||||
for named in [false, true] {
|
||||
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
|
||||
s.execute("object.lock", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0}));
|
||||
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
|
||||
// The first frame ends with a paragraph return, so the paragraph that starts the locked
|
||||
// frame takes in the first frame's empty last part and starts its text there.
|
||||
let in_a = obj(&s, a).plain_text();
|
||||
assert!(in_a.ends_with('\n'));
|
||||
let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count();
|
||||
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
|
||||
let r = s.execute("text.convertListToText", &p).unwrap();
|
||||
assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})");
|
||||
assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert");
|
||||
assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0)));
|
||||
let (ta, tb) = (obj(&s, a), obj(&s, b));
|
||||
assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted");
|
||||
let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count();
|
||||
assert_eq!(markers, own, "the locked frame's first paragraph keeps its list");
|
||||
// The converted text is longer, so the story flows on into the locked frame; its own
|
||||
// paragraphs stay a list.
|
||||
let last = tb.paragraph_count() - 2;
|
||||
assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})");
|
||||
assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n"));
|
||||
assert!(s.tool_options().get("story").is_some(), "the whole story stays selected");
|
||||
fn convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames() {
|
||||
// Over MCP without ids, as the Paragraph panel sends it with every frame of the story, and with
|
||||
// ids naming only the held frame.
|
||||
for command in ["object.lock", "object.hide"] {
|
||||
for held_first in [false, true] {
|
||||
for call in ["none", "story", "held"] {
|
||||
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
|
||||
let (held, other) = if held_first { (a, b) } else { (b, a) };
|
||||
let unrelated =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
let unrelated = NodeId(unrelated);
|
||||
s.execute("text.setFormat", &json!({"ids": [unrelated.0], "list": "bullet"})).unwrap();
|
||||
let unrelated_before = obj(&s, unrelated);
|
||||
s.execute(command, &json!({"ids": [held.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
s.select_tool("type", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
|
||||
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
|
||||
let case = format!("{command}, held first: {held_first}, ids: {call}");
|
||||
let p = match call {
|
||||
"none" => json!({}),
|
||||
"story" => json!({"ids": [a.0, b.0]}),
|
||||
_ => json!({"ids": [held.0]}),
|
||||
};
|
||||
let steps = undo_labels(&s).len();
|
||||
let r = s.execute("text.convertListToText", &p).unwrap();
|
||||
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step");
|
||||
assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed");
|
||||
assert!(no_list(&s, held), "{case}: the held frame leaves its list");
|
||||
assert_eq!(obj(&s, unrelated), unrelated_before, "{case}: other type is as it was");
|
||||
if call == "held" {
|
||||
// The other frame's paragraphs whose text starts there keep their list.
|
||||
assert!(!no_list(&s, other), "{case}: the frame not named keeps its list");
|
||||
continue;
|
||||
}
|
||||
assert!(no_list(&s, other), "{case}: the other frame leaves its list");
|
||||
assert_eq!(bullet_chars(&s, &[a, b]), 12, "{case}: each paragraph's bullet is held once as characters");
|
||||
assert!(s.tool_options().get("story").is_some(), "{case}: the whole story stays selected");
|
||||
// Nothing is a list any more: another call changes nothing and adds no undo step.
|
||||
s.execute("text.convertListToText", &p).unwrap();
|
||||
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text");
|
||||
assert!(!no_list(&s, a) && !no_list(&s, b), "{case}: undo restores the lists");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() {
|
||||
for named in [false, true] {
|
||||
fn convert_to_text_of_the_whole_story_converts_a_paragraph_that_runs_across_a_locked_frame() {
|
||||
// The paragraph that runs from the first frame into the second starts in the locked frame, or
|
||||
// ends in it.
|
||||
for (named, lock_first) in [(false, true), (true, true), (false, false), (true, false)] {
|
||||
let mut s = session();
|
||||
let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40));
|
||||
let a = NodeId(
|
||||
@@ -2354,22 +2415,23 @@ fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked
|
||||
s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap();
|
||||
let in_a = obj(&s, a).plain_text();
|
||||
assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second");
|
||||
s.execute("object.lock", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let (locked, other) = if lock_first { (a, b) } else { (b, a) };
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
s.select_tool("type", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
|
||||
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
|
||||
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
|
||||
let case = format!("ids named: {named}, first frame locked: {lock_first}");
|
||||
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
|
||||
let r = s.execute("text.convertListToText", &p).unwrap();
|
||||
assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})");
|
||||
// The two paragraphs that start in the editable frame, and the empty one that ends the story.
|
||||
assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert");
|
||||
assert_eq!(r["ids"], json!([a.0, b.0]), "{case}: both frames are changed");
|
||||
// The five paragraphs with text, and the empty one that ends the story.
|
||||
assert_eq!(r["converted"], json!(6), "{case}: every paragraph of the story converts");
|
||||
let (ta, tb) = (obj(&s, a), obj(&s, b));
|
||||
assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was");
|
||||
assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list");
|
||||
assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list");
|
||||
assert!(!tb.plain_text().starts_with('\u{2022}'));
|
||||
assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2);
|
||||
assert!(no_list(&s, a) && no_list(&s, b), "{case}: the story leaves its list");
|
||||
assert_eq!(bullet_chars(&s, &[a, b]), 5, "{case}: each paragraph's bullet is held once as characters");
|
||||
assert!(ta.plain_text().contains("\u{2022}\tGamma"), "{case}: the paragraph across the frames takes its bullet where its text starts");
|
||||
assert!(!tb.plain_text().starts_with('\u{2022}'), "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user