Merge main into fix/shape-builder-merge-off-ui-thread

This commit is contained in:
dotCooCoo
2026-10-29 03:59:34 -07:00
224 changed files with 16369 additions and 868 deletions
+29 -2
View File
@@ -1,10 +1,11 @@
//! Blend Options (defaults with nothing selected, `object.blend.info`) and the Blend tool:
//! start points from clicked anchors, adding keys to a blend instead of nesting it (M8.18).
//! start points from clicked anchors, adding keys to a blend instead of nesting it (M8.18), and
//! Escape dropping the first pick.
use serde_json::{Value, json};
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
@@ -140,6 +141,32 @@ fn the_blend_tool_blends_from_clicked_anchors_and_keeps_adding() {
assert!(matches!(r.unwrap().as_slice(), [UiRequest::Dialog(k, _)] if k == "blendOptions"));
}
#[test]
fn escape_drops_the_blend_tools_first_pick() {
let mut s = session();
let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0));
s.select_tool("blend", ViewInfo::default()).unwrap();
let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap();
let esc = |s: &mut Session| s.tool_key(ToolKey::Escape, Mods::default(), ViewInfo::default()).unwrap();
click(&mut s, 20.0, 20.0);
assert!(s.tool_busy());
let (layers, depth) = (s.doc().unwrap().doc.layers.clone(), s.doc().unwrap().history.undo.len());
assert!(esc(&mut s).is_empty());
assert!(!s.tool_busy(), "Escape drops the pick");
assert_eq!((&s.doc().unwrap().doc.layers, s.doc().unwrap().history.undo.len()), (&layers, depth), "and changes nothing");
// The next two clicks blend b and c; a is not part of it.
click(&mut s, 220.0, 20.0);
assert_eq!(s.doc().unwrap().doc.layers, layers, "b is picked first");
click(&mut s, 420.0, 20.0);
let g = s.doc().unwrap().selection.objects[0];
assert_eq!(spec(&s, g).0, vec![b, c]);
// Escape after the blend is made: the next click starts a new blend instead of adding to it.
esc(&mut s);
click(&mut s, 20.0, 20.0);
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
assert_eq!(spec(&s, g).0, vec![b, c], "a was not added");
}
#[test]
fn start_points_round_trip_and_old_blends_load() {
let mut s = session();
+185 -5
View File
@@ -297,6 +297,85 @@ fn shape_builder_fill_option_and_untouched_shapes_kept() {
assert_eq!(outline(&node(&s, sq)).0.anchor_count(), 4);
}
fn parent(s: &Session, id: NodeId) -> Option<NodeId> {
s.doc().unwrap().doc.parent_of(id)
}
/// The merge replaces only the shapes it uses: a selected type object stays as it was.
#[test]
fn shape_builder_merge_keeps_a_selected_type_object() {
let mut s = session();
let (a, b) = two(&mut s);
let t = NodeId(s.execute("text.create", &json!({"x": 300, "y": 300, "text": "Label"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0, t.0]})).unwrap();
let before = node(&s, t);
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [125, 50]]})).unwrap();
assert_eq!(s.doc().unwrap().doc.node(t), Some(&before));
assert_eq!(layer_children(&s), 2, "the merged shape and the type");
assert!(ids(&r).contains(&t), "{r}");
}
/// A hidden member of a selected group stays hidden in its group, with the merged shape.
#[test]
fn shape_builder_merge_keeps_a_hidden_group_member() {
let mut s = session();
let (a, b) = two(&mut s);
let c = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.hide", &json!({"ids": [c.0]})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [125, 50]]})).unwrap();
let merged = NodeId(r["merged"].as_u64().unwrap());
assert_eq!((parent(&s, c), node(&s, c).visible, parent(&s, merged)), (Some(g), false, Some(g)));
assert_eq!(node(&s, g).children().unwrap().len(), 2);
}
/// A locked member of a selected group is neither cut nor moved, and does not cut the others.
#[test]
fn shape_builder_merge_leaves_a_locked_group_member() {
let mut s = session();
let (_, b) = two(&mut s);
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.lock", &json!({"ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let before = node(&s, b);
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [75, 50]]})).unwrap();
assert_eq!(s.doc().unwrap().doc.node(b), Some(&before));
assert_eq!(parent(&s, b), Some(g));
let merged = NodeId(r["merged"].as_u64().unwrap());
assert!((area(&s, merged) - 10000.0).abs() < 1.0, "A whole: {}", area(&s, merged));
}
/// In a clip group, the clipping path stays and the merged shape stays inside the group.
#[test]
fn shape_builder_merge_keeps_a_clip_groups_clipping_path() {
let mut s = session();
let (a, b) = two(&mut s);
let m = rect(&mut s, 0.0, 0.0, 120.0, 100.0);
s.execute("select.set", &json!({"ids": [a.0, b.0, m.0]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let r = s.execute("shapeBuilder.merge", &json!({"ids": [g.0], "points": [[25, 50], [125, 50]]})).unwrap();
let merged = NodeId(r["merged"].as_u64().unwrap());
let gn = node(&s, g);
let NodeKind::Group { children, clip: true } = &gn.kind else { panic!("a clip group: {:?}", gn.kind) };
assert_eq!(children.first().map(|c| c.id), Some(m), "the clipping path");
assert_eq!(parent(&s, merged), Some(g));
}
/// A group goes when deleting regions leaves it empty, and stays while anything is left in it.
#[test]
fn shape_builder_erase_removes_only_a_group_it_empties() {
let mut s = session();
two(&mut s);
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50]], "erase": true})).unwrap();
assert_eq!((ids(&r), node(&s, g).children().unwrap().len()), (vec![g], 2));
let r = s.execute("shapeBuilder.merge", &json!({"points": [[60, 50], [140, 50]], "erase": true})).unwrap();
assert!(ids(&r).is_empty() && s.doc().unwrap().doc.node(g).is_none(), "{r}");
assert_eq!(layer_children(&s), 0);
}
#[test]
fn shape_builder_miss_is_an_error_and_undo_restores() {
let mut s = session();
@@ -2615,12 +2694,45 @@ fn live_paint_bucket_tool_fills_face() {
let gn = node(&s, g);
let f = vectorcraft_tools::builder::face_at(&gn, vectorcraft_geom::Point::new(125.0, 50.0)).unwrap();
assert_eq!(f.appearance.fill_paint(), s.paint.fill);
// Live Paint Selection selects the face.
// A Live Paint Selection click selects the face.
s.select_tool("livePaintSelection", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![f.id]);
}
#[test]
fn live_paint_selection_marquee_selects_what_it_touches() {
let mut s = session();
let g = live(&mut s);
let v = ViewInfo::default();
s.select_tool("livePaintSelection", v).unwrap();
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64), m: Mods, escape: bool| {
s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1).with_mods(m), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1).with_mods(m), v).unwrap();
if escape {
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1).with_mods(m), v).unwrap();
s.doc().unwrap().selection.objects.clone()
};
let gn = node(&s, g);
let face = |x: f64| vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().id;
let edge = |x: f64| vectorcraft_tools::builder::edge_near(&gn, Point::new(x, 50.0), 0.5).unwrap().id;
let shift = Mods { shift: true, ..Default::default() };
// Across the left side: the left face and that side.
assert_eq!(drag(&mut s, (-10.0, 40.0), (40.0, 60.0), Mods::default(), false), vec![face(25.0), edge(0.0)]);
// Shift-drag across the right side adds the right face and that side.
assert_eq!(drag(&mut s, (160.0, 40.0), (140.0, 60.0), shift, false), vec![face(25.0), edge(0.0), face(125.0), edge(150.0)]);
// Shift-drag across the left side again takes those out.
assert_eq!(drag(&mut s, (-10.0, 40.0), (40.0, 60.0), shift, false), vec![face(125.0), edge(150.0)]);
// Escape during the drag, with or without Shift, from a press on a face or outside the group:
// the selection stays as it was.
for (from, m) in [((-10.0, 40.0), shift), ((25.0, 50.0), Mods::default()), ((25.0, 50.0), shift)] {
assert_eq!(drag(&mut s, from, (40.0, 60.0), m, true), vec![face(125.0), edge(150.0)], "{from:?} {m:?}");
}
}
fn line(s: &mut Session, a: (f64, f64), b: (f64, f64)) -> NodeId {
let r = s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap();
NodeId(r["id"].as_u64().unwrap())
@@ -2763,11 +2875,77 @@ fn shape_builder_keeps_the_edges_of_an_unfilled_live_paint_group() {
let c = rect(&mut s, 160.0, 20.0, 100.0, 20.0);
set_fill(&mut s, c, Color::rgb(0.0, 1.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, c.0]})).unwrap();
let before = node(&s, g);
let r = s.execute("shapeBuilder.merge", &json!({"points": [[200, 30]]})).unwrap();
let out = ids(&r);
// The merge does not use the group, so it stays as it was, with every edge: the outline of
// 0..150 × 0..100 and the edges at x = 50 and 100.
assert_eq!(s.doc().unwrap().doc.node(g), Some(&before));
assert!(ids(&r).contains(&g), "{r}");
let edges: Vec<NodeId> = vectorcraft_tools::builder::edges(&before).iter().map(|e| e.id).collect();
assert!((stroked_length(&s, &edges) - 700.0).abs() < 1.0, "{}", stroked_length(&s, &edges));
}
/// A locked face of a Live Paint group the merge replaces is not a region, and a copy of it stays,
/// still locked.
#[test]
fn shape_builder_merge_keeps_a_locked_live_paint_face() {
let mut s = session();
let g = live(&mut s);
let locked = vectorcraft_tools::builder::face_at(&node(&s, g), vectorcraft_geom::Point::new(125.0, 50.0)).unwrap().id;
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let map = s.execute("shapeBuilder.regions", &json!({})).unwrap();
assert!(map["regions"].as_array().unwrap().iter().all(|r| !r["sources"].as_array().unwrap().iter().any(|i| *i == locked.0)), "{map}");
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [75, 50]]})).unwrap();
assert_eq!(r["regions"], 2, "{r}");
assert!(s.doc().unwrap().doc.node(g).is_none());
// Every edge of the group: the outline of 0..150 × 0..100 and the edges at x = 50 and 100.
assert!((stroked_length(&s, &out) - 700.0).abs() < 1.0, "{}", stroked_length(&s, &out));
let kept: Vec<Node> = ids(&r).into_iter().map(|i| node(&s, i)).filter(|n| n.locked).collect();
assert_eq!(kept.len(), 1, "{r}");
assert!((area(&s, kept[0].id) - 5000.0).abs() < 1.0, "{}", area(&s, kept[0].id));
}
/// A hidden face of a Live Paint group the merge replaces is not a region, and a copy of it stays,
/// still hidden.
#[test]
fn shape_builder_merge_keeps_a_hidden_live_paint_face() {
let mut s = session();
let g = live(&mut s);
let hidden = vectorcraft_tools::builder::face_at(&node(&s, g), vectorcraft_geom::Point::new(125.0, 50.0)).unwrap().id;
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [75, 50]]})).unwrap();
assert_eq!(r["regions"], 2, "{r}");
assert!(s.doc().unwrap().doc.node(g).is_none());
let kept: Vec<Node> = ids(&r).into_iter().map(|i| node(&s, i)).filter(|n| !n.visible).collect();
assert_eq!(kept.len(), 1, "{r}");
assert!((area(&s, kept[0].id) - 5000.0).abs() < 1.0, "{}", area(&s, kept[0].id));
}
/// A locked face without a fill and a locked edge without a stroke, in a Live Paint group the
/// merge replaces, each keep a copy, still locked.
#[test]
fn shape_builder_merge_keeps_unpainted_locked_live_paint_members() {
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "none": true})).unwrap();
let n = node(&s, g);
let face = vectorcraft_tools::builder::face_at(&n, Point::new(125.0, 50.0)).unwrap().id;
let edge = vectorcraft_tools::builder::visible_edge_near(&n, Point::new(150.0, 50.0), 4.0).unwrap().id;
let names = (node(&s, face).name, node(&s, edge).name);
assert_ne!(names.0, names.1);
s.edit("t", |d, _| {
d.node_mut(edge).unwrap().appearance.set_stroke(Paint::None);
Ok(())
})
.unwrap();
s.execute("object.lock", &json!({"ids": [face.0, edge.0]})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [75, 50]]})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
let kept: Vec<Node> = ids(&r).into_iter().map(|i| node(&s, i)).filter(|n| n.locked).collect();
let faces = kept.iter().filter(|n| n.name == names.0 && n.appearance.fill_paint().is_none() && (area(&s, n.id) - 5000.0).abs() < 1.0).count();
let edges = kept.iter().filter(|n| n.name == names.1 && n.appearance.stroke_paint().is_none()).count();
assert_eq!((kept.len(), faces, edges), (2, 1, 1), "{r}");
}
/// A plain group whose name starts with "Live Paint" is not a Live Paint group: the Shape Builder
@@ -2791,7 +2969,9 @@ fn shape_builder_takes_the_paths_of_a_plain_group_named_live_paint() {
assert_eq!(map["regions"].as_array().unwrap().len(), 2, "{map}");
let r = s.execute("shapeBuilder.merge", &json!({"points": [[200, 30]]})).unwrap();
let out = ids(&r);
assert!(out.iter().any(|i| (area(&s, *i) - 10000.0).abs() < 1.0), "the group's rectangle is kept: {r}");
// The merge keeps the unused group whole, so its rectangle is inside an id of the reply.
let kept_area = |n: &Node| n.children().map_or_else(|| area(&s, n.id), |c| c.iter().map(|c| area(&s, c.id)).sum());
assert!(out.iter().any(|i| (kept_area(&node(&s, *i)) - 10000.0).abs() < 1.0), "the group's rectangle is kept: {r}");
// A stroke of the group's rectangle splits as a plain path's does.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+109
View File
@@ -154,6 +154,115 @@ fn images_bend_as_a_raster_mesh_warp() {
assert_eq!(svg.matches("<image").count(), 1, "the pieces share the image's pixels");
}
/// A selected embedded 2×2 image, 80×80 pt at (100, 100): a red column left of a blue one.
fn two_color_image(s: &mut Session) -> NodeId {
let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) });
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.edit("Place", |d, sel| {
d.images.insert("two".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
let xf = Affine::translate((100.0, 100.0)) * Affine::scale(40.0);
let im = vectorcraft_doc::ImageObject { key: "two".into(), width: 2, height: 2, xf, link: None, placement: Default::default(), pixels: None };
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap()
}
/// The pixels well inside the image's frame (the clip edges left out) that are a mix of its red
/// and blue rather than one of them.
fn mixed_pixels(s: &Session) -> usize {
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(110.0, 110.0, 170.0, 170.0), 2.0, true);
let mut mixed = 0;
for y in 0..img.height {
for x in 0..img.width {
let p = img.pixel(x, y);
mixed += (p[0] > 40 && p[2] > 40) as usize;
}
}
mixed
}
#[test]
fn anti_alias_off_draws_distorted_images_without_smoothing() {
let mut s = session();
let im = two_color_image(&mut s);
sel(&mut s, &[im]);
let e = arch(&mut s, 2.0, json!({}));
let smooth = mixed_pixels(&s);
assert!(smooth > 400, "with Anti-Alias on the colors blend where the pixels meet: {smooth}");
s.execute("object.envelope.options", &json!({"antiAlias": false})).unwrap();
let mut pieces = 0;
for n in evaluated(&s, e) {
n.walk(&mut |c| pieces += (matches!(c.kind, NodeKind::Image(_)) && c.extras().pixelated) as usize);
}
assert!(pieces >= 32, "{pieces} pixelated pieces");
let hard = mixed_pixels(&s);
assert!(hard * 50 < smooth, "with Anti-Alias off each pixel is red or blue: {hard} mixed of {smooth}");
// The SVG asks viewers not to smooth the pieces either.
let svg = |s: &mut Session| {
let b64 = s.execute("document.export", &json!({"format": "svg"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
String::from_utf8(vectorcraft_format::base64_decode(&b64).unwrap()).unwrap()
};
assert!(svg(&mut s).matches("image-rendering").count() >= 32);
s.execute("object.envelope.options", &json!({"antiAlias": true})).unwrap();
assert!(!svg(&mut s).contains("image-rendering"));
s.execute("object.envelope.options", &json!({"antiAlias": false})).unwrap();
// Expanded, the pieces keep it through a native save.
s.execute("object.envelope.expand", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap();
let mut kept = 0;
back.walk(|c| kept += (matches!(c.kind, NodeKind::Image(_)) && c.extras().pixelated) as usize);
assert_eq!(kept, pieces);
}
fn clip_groups_in(nodes: &[Node]) -> usize {
let mut n = 0;
for c in nodes {
c.walk(&mut |c| n += matches!(c.kind, NodeKind::Group { clip: true, .. }) as usize);
}
n
}
#[test]
fn transparency_masks_distorted_images_instead_of_clipping_them() {
let mut s = session();
let im = red_image(&mut s);
sel(&mut s, &[im]);
let e = arch(&mut s, 80.0, json!({}));
let region = Rect::new(80.0, 60.0, 160.0, 160.0);
let clipped = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, region, 2.0, true);
assert!(clip_groups_in(&evaluated(&s, e)) >= 32);
s.execute("object.envelope.options", &json!({"preserveShape": "transparency"})).unwrap();
let out = evaluated(&s, e);
assert_eq!(clip_groups_in(&out), 0, "no clipping masks");
let (mut images, mut masked) = (0, 0);
for n in &out {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Image(_)) {
images += 1;
masked += c.extras().mask.as_ref().is_some_and(|m| m.clip && !m.invert) as usize;
}
});
}
assert!(images >= 32 && masked == images, "{masked} of {images} pieces masked");
// It draws as the clipping masks did.
let alpha = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, region, 2.0, true);
let (mut sum, mut n) = (0u64, 0u64);
for y in 0..clipped.height {
for x in 0..clipped.width {
let (a, b) = (clipped.pixel(x, y), alpha.pixel(x, y));
sum += (0..4).map(|i| (a[i] as i32 - b[i] as i32).unsigned_abs() as u64).sum::<u64>();
n += 4;
}
}
assert!(sum < n, "mean difference {} per channel", sum as f64 / n as f64);
assert!(alpha.pixel(80, 74)[0] > 200 && alpha.pixel(80, 74)[1] < 60, "the bent image shows: {:?}", alpha.pixel(80, 74));
}
#[test]
fn symbols_bend_with_the_envelope() {
let mut s = session();
+106
View File
@@ -492,6 +492,112 @@ fn lock_and_hide_with_nothing_to_lock_or_hide_record_no_undo_step() {
}
}
/// Hide › Unselected Artwork hides, in one undo step, each object that is not selected and holds no selected object:
/// here `b`, the member `n` of the group that holds the selected `m`, and `p` on another layer. The selected objects,
/// that group, the clip group that holds the selected `c2` with all its members, a locked object, the art on a locked
/// layer and an object hidden before stay as they are, and so does the selection. Show All shows them again.
#[test]
fn hide_unselected_artwork_hides_every_object_that_is_not_selected() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let m = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let n = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[m, n]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let c1 = rect(&mut s, 80.0, 0.0, 10.0, 10.0);
let c2 = rect(&mut s, 85.0, 5.0, 10.0, 10.0);
let c3 = rect(&mut s, 80.0, 0.0, 30.0, 30.0);
sel(&mut s, &[c1, c2, c3]);
let clip = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
let k = rect(&mut s, 120.0, 0.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": k.0, "locked": true})).unwrap();
let h = rect(&mut s, 140.0, 0.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": h.0, "visible": false})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
let p = rect(&mut s, 0.0, 100.0, 10.0, 10.0);
let locked_layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let q = rect(&mut s, 20.0, 100.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": locked_layer.0, "locked": true})).unwrap();
let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::<Vec<_>>();
sel(&mut s, &[a, m, c2]);
let steps = undo_len(&s);
assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 3}));
assert_eq!(shown(&s, &[b, n, p, h]), [false; 4]);
assert_eq!(shown(&s, &[a, m, g, c1, c2, c3, clip, k, q]), [true; 9]);
assert!(node(&s, k).locked);
assert_eq!((undo_len(&s), selected(&s)), (steps + 1, vec![a, m, c2]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shown(&s, &[b, n, p]), [true; 3]);
s.execute("edit.redo", &json!({})).unwrap();
s.execute("object.showAll", &json!({})).unwrap();
assert_eq!(shown(&s, &[b, n, p, h]), [true; 4]);
}
/// Hide › Unselected Artwork leaves the art on a locked artboard as it is, as Select All leaves it unselected.
#[test]
fn hide_unselected_artwork_leaves_the_art_on_a_locked_artboard() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0));
let on_locked = rect(&mut s, 2050.0, 50.0, 10.0, 10.0);
s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 400, "height": 400})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
sel(&mut s, &[a]);
assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 1}));
assert_eq!([a, b, on_locked].map(|id| node(&s, id).visible), [true, false, true]);
}
/// In isolation mode Hide › Unselected Artwork is disabled: the menu item is off, and the command returns an error that
/// names isolation mode and changes nothing. While Lock Guides is on it leaves the guides as they are. With nothing
/// left to hide it records no undo step and returns a count of 0. A compound path that holds a selected path stays as
/// it is.
#[test]
fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode() {
let mut s = session();
let guide = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[guide]);
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
let out = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let m = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let n = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[m, n]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let hide = |s: &mut Session| s.execute("object.hide.unselected", &json!({})).unwrap();
let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::<Vec<_>>();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
select_with_a_step_to_redo(&mut s, &[m]);
let before = history(&s);
let info = find_command("object.hide.unselected").unwrap().info(&s);
assert!(!info.enabled && info.disabled_reason.as_deref() == Some("exit isolation mode first"), "{info:?}");
let e = s.execute("object.hide.unselected", &json!({})).unwrap_err();
assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("isolation mode"), "{e}");
assert_eq!(shown(&s, &[m, n, out, guide]), [true; 4]);
assert_eq!((history(&s), selected(&s)), (before, vec![m]));
s.execute("object.exitIsolation", &json!({})).unwrap();
sel(&mut s, &[m]);
assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled);
assert_eq!(hide(&mut s), json!({"count": 2}));
assert_eq!(shown(&s, &[n, out, guide]), [false, false, true]);
select_with_a_step_to_redo(&mut s, &[m]);
let before = history(&s);
assert_eq!(hide(&mut s), json!({"count": 0}));
assert_eq!(history(&s), before);
// With Lock Guides off, the guide path is hidden like other art.
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
sel(&mut s, &[m]);
assert_eq!(hide(&mut s), json!({"count": 1}));
assert_eq!(shown(&s, &[guide]), [false]);
// A compound path that holds the selected path stays as it is with its paths.
let outer = rect(&mut s, 0.0, 200.0, 100.0, 100.0);
let hole = rect(&mut s, 40.0, 240.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
sel(&mut s, &[hole]);
assert_eq!(hide(&mut s), json!({"count": 1}));
assert_eq!(shown(&s, &[g, c, outer, hole]), [false, true, true, true]);
}
// ---------- Transform Each ----------
#[test]
+99 -1
View File
@@ -1,6 +1,7 @@
//! Opacity-mask editing and the Transparency panel's command reach (M3.25): commands act on the
//! masked object while its mask is edited, accept ids without a selection, take opacity in percent,
//! report mixed values, and saves and exports never carry the editing layer.
//! report mixed values, and saves and exports never carry the editing layer. Mask editing is not
//! entered in isolation mode, and isolation mode is not entered while a mask is edited.
use serde_json::{Value, json};
use vectorcraft_geom::Affine;
@@ -228,6 +229,103 @@ fn one_object_gets_an_empty_mask_drawn_in_editing_mode() {
assert_eq!((s.doc().unwrap().isolation, s.doc().unwrap().active_layer), (Some(layer), Some(layer)));
}
/// The command `cmd` with `p` is off, for `why`.
fn off(s: &mut Session, cmd: &str, p: Value, why: &str) {
let err = s.execute(cmd, &p).unwrap_err();
assert!(matches!(&err, EngineError::Disabled(id, w) if id == cmd && w == why), "{cmd} {p}: {err}");
}
/// Isolation mode is not entered while an opacity mask is edited: Enter Isolation Mode is off for
/// a group in the mask art and for one outside it, and mask editing goes on. After Stop Editing
/// Opacity Mask it isolates again.
#[test]
fn isolation_mode_is_not_entered_while_an_opacity_mask_is_edited() {
let mut s = session();
let group = |s: &mut Session, x: f64| {
let (a, b) = (rect(s, x, 20.0), rect(s, x + 30.0, 20.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
};
let outside = group(&mut s, 220.0);
editing_mask(&mut s);
let layer = s.doc().unwrap().isolation;
let inside = group(&mut s, 0.0);
for id in [inside, outside] {
off(&mut s, "object.isolate", json!({"id": id.0}), "stop editing the opacity mask first");
assert_eq!(s.doc().unwrap().isolation, layer);
assert!(doc(&s).mask_edit.is_some(), "still editing");
}
s.execute("select.set", &json!({"ids": [inside.0]})).unwrap();
off(&mut s, "object.isolate", json!({}), "stop editing the opacity mask first");
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
s.execute("object.isolate", &json!({"id": outside.0})).unwrap();
assert_eq!(s.doc().unwrap().isolation, Some(outside));
}
/// Opacity mask editing is not entered in isolation mode: Edit Opacity Mask and View Opacity Mask
/// are off, and so is Make Opacity Mask for one object, which would edit its new empty mask. Make
/// Opacity Mask with two objects still masks one with the other. After Exit Isolation Mode the mask
/// is edited again.
#[test]
fn opacity_mask_editing_is_not_entered_in_isolation_mode() {
let mut s = session();
let (obj, m) = (rect(&mut s, 0.0, 200.0), rect(&mut s, 0.0, 100.0));
s.execute("transparency.makeOpacityMask", &json!({"ids": [obj.0, m.0]})).unwrap();
let other = rect(&mut s, 220.0, 30.0);
s.execute("select.set", &json!({"ids": [obj.0, other.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("select.set", &json!({"ids": [obj.0]})).unwrap();
let why = "exit isolation mode first";
off(&mut s, "transparency.editOpacityMask", json!({}), why);
off(&mut s, "transparency.editOpacityMask", json!({"id": obj.0}), why);
off(&mut s, "transparency.viewOpacityMask", json!({}), why);
off(&mut s, "transparency.viewOpacityMask", json!({"on": true, "id": obj.0}), why);
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
off(&mut s, "transparency.makeOpacityMask", json!({}), why);
off(&mut s, "transparency.makeOpacityMask", json!({"ids": [other.0]}), why);
// A layer given as the one target is refused too.
let layer = doc(&s).layers[0].id;
let err = s.execute("transparency.makeOpacityMask", &json!({"ids": [layer.0]})).unwrap_err();
assert!(err.to_string().ends_with(why), "{err}");
let st = s.doc().unwrap();
assert!(st.doc.mask_edit.is_none() && st.mask_view.is_none() && mask(&s, other).is_none());
assert_eq!(s.doc().unwrap().isolation, Some(g));
// Two objects: the top one masks the other, without mask editing.
let top = rect(&mut s, 220.0, 10.0);
let r = s.execute("transparency.makeOpacityMask", &json!({"ids": [other.0, top.0]})).unwrap();
assert_eq!(r, json!({"id": other.0, "editing": false}));
assert_eq!(s.doc().unwrap().isolation, Some(g));
// Two members of a compound path given in `ids` are two objects: one masks the other.
let (c1, c2) = (rect(&mut s, 250.0, 10.0), rect(&mut s, 265.0, 10.0));
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let r = s.execute("transparency.makeOpacityMask", &json!({"ids": [c1.0, c2.0]})).unwrap();
assert_eq!(r["editing"], json!(false));
assert!(doc(&s).mask_edit.is_none());
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({"id": obj.0})).unwrap();
assert_eq!(doc(&s).mask_edit.map(|e| e.object), Some(obj));
}
/// In isolation mode, Make Opacity Mask is off for a targeted sublayer that holds two objects:
/// the sublayer is its one target, which would get an empty mask and enter mask editing.
#[test]
fn make_opacity_mask_is_off_for_a_targeted_sublayer_in_isolation_mode() {
let mut s = session();
let layer = doc(&s).layers[0].id;
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
let (a, b) = (rect(&mut s, 0.0, 20.0), rect(&mut s, 40.0, 20.0));
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
s.execute("layer.target", &json!({"id": sub.0})).unwrap();
assert_eq!(s.doc().unwrap().selection.target, Some(sub));
off(&mut s, "transparency.makeOpacityMask", json!({}), "exit isolation mode first");
// Two objects given in `ids` still mask one with the other.
let r = s.execute("transparency.makeOpacityMask", &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(r["editing"], json!(false));
}
#[test]
fn mask_and_transparency_commands_take_ids_without_a_selection() {
let mut s = session();
+17
View File
@@ -141,6 +141,23 @@ fn edit_text_shows_it_flat_in_isolation_then_projects_it_again() {
assert!(s2.execute("perspective.editText", &json!({"id": rect.0})).is_err());
}
/// Edit Text, which shows the type in isolation mode, is off while an opacity mask is edited.
#[test]
fn edit_text_is_off_while_an_opacity_mask_is_edited() {
let (mut s, rect) = persp_session();
let id = persp_text(&mut s);
s.execute("transparency.makeOpacityMask", &json!({"ids": [rect.0]})).unwrap();
let layer = s.doc().unwrap().isolation;
assert!(layer.is_some(), "editing the new empty mask");
let err = s.execute("perspective.editText", &json!({"id": id.0})).unwrap_err();
assert!(matches!(&err, EngineError::Disabled(_, why) if why == "stop editing the opacity mask first"), "{err}");
assert_eq!(s.doc().unwrap().isolation, layer);
assert!(node(&s, id).projection().is_some(), "still projected");
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
s.execute("perspective.editText", &json!({"id": id.0})).unwrap();
assert_eq!(s.doc().unwrap().isolation, Some(id));
}
/// Edit Text ending while a background save writes the file leaves the document saved once the
/// file is written: the flat view is never saved. Saved while editing and edited after: undoing
/// the edit once Edit Text has ended is back at what the file holds.
+108
View File
@@ -998,6 +998,114 @@ fn whole_objects_moved_with_selected_anchors_follow_transform_pattern_tiles() {
}
}
/// A Direct Selection or Group Selection drag that starts on the fill of a path selected whole,
/// while another path has an anchor selected, moves the path whole and only that anchor of the
/// other path, in one undo step, as a drag of the anchor does. With Transform Pattern Tiles on,
/// the tiles of the path selected whole move with it. Alt pressed during the drag copies the
/// selected objects instead.
#[test]
fn a_drag_from_a_fill_moves_only_the_selected_anchors_of_partly_selected_paths() {
use vectorcraft_tools::PointerKind::{Down, Drag, Up};
let mut s = new_doc();
let filled = patterned_square(&mut s);
let other = square(&mut s, 300.0, 100.0);
let v = ViewInfo { smart_guides: false, snap_to_point: false, corner_widgets: false, ..ViewInfo::default() };
set_pref(&mut s, "transformPatternTiles", json!(true));
let xs = |s: &Session| -> Vec<f64> {
s.doc().unwrap().doc.node(other).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p.x).collect()
};
let before = xs(&s);
for tool in ["directSelection", "groupSelection"] {
s.select_tool(tool, v).unwrap();
s.execute("select.set", &json!({"ids": [filled.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]);
assert_eq!(top_left(&s, filled), (110.0, 100.0), "{tool}: the square moves whole");
let mut moved = before.clone();
moved[0] += 10.0;
assert_eq!(xs(&s), moved, "{tool}: the selected anchor moves alone");
assert_eq!(s.journal.last().unwrap().0, "path.moveAnchors", "{tool}");
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move"), "{tool}");
assert_eq!(pattern_tiles(&s, filled), [1.0, 0.0, 0.0, 1.0, 10.0, 0.0], "{tool}: the tiles move with the square");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((top_left(&s, filled), xs(&s)), ((100.0, 100.0), before.clone()), "{tool}: one undo step");
// Alt pressed during the drag copies the selected objects and leaves the originals.
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
let objects = count(&s);
s.execute("select.set", &json!({"ids": [filled.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
let alt = vectorcraft_tools::Mods { alt: true, ..vectorcraft_tools::Mods::default() };
s.pointer(&PointerEvent::new(Down, 125.0, 125.0), v).unwrap();
s.pointer(&PointerEvent::new(Drag, 130.0, 125.0), v).unwrap();
s.pointer(&PointerEvent::new(Drag, 135.0, 125.0).with_mods(alt), v).unwrap();
s.pointer(&PointerEvent::new(Up, 135.0, 125.0).with_mods(alt), v).unwrap();
assert_eq!((top_left(&s, filled), xs(&s), count(&s)), ((100.0, 100.0), before.clone(), objects + 2), "{tool}: copied");
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Copy"), "{tool}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(count(&s), objects, "{tool}");
}
}
/// A path selected whole inside a selected group moves once, with the group, when the selection
/// also holds a direct-selected anchor: a Group Selection drag from the path's fill (which adds
/// the group) and an arrow key move both by 10 pt.
#[test]
fn a_path_in_a_selected_group_moves_once_with_selected_anchors() {
use vectorcraft_tools::PointerKind::{Down, Drag, Up};
let mut s = new_doc();
let (a, b) = (square(&mut s, 100.0, 100.0), square(&mut s, 160.0, 100.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let other = square(&mut s, 300.0, 100.0);
let v = ViewInfo { smart_guides: false, snap_to_point: false, corner_widgets: false, ..ViewInfo::default() };
let first_x = |s: &Session| s.doc().unwrap().doc.node(other).unwrap().path_data().unwrap().subpaths[0].anchors[0].p.x;
s.select_tool("groupSelection", v).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]);
assert!(s.doc().unwrap().selection.contains(g), "the press added the group");
assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (170.0, 100.0), 310.0), "the drag");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g.0, a.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "big": true})).unwrap();
assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (170.0, 100.0), 310.0), "the arrow key");
}
/// Transform Again after a Direct Selection drag from a fill with an anchor of another path
/// selected moves the path selected whole and only that anchor again, by the same distance. A
/// drag back to where it began leaves that move to repeat, and `path.moveAnchors` run as a
/// command is repeated too.
#[test]
fn transform_again_repeats_a_drag_from_a_fill_with_anchors_selected() {
use vectorcraft_tools::PointerKind::{Down, Drag, Up};
let mut s = new_doc();
let filled = square(&mut s, 100.0, 100.0);
let other = square(&mut s, 300.0, 100.0);
let v = ViewInfo { smart_guides: false, snap_to_point: false, corner_widgets: false, ..ViewInfo::default() };
let xs = |s: &Session| -> Vec<f64> {
s.doc().unwrap().doc.node(other).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p.x).collect()
};
let mut moved = xs(&s);
s.select_tool("directSelection", v).unwrap();
s.execute("select.set", &json!({"ids": [filled.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]);
s.execute("object.transformAgain", &json!({})).unwrap();
moved[0] += 20.0;
assert_eq!((top_left(&s, filled), xs(&s)), ((120.0, 100.0), moved.clone()));
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Transform Again"));
// A drag that ends where it began leaves the move to repeat.
gesture(&mut s, v, &[(Down, 145.0, 125.0), (Drag, 155.0, 125.0), (Drag, 145.0, 125.0), (Up, 145.0, 125.0)]);
s.execute("object.transformAgain", &json!({})).unwrap();
moved[0] += 10.0;
assert_eq!((top_left(&s, filled), xs(&s)), ((130.0, 100.0), moved), "after a drag back to its start");
// The command, as an action plays it back, is repeated the same way.
s.execute("path.moveAnchors", &json!({"dx": 0, "dy": 5})).unwrap();
s.execute("object.transformAgain", &json!({})).unwrap();
assert_eq!(top_left(&s, filled), (130.0, 110.0), "path.moveAnchors");
}
/// General › Select Same Tint % (#394): off, Select › Same › Fill Color takes every tint of the
/// swatch; on, only the same tint.
#[test]
+139 -1
View File
@@ -84,7 +84,7 @@ fn save_as_takes_on_path_format_and_options() {
let svg = s.execute("file.formatOptions", &json!({"format": "svg"})).unwrap();
assert_eq!(svg["options"]["outlineText"]["value"], false, "another format shows its defaults");
let ids: Vec<&str> = o["saveFormats"].as_array().unwrap().iter().map(|f| f["id"].as_str().unwrap()).collect();
assert_eq!(ids, ["vectorcraft", "template", "pdf", "svg", "svgz", "ai"]);
assert_eq!(ids, ["vectorcraft", "template", "pdf", "svg", "svgz", "ai", "eps"]);
// SVGZ is gzip-compressed SVG and reopens as SVGZ.
let svgz = path(&d, "doc.svgz");
s.execute("file.saveAs", &json!({"path": svgz})).unwrap();
@@ -405,3 +405,141 @@ fn transparency_grid_round_trips_without_dirtying() {
assert!(!s.doc().unwrap().transparency_grid);
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() {
let d = dir("eps-original-format");
let eps_path = path(&d, "Artwork.eps");
// Original, contributor-authored PostScript: the artwork occupies only part of the page.
let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n0 0 1 setrgbcolor 30 20 40 30 rectfill\nshowpage\n%%EOF\n";
std::fs::write(&eps_path, source).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"path": eps_path})).unwrap();
assert_eq!(s.doc().unwrap().format, "eps");
assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str()));
let board = s.doc().unwrap().doc.artboards[0].rect;
assert_eq!((board.width(), board.height()), (200.0, 100.0));
rect(&mut s);
let edited_layers = s.doc().unwrap().doc.layers.clone();
let r = s.execute("document.save", &json!({"options": {"previewFormat": "none", "thumbnails": false}})).unwrap();
assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(eps_path.as_str()), Some("eps")));
let bytes = std::fs::read(&eps_path).unwrap();
assert!(bytes.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0"));
assert!(std::str::from_utf8(vectorcraft_eps::sections(&bytes).unwrap().0).unwrap().contains("%%BoundingBox: 0 0 200 100"));
let editing = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(editing.artboards[0].rect, board);
assert_eq!(editing.layers, edited_layers);
assert!(!s.doc().unwrap().is_dirty());
let opened = s.execute("document.open", &json!({"path": eps_path})).unwrap();
assert_eq!(opened["restored"], true);
assert_eq!(s.doc().unwrap().doc.layers, edited_layers);
assert_eq!(s.doc().unwrap().doc.artboards[0].rect, board);
rect(&mut s);
s.execute("document.save", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str()));
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn eps_save_keeps_all_editing_artboards_while_printing_one_page() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
rect(&mut s);
let r = s.execute("document.save", &json!({"format": "eps", "artboard": 1, "previewFormat": "none", "thumbnails": false})).unwrap();
let bytes = b64(&r);
let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(native.artboards.len(), 2);
assert_eq!(native.layers, s.doc().unwrap().doc.layers);
assert!(s.execute("document.save", &json!({"format": "eps", "range": "all"})).is_err(), "EPS is one printed page");
for options in [json!({"useArtboards": false}), json!({"selectedOnly": true})] {
assert!(s.execute("document.save", &json!({"format": "eps", "options": options})).is_err(), "cropping is Export's job");
}
}
#[test]
fn eps_save_retains_lossy_import_overwrite_protection_and_transparency_warning() {
let d = dir("eps-import-warning");
let eps_path = path(&d, "Artwork.eps");
let mut s = session();
rect(&mut s);
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let r = s.execute("document.save", &json!({"path": eps_path, "previewFormat": "none", "thumbnails": false})).unwrap();
assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("flatten")), "{r}");
let original = std::fs::read(&eps_path).unwrap();
let st = s.doc_mut().unwrap();
st.imported_from = Some(eps_path.clone());
st.import_losses.push("test import omitted artwork".into());
rect(&mut s);
assert!(s.execute("document.save", &json!({})).unwrap_err().to_string().contains("acknowledgeLoss"));
assert_eq!(std::fs::read(&eps_path).unwrap(), original);
s.execute("document.save", &json!({"acknowledgeLoss": true})).unwrap();
assert_ne!(std::fs::read(&eps_path).unwrap(), original);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn eps_save_supports_an_empty_artboard_without_cropping_its_page() {
let mut s = session();
let r = s.execute("document.save", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap();
let bytes = b64(&r);
let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(native.artboards[0].rect, s.doc().unwrap().doc.artboards[0].rect);
assert_eq!(native.node_count(), s.doc().unwrap().doc.node_count());
assert!(std::str::from_utf8(vectorcraft_eps::sections(&bytes).unwrap().0).unwrap().contains("%%BoundingBox: 0 0 200 100"));
}
#[test]
fn partially_read_eps_requires_confirmation_before_save_back() {
let d = dir("eps-partial-import");
let eps_path = path(&d, "partial.eps");
let original = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n0 0 1 setrgbcolor 30 20 40 30 rectfill\nunsupportedMockyOperator\n1 0 0 setrgbcolor 80 20 40 30 rectfill\nshowpage\n%%EOF\n";
std::fs::write(&eps_path, original).unwrap();
let mut s = Session::new();
let opened = s.execute("document.open", &json!({"path": eps_path})).unwrap();
assert!(opened["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with("the file was read up to an error")), "{opened}");
rect(&mut s);
assert!(s.execute("document.save", &json!({})).unwrap_err().to_string().contains("acknowledgeLoss"));
assert_eq!(std::fs::read(&eps_path).unwrap(), original);
s.execute("document.save", &json!({"acknowledgeLoss": true})).unwrap();
assert!(vectorcraft_eps::native(&std::fs::read(&eps_path).unwrap()).is_some());
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn eps_with_damaged_editing_data_requires_confirmation_before_save_back() {
let d = dir("eps-damaged-editing");
let eps_path = path(&d, "damaged.eps");
let mut s = session();
rect(&mut s);
let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "thumbnails": false, "cmykPostScript": false})).unwrap();
let mut bytes = b64(&r);
let at = bytes.windows(9).position(|w| w == b"native\n% ").unwrap() + 12;
bytes[at] = b'z';
std::fs::write(&eps_path, &bytes).unwrap();
let opened = s.execute("document.open", &json!({"path": eps_path})).unwrap();
assert_eq!(opened["restored"], false);
assert!(opened["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("editing data can't be read")), "{opened}");
rect(&mut s);
assert!(s.execute("document.save", &json!({})).unwrap_err().to_string().contains("acknowledgeLoss"));
assert_eq!(std::fs::read(&eps_path).unwrap(), bytes);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 4000, "height": 4000})).unwrap();
rect(&mut s);
// Explicit colour preview remains a colour preview; Save bounds its resolution, not the art.
let r = s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap();
let bytes = b64(&r);
let (ps, tiff) = vectorcraft_eps::sections(&bytes).unwrap();
let tiff = tiff.unwrap();
assert!(tiff.len() < 4 * 1024 * 1024 + 64 * 1024, "compatibility preview grew to {} bytes", tiff.len());
let preview = image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap();
assert_eq!((preview.width(), preview.height()), (1024, 1024));
assert!(std::str::from_utf8(ps).unwrap().contains("%%BoundingBox: 0 0 4000 4000"));
let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(native.artboards, s.doc().unwrap().doc.artboards);
assert_eq!(native.layers, s.doc().unwrap().doc.layers);
}
+203
View File
@@ -356,6 +356,50 @@ fn shaper_isolate_refuses_a_locked_or_hidden_source_group() {
}
}
/// While an opacity mask or a pattern is edited, its editing layer stays isolated: a Shaper source
/// pick selects the original shape without isolating it, and a scribble, Release and Expand keep the
/// layer isolated. Leaving the mode then ends isolation.
#[test]
fn shaper_keeps_the_mask_and_pattern_editing_layers_isolated() {
for mode in ["mask", "pattern"] {
let mut s = session();
let object = rectangle(&mut s, 300.0, "#000000");
let layer = if mode == "mask" {
let m = rectangle(&mut s, 300.0, "#ffffff");
s.execute("select.set", &json!({"ids": [object.0, m.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap()["layer"].as_u64().map(NodeId)
} else {
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
s.doc().unwrap().doc.pattern_edit.as_ref().map(|e| e.layer)
};
let isolation = |s: &Session| s.doc().unwrap().isolation;
assert!(layer.is_some() && isolation(&s) == layer, "{mode}");
let a = rectangle(&mut s, 0.0, "#ff0000");
let b = rectangle(&mut s, 50.0, "#0000ff");
let make = |s: &mut Session| {
let pts = [[25, 20], [75, 35], [30, 50], [125, 65]];
NodeId(s.execute("shaper.scribble", &json!({"points": pts, "ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap())
};
let g = make(&mut s);
assert_eq!(s.doc().unwrap().doc.parent_of(g), layer, "{mode}");
assert_eq!(isolation(&s), layer, "{mode}: scribble");
let picked = s.execute("shaper.select", &json!({"point": [25, 50], "source": true})).unwrap();
assert_eq!(picked["id"], json!(a.0), "{mode}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{mode}");
assert_eq!(isolation(&s), layer, "{mode}: source pick");
s.execute("shaper.release", &json!({"id": g.0})).unwrap();
assert_eq!(isolation(&s), layer, "{mode}: release");
let g = make(&mut s);
s.execute("shaper.expand", &json!({"id": g.0})).unwrap();
assert_eq!(isolation(&s), layer, "{mode}: expand");
let leave = if mode == "mask" { "transparency.stopEditingOpacityMask" } else { "object.pattern.done" };
s.execute(leave, &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(st.doc.mask_edit.is_none() && st.doc.pattern_edit.is_none() && st.isolation.is_none(), "{mode}");
}
}
#[test]
fn shaper_lines_keep_free_angles_with_or_without_shift() {
for shift in [false, true] {
@@ -567,3 +611,162 @@ fn shaper_joined_outline_keeps_its_stroke_paint_after_source_edits() {
assert_ne!(node(&s, id).appearance.stroke_paint().label(), "#00ff00");
}
}
fn source_ids(s: &Session, g: NodeId) -> Vec<NodeId> {
node(s, g).children().unwrap()[0].children().unwrap().iter().map(|n| n.id).collect()
}
/// A Selection-tool drag from `from` to `to`.
fn drag(s: &mut Session, v: ViewInfo, from: [f64; 2], to: [f64; 2]) {
s.pointer(&PointerEvent::new(PointerKind::Down, from[0], from[1]), v).unwrap();
for t in [0.25, 0.5, 1.0] {
let p = [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t];
s.pointer(&PointerEvent::new(PointerKind::Drag, p[0], p[1]), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, to[0], to[1]), v).unwrap();
}
/// Two overlapping rectangles in a Shaper Group, in Construction mode with the left one selected
/// and the Selection tool chosen → (left, right, group).
fn construction(s: &mut Session, v: ViewInfo) -> (NodeId, NodeId, NodeId) {
let a = rectangle(s, 0.0, "#ff0000");
let b = rectangle(s, 50.0, "#0000ff");
let g = scribble(s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.select_tool("selection", v).unwrap();
(a, b, g)
}
/// In Construction mode, a Selection-tool drag that drops an original shape wholly outside the
/// bounds of the group's original shapes takes it out of the group, in one undo step: it becomes a
/// path just above the group with its own look, and stays selected. Undo puts it back. With
/// Real-time Drawing off the drop does the same.
#[test]
fn shaper_dragging_an_original_shape_out_of_the_bounds_takes_it_out_of_the_group() {
for real_time in [true, false] {
let mut s = session();
s.prefs.real_time_drawing = real_time;
let v = ViewInfo { smart_guides: false, ..Default::default() };
let (a, b, g) = construction(&mut s, v);
let look = node(&s, a).appearance.clone();
let steps = s.doc().unwrap().history.undo.len();
drag(&mut s, v, [25.0, 50.0], [25.0, 200.0]);
let st = s.doc().unwrap();
assert_eq!(source_ids(&s, g), vec![b], "real-time {real_time}");
let (parent, index, _) = st.doc.position(a).unwrap();
assert_eq!((parent, index), { st.doc.position(g).map(|(p, i, _)| (p, i + 1)).unwrap() });
assert_eq!(node(&s, a).appearance, look);
assert_eq!(node(&s, a).geometric_bounds().unwrap().y0, 150.0);
assert_eq!(st.selection.objects, vec![a]);
assert_eq!(st.isolation, None);
assert_eq!(st.history.undo.len(), steps + 1);
assert_eq!(st.history.undo.last().unwrap().label, "Remove from Shaper Group");
// The group's result is the right rectangle alone.
assert_eq!(fill(&s, g, 25.0, 50.0), None);
assert_eq!(fill(&s, g, 125.0, 50.0).as_deref(), Some("#0000ff"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(source_ids(&s, g), vec![a, b]);
assert_eq!(node(&s, a).geometric_bounds().unwrap().y0, 0.0);
assert_eq!(fill(&s, g, 25.0, 50.0).as_deref(), Some("#ff0000"));
}
}
/// A drop that leaves the original shape across the bounds of the group's original shapes only
/// moves it, as before.
#[test]
fn shaper_dragging_an_original_shape_across_the_bounds_only_moves_it() {
let mut s = session();
let v = ViewInfo { smart_guides: false, ..Default::default() };
let (a, b, g) = construction(&mut s, v);
let sources = node(&s, g).children().unwrap()[0].id;
drag(&mut s, v, [25.0, 50.0], [25.0, 100.0]);
let st = s.doc().unwrap();
assert_eq!(source_ids(&s, g), vec![a, b]);
assert_eq!(node(&s, a).geometric_bounds().unwrap().y0, 50.0);
assert_eq!(st.isolation, Some(sources));
assert_eq!(st.history.undo.last().unwrap().label, "Move");
// Outside Construction mode the same drop moves the group as usual.
s.execute("object.exitIsolation", &json!({})).unwrap();
drag(&mut s, v, [25.0, 100.0], [25.0, 400.0]);
assert_eq!(source_ids(&s, g), vec![a, b]);
}
/// Taking the last original shape out removes the group, and the native file keeps the result.
#[test]
fn shaper_taking_the_last_original_shape_out_removes_the_group_and_saves() {
let mut s = session();
let v = ViewInfo { smart_guides: false, ..Default::default() };
let (a, b, g) = construction(&mut s, v);
drag(&mut s, v, [25.0, 50.0], [25.0, 200.0]);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
drag(&mut s, v, [125.0, 50.0], [400.0, 50.0]);
let doc = &s.doc().unwrap().doc;
assert!(doc.node(g).is_none());
assert_eq!(doc.parent_of(a), doc.parent_of(b));
assert_eq!(node(&s, b).geometric_bounds().unwrap().x0, 325.0);
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
assert_eq!(back.layers, doc.layers);
}
/// Flat bounds of horizontal or vertical lines on the line of a group's flat bounds, and bounds that
/// touch the group's bounds, are not outside them.
#[test]
fn shaper_outside_test_handles_flat_and_touching_bounds() {
use crate::cmd::shaper::wholly_outside;
use vectorcraft_geom::Rect;
let row = Rect::new(0.0, 150.0, 200.0, 150.0);
assert!(!wholly_outside(Rect::new(50.0, 150.0, 120.0, 150.0), row));
assert!(!wholly_outside(Rect::new(150.0, 150.0, 300.0, 150.0), row));
assert!(wholly_outside(Rect::new(250.0, 150.0, 300.0, 150.0), row));
assert!(wholly_outside(Rect::new(50.0, 160.0, 120.0, 160.0), row));
let column = Rect::new(80.0, 0.0, 80.0, 100.0);
assert!(!wholly_outside(Rect::new(80.0, 50.0, 80.0, 150.0), column));
assert!(wholly_outside(Rect::new(90.0, 50.0, 90.0, 150.0), column));
let square = Rect::new(0.0, 0.0, 100.0, 100.0);
assert!(!wholly_outside(Rect::new(100.0, 0.0, 200.0, 100.0), square));
assert!(wholly_outside(Rect::new(100.5, 0.0, 200.0, 100.0), square));
}
/// `shaper.releaseSource` takes the named original shape out, refuses a shape of another group or
/// none, and `object.transform`'s `releaseOutside` makes one undo step outside a drag too.
#[test]
fn shaper_release_source_command_and_transform_flag() {
let mut s = session();
let a = rectangle(&mut s, 0.0, "#ff0000");
let b = rectangle(&mut s, 50.0, "#0000ff");
let g = scribble(&mut s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]);
let other = rectangle(&mut s, 300.0, "#00ff00");
let untouched = s.doc().unwrap().doc.layers.clone();
for p in [json!({"source": other.0}), json!({"source": a.0, "group": other.0}), json!({"source": "x"}), json!({})] {
assert!(s.execute("shaper.releaseSource", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().doc.layers, untouched);
}
s.execute("shaper.releaseSource", &json!({"source": b.0, "group": g.0})).unwrap();
assert_eq!(source_ids(&s, g), vec![a]);
assert_eq!(s.doc().unwrap().selection.objects, vec![b]);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Remove from Shaper Group");
s.execute("edit.undo", &json!({})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 150], "ids": [a.0], "releaseOutside": true})).unwrap();
assert_eq!(source_ids(&s, g), vec![b]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Remove from Shaper Group");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(source_ids(&s, g), vec![a, b]);
assert_eq!(node(&s, a).geometric_bounds().unwrap().y0, 0.0);
// With a history of one step, that step still goes back to before the move.
s.doc_mut().unwrap().history.limit = 1;
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 150], "ids": [a.0], "releaseOutside": true})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(source_ids(&s, g), vec![a, b]);
assert_eq!(node(&s, a).geometric_bounds().unwrap().y0, 0.0);
// Shapes taken out together keep their stacking order, whatever order they are named in.
for ids in [[a.0, b.0], [b.0, a.0]] {
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 150], "ids": ids, "releaseOutside": true})).unwrap();
let doc = &s.doc().unwrap().doc;
assert!(doc.node(g).is_none());
assert!(doc.position(a).unwrap().1 < doc.position(b).unwrap().1, "{ids:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(source_ids(&s, g), vec![a, b]);
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Object › Path › Smooth (`object.path.smooth`): the slider from minimum to maximum smoothing and
//! Auto-Smooth, as the Smooth slider help page describes
//! (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html).
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_geom::kurbo::ParamCurveNearest;
use vectorcraft_geom::{ParamCurve, PathData, Point};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn path_of(s: &Session, id: NodeId) -> PathData {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { path, .. } => path.clone(),
_ => panic!("not a path"),
}
}
/// A path through `points`, selected: its id.
fn polyline(s: &mut Session, points: &[(f64, f64)], closed: bool) -> NodeId {
let anchors: Vec<Value> = points.iter().map(|&(x, y)| json!({"x": x, "y": y})).collect();
NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap())
}
/// A sine wave 300 pt long with an anchor every 3 pt, its anchors 1.5 pt above and below it in turn.
fn jagged_wave(s: &mut Session) -> NodeId {
let pts: Vec<(f64, f64)> = (0..=100u32)
.map(|i| (f64::from(i) * 3.0, 200.0 + 40.0 * (f64::from(i) * 3.0 / 50.0).sin() + if i.is_multiple_of(2) { 1.5 } else { -1.5 }))
.collect();
polyline(s, &pts, false)
}
/// A closed ring of radius `r` around (`cx`, 300) with 120 anchors, `jag` pt in and out in turn.
fn jagged_ring(s: &mut Session, cx: f64, r: f64, jag: f64) -> NodeId {
let pts: Vec<(f64, f64)> = (0..120u32)
.map(|i| {
let a = f64::from(i) * std::f64::consts::TAU / 120.0;
let rr = r + if i.is_multiple_of(2) { jag } else { -jag };
(cx + rr * a.cos(), 300.0 + rr * a.sin())
})
.collect();
polyline(s, &pts, true)
}
/// The farthest that 11 points on each segment of `from` lie from the nearest point of `to`.
fn farthest(from: &PathData, to: &PathData) -> f64 {
let off = |p: Point| {
to.subpaths
.iter()
.flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i).nearest(p, 1e-9).distance_sq.sqrt()))
.fold(f64::INFINITY, f64::min)
};
from.subpaths
.iter()
.flat_map(|sp| (0..sp.segment_count()).flat_map(move |i| (0..=10).map(move |k| sp.segment(i).eval(f64::from(k) / 10.0))))
.map(off)
.fold(0.0, f64::max)
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn minimum_smoothing_leaves_the_path_where_it_was() {
let mut s = session();
let id = jagged_wave(&mut s);
let before = path_of(&s, id);
let out = s.execute("object.path.smooth", &json!({"level": 0})).unwrap();
assert_eq!(out["level"], json!(0.0));
let after = path_of(&s, id);
// 0.1 % of the longer side (300 pt), both ways.
assert!(farthest(&before, &after) <= 0.3 + 1e-6 && farthest(&after, &before) <= 0.3 + 1e-6);
}
#[test]
fn more_smoothing_removes_the_jags_and_keeps_the_shape() {
let mut s = session();
let id = jagged_wave(&mut s);
let before = path_of(&s, id);
let mut counts = vec![];
for level in [25, 50, 100] {
let out = s.execute("object.path.smooth", &json!({ "level": level })).unwrap();
let after = path_of(&s, id);
assert_eq!(out["after"].as_u64().unwrap() as usize, after.anchor_count());
counts.push(after.anchor_count());
// Within the tolerance (2.5 % of 300 pt at most) plus the jag the refit smooths away.
assert!(farthest(&before, &after) <= 7.5 + 1.5, "level {level}: {}", farthest(&before, &after));
// The end points of an open path stay put.
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
assert_eq!((a[0].p, a[a.len() - 1].p), (b[0].p, b[b.len() - 1].p));
assert!(!after.subpaths[0].closed);
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(counts[0] < 101 / 2 && counts[2] <= 10, "{counts:?}");
assert!(counts.windows(2).all(|w| w[0] >= w[1]), "{counts:?}");
}
#[test]
fn auto_smooth_uses_the_middle_level() {
let mut s = session();
let id = jagged_wave(&mut s);
let out = s.execute("object.path.smooth", &json!({"auto": true, "level": 0})).unwrap();
assert_eq!(out["level"], json!(50.0));
let auto = path_of(&s, id);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.path.smooth", &json!({"level": 50})).unwrap();
assert_eq!(path_of(&s, id), auto);
}
#[test]
fn closed_paths_and_compound_path_members_smooth_in_one_undo_step() {
let mut s = session();
let outer = jagged_ring(&mut s, 300.0, 100.0, 2.0);
let inner = jagged_ring(&mut s, 300.0, 40.0, 1.0);
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let (o, i) = (path_of(&s, outer), path_of(&s, inner));
let steps = undo_len(&s);
let out = s.execute("object.path.smooth", &json!({"level": 100})).unwrap();
assert_eq!(out["ids"].as_array().unwrap().len(), 2);
assert_eq!(undo_len(&s), steps + 1);
for id in [outer, inner] {
let now = path_of(&s, id);
assert!(now.subpaths[0].closed);
assert!(now.anchor_count() < 120 / 4, "{}", now.anchor_count());
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((path_of(&s, outer), path_of(&s, inner)), (o, i));
}
#[test]
fn smooths_the_objects_given() {
let mut s = session();
let a = jagged_wave(&mut s);
let b = jagged_ring(&mut s, 300.0, 50.0, 1.0);
let ring = path_of(&s, b);
// `b` is selected; `ids` names `a` instead.
let out = s.execute("object.path.smooth", &json!({"ids": [a.0], "level": 100})).unwrap();
assert_eq!(out["ids"], json!([a.0]));
assert_eq!(path_of(&s, b), ring);
}
#[test]
fn bad_params_are_refused_and_change_nothing() {
let mut s = session();
let id = jagged_wave(&mut s);
let before = path_of(&s, id);
let steps = undo_len(&s);
for p in [json!({"level": "50"}), json!({"auto": true, "level": "max"}), json!({"auto": "yes"}), json!({"ids": "all"}), json!({"ids": [999_999]})]
{
assert!(s.execute("object.path.smooth", &p).is_err(), "{p}");
}
assert_eq!((path_of(&s, id), undo_len(&s)), (before, steps));
// Levels past the ends count as the ends.
assert_eq!(s.execute("object.path.smooth", &json!({"level": 250})).unwrap()["level"], json!(100.0));
}
+345
View File
@@ -47,6 +47,151 @@ fn document_color_mode_converts_grouped_swatches() {
assert!(matches!(doc(&s).swatch("Bright Red").unwrap().paint.color(), Some(Color::Cmyk { .. })));
}
/// The first solid fill color in the subtree of `n`.
fn first_fill(n: &vectorcraft_doc::Node) -> Color {
let mut out = None;
n.walk(&mut |m| {
if out.is_none() {
out = m.appearance.fill_paint().color();
}
});
out.unwrap_or_else(|| panic!("no fill in {n:?}"))
}
/// The fill of graph design "Bar", the fill of brush "Holder"'s art and its Hue Shift key color,
/// the fill of graphic style "Red" and the fill of the art of `masked`'s opacity mask.
fn colors_outside_the_layers(s: &Session, masked: NodeId) -> Vec<Color> {
let d = doc(s);
let brush = vectorcraft_brush::find(d, "Holder").unwrap();
let vectorcraft_brush::Colorization::HueShift { key } = brush.kind.colorization() else { panic!("not Hue Shift") };
vec![
first_fill(&d.graph_designs.iter().find(|g| g.name == "Bar").unwrap().art),
first_fill(brush.art()[0]),
key,
d.graphic_style("Red").unwrap().appearance.fill_paint().color().unwrap(),
first_fill(&d.node(masked).unwrap().extras().mask.as_deref().unwrap().art),
]
}
/// Document Color Mode converts the colors of graph designs, of the art of brushes (with a Hue
/// Shift brush's key color), of graphic styles and of opacity-mask art as it converts the
/// layers' art, tints of global swatches included, in one undo step.
#[test]
fn document_color_mode_converts_art_outside_the_layers() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
let hue_shift = json!({"colorization": {"method": "hueShift"}});
for (cmd, p, paint) in [
("graph.design", json!({"new": "Bar"}), json!({"swatch": "Tone", "tint": 40})),
("brush.new", json!({"type": "art", "name": "Holder", "params": hue_shift}), json!({"color": "#ff0000"})),
("graphicStyle.new", json!({"name": "Red"}), json!({"color": "#ff0000"})),
] {
let id = rect(&mut s);
let mut paint = paint;
paint["ids"] = json!([id.0]);
run(&mut s, "paint.setFill", paint);
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [id.0]}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, cmd, p);
run(&mut s, "edit.clear", json!({"ids": [id.0]}));
}
let masked = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [masked.0]}));
let m = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#808080", "ids": [m.0]}));
run(&mut s, "select.set", json!({"ids": [masked.0, m.0]}));
run(&mut s, "transparency.makeOpacityMask", json!({"clip": true, "invert": false}));
let before = colors_outside_the_layers(&s, masked);
assert!(before.iter().all(|c| matches!(c, Color::Rgb { .. })), "{before:?}");
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
let after = colors_outside_the_layers(&s, masked);
assert!(after.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{after:?}");
// The same red converts to the same inks wherever it is.
let red = first_fill(doc(&s).node(masked).unwrap());
assert_eq!(after[1..4], [red; 3]);
// A tint of a global swatch is the converted swatch's color at that tint.
let tone = doc(&s).swatch("Tone").unwrap().paint.color().unwrap();
assert_eq!(after[0], tone.tinted(0.4));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(colors_outside_the_layers(&s, masked), before);
}
/// A Hue Shift brush whose art is painted with a tint of a global swatch keeps its key color equal
/// to that art color after Document Color Mode.
#[test]
fn document_color_mode_keeps_a_hue_shift_key_on_its_tinted_art() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Tone", "tint": 40, "ids": [id.0]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [id.0]}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Holder", "params": {"colorization": {"method": "hueShift"}}}));
run(&mut s, "edit.clear", json!({"ids": [id.0]}));
let key_and_art = |s: &Session| {
let brush = vectorcraft_brush::find(doc(s), "Holder").unwrap();
let vectorcraft_brush::Colorization::HueShift { key } = brush.kind.colorization() else { panic!("not Hue Shift") };
(key, first_fill(brush.art()[0]))
};
let (key, art) = key_and_art(&s);
assert_eq!(key, art);
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
let (key, art) = key_and_art(&s);
assert!(matches!(art, Color::Cmyk { .. }), "{art:?}");
assert_eq!(key, art);
}
/// The reply's `changed` counts the colors of the document's art; the colors of brush art and
/// graphic styles convert without being counted.
#[test]
fn document_color_mode_counts_the_colors_of_the_art_only() {
let changed = |library: bool| {
let mut s = session();
if library {
for (cmd, p) in [("brush.new", json!({"type": "art", "name": "Holder"})), ("graphicStyle.new", json!({"name": "Red"}))] {
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [id.0]}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, cmd, p);
run(&mut s, "edit.clear", json!({"ids": [id.0]}));
}
}
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [id.0]}));
let r = run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
if library {
let brush = vectorcraft_brush::find(doc(&s), "Holder").unwrap();
assert!(matches!(first_fill(brush.art()[0]), Color::Cmyk { .. }));
}
r["changed"].as_u64().unwrap()
};
let in_art = changed(false);
assert!(in_art > 0);
assert_eq!(changed(true), in_art);
}
/// Document Color Mode chosen while a pattern is being edited also converts the tile that pattern
/// editing's Cancel puts back.
#[test]
fn document_color_mode_converts_the_tile_that_pattern_cancel_puts_back() {
let mut s = session();
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [id.0]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [id.0]}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
let pattern = run(&mut s, "object.pattern.make", json!({"edit": false}))["name"].as_str().unwrap().to_string();
run(&mut s, "object.pattern.edit", json!({"name": pattern}));
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
run(&mut s, "object.pattern.cancel", json!({}));
let red = first_fill(doc(&s).node(id).unwrap());
assert!(matches!(red, Color::Cmyk { .. }), "{red:?}");
let tile: Vec<Color> = doc(&s).pattern(&pattern).unwrap().art.iter().map(|n| first_fill(n)).collect();
assert_eq!(tile, [red]);
}
#[test]
fn grouped_spot_swatches_print_on_their_own_plate() {
let mut s = session();
@@ -383,3 +528,203 @@ fn global_swatch_edits_reach_opacity_mask_art() {
run(&mut s, "edit.undo", json!({}));
assert_eq!(mask_fill(&s).color(), Some(Color::rgb(1.0, 1.0, 1.0)));
}
/// The fills of graph design "Bar" and of the art of brush "Holder", as `place: color, link`.
fn fills_outside_the_layers(s: &Session) -> Vec<String> {
let d = doc(s);
let mut out = vec![];
let mut tree = |place: &str, n: &vectorcraft_doc::Node| {
n.walk(&mut |m| {
if let Paint::Solid { color, swatch, .. } = m.appearance.fill_paint() {
out.push(format!("{place}: {}, {}", color.to_hex(), swatch.as_deref().unwrap_or("-")));
}
})
};
tree("design", &d.graph_designs.iter().find(|g| g.name == "Bar").unwrap().art);
vectorcraft_brush::find(d, "Holder").unwrap().art().into_iter().for_each(|n| tree("brush art", n));
out
}
/// A global swatch edit that recolors a Hue Shift brush's key color in its art moves the key to the
/// new color, so strokes still paint that art with the stroke color.
#[test]
fn global_swatch_edits_move_a_hue_shift_key() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Tone", "ids": [id.0]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [id.0]}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Key", "ids": [id.0], "params": {"colorization": {"method": "hueShift"}}}));
let key = |s: &mut Session| run(s, "brush.get", json!({"name": "Key"}))["colorization"]["key"].clone();
let (red, blue) = (json!(Color::rgb(1.0, 0.0, 0.0)), json!(Color::rgb(0.0, 0.0, 1.0)));
assert_eq!(key(&mut s), red);
run(&mut s, "swatch.edit", json!({"name": "Tone", "color": "#0000ff"}));
assert_eq!(key(&mut s), blue);
run(&mut s, "edit.undo", json!({}));
assert_eq!(key(&mut s), red);
// A paint in the key color that only an opacity mask uses leaves the key where it is.
run(&mut s, "swatch.new", json!({"name": "MaskTone", "color": "#ff0000", "global": true}));
let obj = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [obj.0]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [obj.0]}));
let m = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "MaskTone", "ids": [m.0]}));
run(&mut s, "select.set", json!({"ids": [obj.0, m.0]}));
run(&mut s, "transparency.makeOpacityMask", json!({"clip": true, "invert": false}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Masked", "ids": [obj.0], "params": {"colorization": {"method": "hueShift"}}}));
let masked = |s: &mut Session| run(s, "brush.get", json!({"name": "Masked"}))["colorization"]["key"].clone();
assert_eq!(masked(&mut s), red);
run(&mut s, "swatch.edit", json!({"name": "MaskTone", "color": "#0000ff"}));
assert_eq!(masked(&mut s), red);
// With the art and its mask on one swatch, the key takes the art's new color, not the mask's.
run(&mut s, "swatch.new", json!({"name": "Both", "color": "#ffffff", "global": true}));
let obj = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Both", "ids": [obj.0]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [obj.0]}));
let m = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Both", "tint": 50, "ids": [m.0]}));
run(&mut s, "select.set", json!({"ids": [obj.0, m.0]}));
run(&mut s, "transparency.makeOpacityMask", json!({"clip": true, "invert": false}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Both", "ids": [obj.0], "params": {"colorization": {"method": "hueShift"}}}));
run(&mut s, "swatch.edit", json!({"name": "Both", "color": "#0000ff"}));
assert_eq!(run(&mut s, "brush.get", json!({"name": "Both"}))["colorization"]["key"], blue);
}
/// A global swatch edit that recolors brush art keeps the stored library entries that do not parse
/// as brushes.
#[test]
fn global_swatch_edits_keep_unreadable_brush_entries() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Tone", "ids": [id.0]}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Holder", "ids": [id.0]}));
let junk = json!({"name": "Unreadable", "kind": 7});
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let Some(Value::Array(entries)) = doc.unknown.get_mut(vectorcraft_brush::DOC_KEY) else { panic!("no stored brushes") };
entries.push(junk.clone());
run(&mut s, "swatch.edit", json!({"name": "Tone", "color": "#0000ff"}));
let stored = &s.doc().unwrap().doc.unknown[vectorcraft_brush::DOC_KEY];
assert!(stored.as_array().is_some_and(|a| a.contains(&junk)), "{stored}");
assert!(vectorcraft_brush::find(&s.doc().unwrap().doc, "Holder").is_some());
}
/// A global swatch edit that recolors brush art keeps the fields of stored brush entries that the
/// brush definition does not read, both on the brush it recolors and on the brushes it leaves alone,
/// and inside the art too. A swatch delete that unlinks the art drops the link and keeps those fields.
#[test]
fn global_swatch_edits_keep_unread_brush_fields() {
// Adds `"extra": 8` to every object under `v` that links a swatch.
fn tag_links(v: &mut Value) {
match v {
Value::Object(o) => {
if o.contains_key("swatch") {
o.insert("extra".into(), json!(8));
}
o.values_mut().for_each(tag_links);
}
Value::Array(a) => a.iter_mut().for_each(tag_links),
_ => {}
}
}
// The objects under `v` that carry `"extra": 8`.
fn tagged(v: &Value) -> Vec<&Value> {
match v {
Value::Object(o) => o.get("extra").filter(|e| **e == json!(8)).map(|_| v).into_iter().chain(o.values().flat_map(tagged)).collect(),
Value::Array(a) => a.iter().flat_map(tagged).collect(),
_ => vec![],
}
}
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Tone", "ids": [id.0]}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Holder", "ids": [id.0]}));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let Some(Value::Array(entries)) = doc.unknown.get_mut(vectorcraft_brush::DOC_KEY) else { panic!("no stored brushes") };
for e in entries.iter_mut() {
if let Some(o) = e.as_object_mut() {
o.insert("extra".into(), json!(7));
}
tag_links(e);
}
let links = tagged(&doc.unknown[vectorcraft_brush::DOC_KEY]).len();
assert!(links > 0, "{}", doc.unknown[vectorcraft_brush::DOC_KEY]);
run(&mut s, "swatch.edit", json!({"name": "Tone", "color": "#0000ff"}));
let stored = &s.doc().unwrap().doc.unknown[vectorcraft_brush::DOC_KEY];
let entries = stored.as_array().map(Vec::as_slice).unwrap_or_default();
assert!(entries.len() > 1, "{stored}");
assert!(entries.iter().all(|e| e["extra"] == json!(7)), "{stored}");
assert_eq!(tagged(stored).len(), links, "{stored}");
let holder = vectorcraft_brush::find(&s.doc().unwrap().doc, "Holder").unwrap();
let fill = holder.art().first().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()));
assert_eq!(fill, Some(Some("#0000ff".to_string())));
run(&mut s, "swatch.delete", json!({"name": "Tone"}));
let stored = &s.doc().unwrap().doc.unknown[vectorcraft_brush::DOC_KEY];
let unlinked = tagged(stored);
assert_eq!(unlinked.len(), links, "{stored}");
assert!(unlinked.iter().all(|o| o.get("swatch").is_none()), "{stored}");
let holder = vectorcraft_brush::find(&s.doc().unwrap().doc, "Holder").unwrap();
let fill = holder.art().first().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()));
assert_eq!(fill, Some(Some("#0000ff".to_string())));
}
/// A global swatch edit, rename, delete and Default Swatches with replace change the art of graph
/// designs and brushes: the art follows the swatch's color and name, or keeps its color unlinked,
/// each in one undo step.
#[test]
fn global_swatch_edits_reach_graph_designs_and_brush_art() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
for (cmd, p) in [("graph.design", json!({"new": "Bar"})), ("brush.new", json!({"type": "art", "name": "Holder"}))] {
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Tone", "ids": [id.0]}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, cmd, p);
run(&mut s, "edit.clear", json!({"ids": [id.0]}));
}
let both = |fill: &str| vec![format!("design: {fill}"), format!("brush art: {fill}")];
assert_eq!(fills_outside_the_layers(&s), both("#ff0000, Tone"));
let undo = s.doc().unwrap().history.undo.len();
let r = run(&mut s, "swatch.edit", json!({"name": "Tone", "color": "#0000ff"}));
assert_eq!(r["relinked"], 2, "{r}");
assert_eq!(fills_outside_the_layers(&s), both("#0000ff, Tone"));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(fills_outside_the_layers(&s), both("#ff0000, Tone"));
run(&mut s, "swatch.edit", json!({"name": "Tone", "newName": "Hue"}));
assert_eq!(fills_outside_the_layers(&s), both("#ff0000, Hue"));
// Default Swatches with replace drops the links to the swatches it removes.
run(&mut s, "swatch.resetDefaults", json!({"replace": true}));
assert_eq!(fills_outside_the_layers(&s), both("#ff0000, -"));
run(&mut s, "edit.undo", json!({}));
let r = run(&mut s, "swatch.delete", json!({"name": "Hue"}));
assert_eq!(r["unlinked"], 2, "{r}");
assert_eq!(fills_outside_the_layers(&s), both("#ff0000, -"));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2);
}
/// A global swatch edited while a pattern is being edited also changes the tile that pattern
/// editing's Cancel puts back.
#[test]
fn global_swatch_edits_reach_the_tile_that_pattern_cancel_puts_back() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
let id = rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Tone", "ids": [id.0]}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
let pattern = run(&mut s, "object.pattern.make", json!({"edit": false}))["name"].as_str().unwrap().to_string();
run(&mut s, "object.pattern.edit", json!({"name": pattern}));
run(&mut s, "swatch.edit", json!({"name": "Tone", "color": "#0000ff"}));
run(&mut s, "object.pattern.cancel", json!({}));
let mut fills = vec![];
for n in &doc(&s).pattern(&pattern).unwrap().art {
n.walk(&mut |m| fills.push(m.appearance.fill_paint()));
}
assert_eq!(fills, [Paint::Solid { color: Color::rgb(0.0, 0.0, 1.0), swatch: Some("Tone".into()), tint: 1.0 }]);
}